diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 749aa797fa1..9878d8651cc 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,9 +4,6 @@ updates: directory: "/" schedule: interval: "daily" - groups: - maven: - patterns: ["*"] - package-ecosystem: "github-actions" directory: "/" diff --git a/.github/workflows/full-integration.yaml b/.github/workflows/full-integration.yaml index 57789d54a8c..c831df5ec61 100644 --- a/.github/workflows/full-integration.yaml +++ b/.github/workflows/full-integration.yaml @@ -1,6 +1,7 @@ name: full-integration on: + workflow_dispatch: schedule: - cron: '30 0 * * *' # daily at 0:30 UTC @@ -13,7 +14,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest] + os: [ubuntu-latest, windows-latest, macos-latest] steps: - name: Prepare git diff --git a/.github/workflows/verify-push.yaml b/.github/workflows/verify-push.yaml index 6c98df57073..f2a5b59d8ee 100644 --- a/.github/workflows/verify-push.yaml +++ b/.github/workflows/verify-push.yaml @@ -58,7 +58,6 @@ jobs: - contribs/railsim - contribs/roadpricing - contribs/analysis - - contribs/eventsBasedPTRouter - contribs/hybridsim - contribs/informed-mode-choice - contribs/otfvis diff --git a/benchmark/src/main/java/org/matsim/benchmark/Benchmark.java b/benchmark/src/main/java/org/matsim/benchmark/Benchmark.java index 9c11ff9f623..addf157f821 100644 --- a/benchmark/src/main/java/org/matsim/benchmark/Benchmark.java +++ b/benchmark/src/main/java/org/matsim/benchmark/Benchmark.java @@ -32,7 +32,7 @@ public class Benchmark { public static void main(String[] args) throws IOException { Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("benchmark"), "config.xml")); Controler ctl = new Controler(config); - ctl.getConfig().controler().setCreateGraphs(false); + ctl.getConfig().controller().setCreateGraphs(false); ctl.run(); } diff --git a/contribs/accessibility/pom.xml b/contribs/accessibility/pom.xml index 300f8fb1bd1..45d1f56723b 100644 --- a/contribs/accessibility/pom.xml +++ b/contribs/accessibility/pom.xml @@ -52,7 +52,7 @@ org.openstreetmap.osmosis osmosis-core - 0.48.3 + ${osmosis.version} @@ -65,7 +65,7 @@ org.openstreetmap.osmosis osmosis-xml - 0.48.3 + ${osmosis.version} org.matsim.contrib diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityComputationNairobiLandUseLocalCopy.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityComputationNairobiLandUseLocalCopy.java index ef0f7fdc022..91e6e1c72ca 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityComputationNairobiLandUseLocalCopy.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityComputationNairobiLandUseLocalCopy.java @@ -39,26 +39,26 @@ */ class AccessibilityComputationNairobiLandUseLocalCopy { public static final Logger LOG = LogManager.getLogger(AccessibilityComputationNairobiLandUseLocalCopy.class); - + public static void main(String[] args) { int tileSize_m = 500; boolean push2Geoserver = false; // Set true for run on server boolean createQGisOutput = true; // Set false for run on server - + final Config config = ConfigUtils.createConfig(new AccessibilityConfigGroup()); - + Envelope envelope = new Envelope(246000, 271000, 9853000, 9863000); // Central part of Nairobi String scenarioCRS = "EPSG:21037"; // EPSG:21037 = Arc 1960 / UTM zone 37S, for Nairobi, Kenya - + config.network().setInputFile("../nairobi/data/nairobi/input/2015-10-15_network.xml"); config.facilities().setInputFile("../nairobi/data/land_use/Nairobi_LU_2010/facilities.xml"); String runId = "ke_nairobi_landuse_hexagons_" + tileSize_m; - config.controler().setOutputDirectory("../nairobi/data/nairobi/output/" + runId + "_lcpt_par4_car_tr-7_500/"); - config.controler().setRunId(runId); - - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); - + config.controller().setOutputDirectory("../nairobi/data/nairobi/output/" + runId + "_lcpt_par4_car_tr-7_500/"); + config.controller().setRunId(runId); + + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); + AccessibilityConfigGroup acg = ConfigUtils.addOrGetModule(config, AccessibilityConfigGroup.class); acg.setAreaOfAccessibilityComputation(AreaOfAccesssibilityComputation.fromBoundingBoxHexagons); acg.setEnvelope(envelope); @@ -69,17 +69,17 @@ public static void main(String[] args) { acg.setOutputCrs(scenarioCRS); //acg.setUseParallelization(false); - + ConfigUtils.setVspDefaults(config); - + final Scenario scenario = ScenarioUtils.loadScenario(config); - + // final List activityTypes = Arrays.asList(new String[]{"educational", "commercial", "industrial", "recreational", "water_body"}); final List activityTypes = Arrays.asList(new String[]{"educational"}); final ActivityFacilities densityFacilities = AccessibilityUtils.createFacilityForEachLink(Labels.DENSITIY, scenario.getNetwork()); - + final Controler controler = new Controler(scenario); - + for (String activityType : activityTypes) { AccessibilityModule module = new AccessibilityModule(); module.setConsideredActivityType(activityType); @@ -88,17 +88,17 @@ public static void main(String[] args) { module.setCreateQGisOutput(createQGisOutput); controler.addOverridingModule(module); } - + controler.run(); - + if (createQGisOutput) { final Integer range = 9; // In the current implementation, this must always be 9 final Double lowerBound = -3.5; // (upperBound - lowerBound) ideally nicely divisible by (range - 2) final Double upperBound = 3.5; final int populationThreshold = (int) (10 / (1000/tileSize_m * 1000/tileSize_m)); // People per km^2 or roads (?) - + String osName = System.getProperty("os.name"); - String workingDirectory = config.controler().getOutputDirectory(); + String workingDirectory = config.controller().getOutputDirectory(); for (String actType : activityTypes) { String actSpecificWorkingDirectory = workingDirectory + actType + "/"; for (Modes4Accessibility mode : acg.getIsComputingMode()) { diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityComputationShutdownListener.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityComputationShutdownListener.java index a3f82abfa44..39637e1228f 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityComputationShutdownListener.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityComputationShutdownListener.java @@ -30,11 +30,10 @@ 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.Node; import org.matsim.contrib.accessibility.utils.AggregationObject; import org.matsim.contrib.accessibility.utils.ProgressBar; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.controler.events.ShutdownEvent; import org.matsim.core.controler.listener.ShutdownListener; import org.matsim.core.gbl.Gbl; @@ -58,9 +57,9 @@ final class AccessibilityComputationShutdownListener implements ShutdownListener private final ArrayList zoneDataExchangeListeners = new ArrayList<>(); private AccessibilityConfigGroup acg; - private final PlanCalcScoreConfigGroup cnScoringGroup; + private final ScoringConfigGroup cnScoringGroup; + - public AccessibilityComputationShutdownListener(Scenario scenario, ActivityFacilities measuringPoints, ActivityFacilities opportunities, String outputDirectory) { this.measuringPoints = measuringPoints; @@ -69,7 +68,7 @@ public AccessibilityComputationShutdownListener(Scenario scenario, ActivityFacil this.outputDirectory = outputDirectory; this.acg = ConfigUtils.addOrGetModule(scenario.getConfig(), AccessibilityConfigGroup.GROUP_NAME, AccessibilityConfigGroup.class); - this.cnScoringGroup = scenario.getConfig().planCalcScore(); + this.cnScoringGroup = scenario.getConfig().scoring(); if (cnScoringGroup.getOrCreateModeParams(TransportMode.car).getMarginalUtilityOfDistance() != 0.) { LOG.error("Marginal utility of distance for car different from zero, but not used in accessibility computations"); @@ -241,10 +240,10 @@ private void writeCSVFile(String adaptedOutputDirectory) { writer.writeField(facility.getCoord().getX()); writer.writeField(facility.getCoord().getY()); writer.writeField(tuple.getSecond()); - + for (String mode : getModes() ) { final double value = accessibilitiesMap.get(tuple).get(mode); - if (!Double.isNaN(value)) { + if (!Double.isNaN(value)) { writer.writeField(value) ; } else { writer.writeField(Double.NaN) ; diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityFromEvents.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityFromEvents.java index 476471ebd8c..b200e3a46f0 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityFromEvents.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityFromEvents.java @@ -58,7 +58,7 @@ private AccessibilityFromEvents( Scenario scenario, String eventsFile, List map = new LinkedHashMap<>( ) ; EventsManager events = EventsUtils.createEventsManager(); - for( String mode : scenario.getConfig().plansCalcRoute().getNetworkModes() ){ + for( String mode : scenario.getConfig().routing().getNetworkModes() ){ TravelTimeCalculator.Builder builder = new TravelTimeCalculator.Builder( scenario.getNetwork() ); builder.setCalculateLinkTravelTimes( true ); builder.setCalculateLinkToLinkTravelTimes( false ); @@ -74,7 +74,7 @@ public void run() { install( new ScenarioByInstanceModule( scenario ) ) ; install( new TripRouterModule() ) ; install( new TimeInterpretationModule() ); - for( String mode : getConfig().plansCalcRoute().getNetworkModes() ){ + for( String mode : getConfig().routing().getNetworkModes() ){ addTravelTimeBinding( mode ).toInstance( map.get(mode) ); } install( new TravelDisutilityModule() ) ; diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityModule.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityModule.java index 19c98283c02..c4677dd3fd3 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityModule.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityModule.java @@ -139,7 +139,7 @@ public ControlerListener get() { } AccessibilityUtils.assignAdditionalFacilitiesDataToMeasurePoint(measuringPoints, measurePointGeometryMap, additionalFacs); - String outputDirectory = scenario.getConfig().controler().getOutputDirectory() + "/" + activityType; + String outputDirectory = scenario.getConfig().controller().getOutputDirectory() + "/" + activityType; AccessibilityComputationShutdownListener accessibilityShutdownListener = new AccessibilityComputationShutdownListener(scenario, measuringPoints, opportunities, outputDirectory); // for (Modes4Accessibility mode : acg.getIsComputingMode()) { @@ -150,14 +150,14 @@ public ControlerListener get() { final TravelDisutilityFactory travelDisutilityFactory = travelDisutilityFactories.get(TransportMode.car); Gbl.assertNotNull(travelDisutilityFactory); calculator = new NetworkModeAccessibilityExpContributionCalculator(mode, new FreeSpeedTravelTime(), travelDisutilityFactory, scenario); - } else if ( config.plansCalcRoute().getNetworkModes().contains( mode ) ) { + } else if ( config.routing().getNetworkModes().contains( mode ) ) { final TravelTime nwModeTravelTime = travelTimes.get(mode); Gbl.assertNotNull(nwModeTravelTime); final TravelDisutilityFactory nwModeTravelDisutility = travelDisutilityFactories.get(mode); Gbl.assertNotNull( nwModeTravelDisutility ); calculator = new NetworkModeAccessibilityExpContributionCalculator(mode, nwModeTravelTime, nwModeTravelDisutility, scenario); } else if ( TransportMode.pt.equals( mode ) ){ - calculator = new SwissRailRaptorAccessibilityContributionCalculator( mode, config.planCalcScore(), scenario ); + calculator = new SwissRailRaptorAccessibilityContributionCalculator( mode, config.scoring(), scenario ); } else if ( Modes4Accessibility.matrixBasedPt.name().equals( mode ) ) { throw new RuntimeException("currently not supported because implementation not consistent with guice grapher. kai, sep'19") ; // calculator = new LeastCostPathCalculatorAccessibilityContributionCalculator( @@ -175,7 +175,7 @@ public ControlerListener get() { if ( travelDisutilityFactory==null ) { throw new RuntimeException("mode=" + mode + "; travelDisutilityFactory is null!") ; } - calculator = new TripRouterAccessibilityContributionCalculator(mode, tripRouter, config.planCalcScore(), scenario, + calculator = new TripRouterAccessibilityContributionCalculator(mode, tripRouter, config.scoring(), scenario, travelTime, travelDisutilityFactory ); } @@ -195,7 +195,7 @@ public ControlerListener get() { } Set additionalFacInfo = additionalFacs.keySet(); accessibilityShutdownListener.addFacilityDataExchangeListener(new GeoserverUpdater(acg.getOutputCrs(), - config.controler().getRunId() + "_" + activityType, measurePointGeometryMap, additionalFacInfo, + config.controller().getRunId() + "_" + activityType, measurePointGeometryMap, additionalFacInfo, outputDirectory, pushing2Geoserver, createQGisOutput)); } diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityUtils.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityUtils.java index 0de040c489c..db9adc47ccd 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityUtils.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/AccessibilityUtils.java @@ -34,7 +34,7 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.NetworkConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.gbl.Gbl; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; @@ -65,7 +65,7 @@ public static final Map, AggregationObject> aggregat // yyyy this method ignores the "capacities" of the facilities. kai, mar'14 // for now, we decided not to add "capacities" as it is not needed for current projects. dz, feb'16 - double walkSpeed_m_h = config.plansCalcRoute().getTeleportedModeSpeeds().get(TransportMode.walk) * 3600.; + double walkSpeed_m_h = config.routing().getTeleportedModeSpeeds().get(TransportMode.walk) * 3600.; AccessibilityConfigGroup acg = ConfigUtils.addOrGetModule(config, AccessibilityConfigGroup.GROUP_NAME, AccessibilityConfigGroup.class); LOG.info("Aggregating " + opportunities.getFacilities().size() + " opportunities with same nearest node..."); @@ -76,11 +76,11 @@ public static final Map, AggregationObject> aggregat double distance_m = NetworkUtils.getEuclideanDistance(opportunity.getCoord(), nearestNode.getCoord()); // in MATSim this is [utils/h]: cnScoringGroup.getTravelingWalk_utils_hr() - cnScoringGroup.getPerforming_utils_hr() - double walkBetaTT_utils_h = config.planCalcScore().getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - - config.planCalcScore().getPerforming_utils_hr(); // default values: -12 = (-6.) - (6.) + double walkBetaTT_utils_h = config.scoring().getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() + - config.scoring().getPerforming_utils_hr(); // default values: -12 = (-6.) - (6.) double VjkWalkTravelTime = walkBetaTT_utils_h * (distance_m / walkSpeed_m_h); - double expVjk = Math.exp(config.planCalcScore().getBrainExpBeta() * VjkWalkTravelTime); + double expVjk = Math.exp(config.scoring().getBrainExpBeta() * VjkWalkTravelTime); // add Vjk to sum AggregationObject jco = opportunityClusterMap.get(nearestNode.getId()); // Why "jco"? @@ -142,16 +142,16 @@ public static Network createModeSpecificSubNetwork(Network network, String mode, } - public static double getModeSpecificConstantForAccessibilities(String mode, PlanCalcScoreConfigGroup planCalcScoreConfigGroup) { + public static double getModeSpecificConstantForAccessibilities(String mode, ScoringConfigGroup scoringConfigGroup) { double modeSpecificConstant; if (mode.equals(Modes4Accessibility.freespeed.name())) { - modeSpecificConstant = planCalcScoreConfigGroup.getModes().get(TransportMode.car).getConstant(); + modeSpecificConstant = scoringConfigGroup.getModes().get(TransportMode.car).getConstant(); } else { - modeSpecificConstant = planCalcScoreConfigGroup.getModes().get(mode).getConstant(); + modeSpecificConstant = scoringConfigGroup.getModes().get(mode).getConstant(); } return modeSpecificConstant; } - + /** * Collects all facilities of a given type that have been loaded to the sceanrio. */ @@ -191,8 +191,8 @@ public static List collectAllFacilityOptionTypes(Scenario scenario) { public static void combineDifferentActivityOptionTypes(final Scenario scenario, String combinedType, final List activityOptionsToBeIncluded) { - ActivityOption markerOption = new ActivityOptionImpl(combinedType); - + ActivityOption markerOption = new ActivityOptionImpl(combinedType); + // Memorize all facilities that have certain activity options in a activity facilities container final ActivityFacilities consideredFacilities = FacilitiesUtils.createActivityFacilities(); for (ActivityFacility facility : scenario.getActivityFacilities().getFacilities().values()) { @@ -205,7 +205,7 @@ public static void combineDifferentActivityOptionTypes(final Scenario scenario, } } } - + // Add marker option to facilities to be considered for (ActivityFacility facility : consideredFacilities.getFacilities().values()) { facility.addActivityOption(markerOption); @@ -227,16 +227,16 @@ public static final ActivityFacilities createFacilityForEachLink(String facility public static final ActivityFacilities createFacilityFromBuildingShapefile(String shapeFileName, String identifierCaption, String numberOfHouseholdsCaption) { ShapeFileReader shapeFileReader = new ShapeFileReader(); Collection features = shapeFileReader.readFileAndInitialize(shapeFileName); - + ActivityFacilities facilities = FacilitiesUtils.createActivityFacilities("DensitiyFacilities"); ActivityFacilitiesFactory aff = facilities.getFactory(); - + for (SimpleFeature feature : features) { String featureId = (String) feature.getAttribute(identifierCaption); Integer numberOfHouseholds = Integer.parseInt((String) feature.getAttribute(numberOfHouseholdsCaption)); Geometry geometry = (Geometry) feature.getDefaultGeometry(); Coord coord = CoordUtils.createCoord(geometry.getCentroid().getX(), geometry.getCentroid().getY()); - + for (int i = 0; i < numberOfHouseholds; i++) { ActivityFacility facility = aff.createActivityFacility(Id.create(featureId + "_" + i, ActivityFacility.class), coord); facilities.addActivityFacility(facility); @@ -255,7 +255,7 @@ public static ActivityFacilities createMeasuringPointsFromNetworkBounds(Network double xMax = boundingBox.getXMax(); double yMin = boundingBox.getYMin(); double yMax = boundingBox.getYMax(); - + ActivityFacilities measuringPoints = GridUtils.createGridLayerByGridSizeByBoundingBoxV2(xMin, yMin, xMax, yMax, cellSize); return measuringPoints; } @@ -263,7 +263,7 @@ public static ActivityFacilities createMeasuringPointsFromNetworkBounds(Network /** * Calculates the sum of the values of a given list. - * + * * @param valueList * @return sum */ @@ -279,7 +279,7 @@ public static double calculateSum(List valueList) { /** * Calculates Gini coefficient of the values of a given values. The Gini Coefficient is equals to the half of * the relative mean absolute difference (RMD). - * + * * @see * @see * @param valueList @@ -289,7 +289,7 @@ public static double calculateGiniCoefficient(List valueList) { int numberOfValues = valueList.size(); double sumOfValues = calculateSum(valueList); double arithmeticMean = sumOfValues / numberOfValues; - + double sumOfAbsoluteDifferences = 0.; for (double i : valueList) { for (double j : valueList) { @@ -310,24 +310,24 @@ public static double calculateGiniCoefficient(List valueList) { public static ActivityFacilities createFacilitiesFromPlans(Population population) { ActivityFacilitiesFactory aff = new ActivityFacilitiesFactoryImpl(); ActivityFacilities facilities = FacilitiesUtils.createActivityFacilities(); - + for(Person person : population.getPersons().values()) { for(Plan plan : person.getPlans()) { Id personId = person.getId(); - + for (PlanElement planElement : plan.getPlanElements()) { if (planElement instanceof Activity) { Activity activity = (Activity) planElement; - + Coord coord= activity.getCoord(); if (coord == null) { throw new NullPointerException("Activity does not have any coordinates."); } - + String activityType = activity.getType(); - + // In case an agent visits the same activity location twice, create another activity facility with a modified ID - Integer i = 1; + Integer i = 1; Id facilityId = Id.create(activityType + "_" + personId.toString() + "_" + i.toString(), ActivityFacility.class); while (facilities.getFacilities().containsKey(facilityId)) { i++; @@ -335,7 +335,7 @@ public static ActivityFacilities createFacilitiesFromPlans(Population population } ActivityFacility facility = aff.createActivityFacility(facilityId, activity.getCoord()); - + facility.addActivityOption(aff.createActivityOption(activityType)); facilities.addActivityFacility(facility); // log.info("Created activity with option of type " + activityType + " and ID " + facilityId + "."); @@ -353,7 +353,7 @@ public static String getDate() { String monthStr = month + ""; if (month < 10) monthStr = "0" + month; - String date = cal.get(Calendar.YEAR) + "-" + String date = cal.get(Calendar.YEAR) + "-" + monthStr + "-" + cal.get(Calendar.DAY_OF_MONTH); return date; } @@ -363,16 +363,16 @@ public static void assignAdditionalFacilitiesDataToMeasurePoint(ActivityFaciliti Map additionalFacilityData) { LOG.info("Start assigning additional facilities data to measure point."); GeometryFactory geometryFactory = new GeometryFactory(); - + for (ActivityFacilities additionalDataFacilities : additionalFacilityData.values()) { // Iterate over all additional data collections String additionalDataName = additionalDataFacilities.getName(); int additionalDataFacilitiesToAssign = additionalDataFacilities.getFacilities().size(); - + for (Id measurePointId : measurePoints.getFacilities().keySet()) { // Iterate over all measure points ActivityFacility measurePoint = measurePoints.getFacilities().get(measurePointId); measurePoint.getAttributes().putAttribute(additionalDataName, 0); Geometry geometry = measurePointGeometryMap.get(measurePointId); - + for (ActivityFacility facility : additionalDataFacilities.getFacilities().values()) { // Iterate over additional-data facilities Point point = geometryFactory.createPoint(new Coordinate(facility.getCoord().getX(), facility.getCoord().getY())); if (geometry.contains(point)) { diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/ConstantSpeedAccessibilityExpContributionCalculator.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/ConstantSpeedAccessibilityExpContributionCalculator.java index 329155e30e4..90179912f8d 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/ConstantSpeedAccessibilityExpContributionCalculator.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/ConstantSpeedAccessibilityExpContributionCalculator.java @@ -29,7 +29,7 @@ import org.matsim.contrib.accessibility.utils.Distances; import org.matsim.contrib.accessibility.utils.NetworkUtil; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; @@ -54,14 +54,14 @@ final class ConstantSpeedAccessibilityExpContributionCalculator implements Acces // private Network network; private Network subNetwork; private Scenario scenario; - + private double logitScaleParameter; - + private double betaModeTT; // in MATSim this is [utils/h]: cnScoringGroup.getTravelingBike_utils_hr() - cnScoringGroup.getPerforming_utils_hr() private double betaModeTD; // in MATSim this is 0 !!! since getMonetaryDistanceCostRateBike doesn't exist: private double constMode; private double modeSpeed_m_h = -1; - + private double betaWalkTT; private double betaWalkTD; private double walkSpeed_m_h; @@ -77,27 +77,27 @@ public ConstantSpeedAccessibilityExpContributionCalculator(final String mode, fi this.scenario = scenario; this.config = scenario.getConfig(); - final PlanCalcScoreConfigGroup planCalcScoreConfigGroup = config.planCalcScore() ; + final ScoringConfigGroup scoringConfigGroup = config.scoring() ; - if (planCalcScoreConfigGroup.getOrCreateModeParams(mode).getMonetaryDistanceRate() != 0.) { + if (scoringConfigGroup.getOrCreateModeParams(mode).getMonetaryDistanceRate() != 0.) { LOG.error("Monetary distance cost rate for " + mode + " different from zero, but not used in accessibility computations"); } - logitScaleParameter = planCalcScoreConfigGroup.getBrainExpBeta(); + logitScaleParameter = scoringConfigGroup.getBrainExpBeta(); - if (config.plansCalcRoute().getTeleportedModeSpeeds().get(mode) == null) { + if (config.routing().getTeleportedModeSpeeds().get(mode) == null) { LOG.error("No teleported mode speed for mode " + mode + " set."); } - this.modeSpeed_m_h = config.plansCalcRoute().getTeleportedModeSpeeds().get(mode) * 3600.; + this.modeSpeed_m_h = config.routing().getTeleportedModeSpeeds().get(mode) * 3600.; - final PlanCalcScoreConfigGroup.ModeParams modeParams = planCalcScoreConfigGroup.getOrCreateModeParams(mode); - betaModeTT = modeParams.getMarginalUtilityOfTraveling() - planCalcScoreConfigGroup.getPerforming_utils_hr(); + final ScoringConfigGroup.ModeParams modeParams = scoringConfigGroup.getOrCreateModeParams(mode); + betaModeTT = modeParams.getMarginalUtilityOfTraveling() - scoringConfigGroup.getPerforming_utils_hr(); betaModeTD = modeParams.getMarginalUtilityOfDistance(); constMode = modeParams.getConstant(); - betaWalkTT = planCalcScoreConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - planCalcScoreConfigGroup.getPerforming_utils_hr(); - betaWalkTD = planCalcScoreConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfDistance(); - this.walkSpeed_m_h = config.plansCalcRoute().getTeleportedModeSpeeds().get(TransportMode.walk) * 3600; + betaWalkTT = scoringConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - scoringConfigGroup.getPerforming_utils_hr(); + betaWalkTD = scoringConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfDistance(); + this.walkSpeed_m_h = config.routing().getTeleportedModeSpeeds().get(TransportMode.walk) * 3600; } @@ -124,14 +124,14 @@ public void initialize(ActivityFacilities measuringPoints, ActivityFacilities op } - + @Override public void notifyNewOriginNode(Id fromNodeId, Double departureTime) { this.fromNode = subNetwork.getNodes().get(fromNodeId); this.lcptTravelDistance.calculate(subNetwork, fromNode, departureTime); } - + @Override public double computeContributionOfOpportunity(ActivityFacility origin, Map, AggregationObject> aggregatedOpportunities, Double departureTime) { diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/LeastCostPathCalculatorAccessibilityContributionCalculator.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/LeastCostPathCalculatorAccessibilityContributionCalculator.java index 74dbdfeffa2..ee526dafc6d 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/LeastCostPathCalculatorAccessibilityContributionCalculator.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/LeastCostPathCalculatorAccessibilityContributionCalculator.java @@ -5,7 +5,7 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Node; import org.matsim.contrib.accessibility.utils.AggregationObject; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.facilities.ActivityFacilities; import org.matsim.facilities.ActivityFacility; @@ -18,7 +18,7 @@ */ final class LeastCostPathCalculatorAccessibilityContributionCalculator implements AccessibilityContributionCalculator { private final LeastCostPathCalculator leastCostPathCalculator; - private final PlanCalcScoreConfigGroup planCalcScoreConfigGroup; + private final ScoringConfigGroup scoringConfigGroup; private Node fromNode; private Double departureTime; private Scenario scenario; @@ -27,8 +27,8 @@ final class LeastCostPathCalculatorAccessibilityContributionCalculator implement Map, AggregationObject> aggregatedOpportunities; - public LeastCostPathCalculatorAccessibilityContributionCalculator(PlanCalcScoreConfigGroup planCalcScoreConfigGroup, LeastCostPathCalculator leastCostPathCalculator, Scenario scenario) { - this.planCalcScoreConfigGroup = planCalcScoreConfigGroup; + public LeastCostPathCalculatorAccessibilityContributionCalculator(ScoringConfigGroup scoringConfigGroup, LeastCostPathCalculator leastCostPathCalculator, Scenario scenario) { + this.scoringConfigGroup = scoringConfigGroup; this.leastCostPathCalculator = leastCostPathCalculator; this.scenario = scenario; } @@ -55,7 +55,7 @@ public double computeContributionOfOpportunity(ActivityFacility origin, for (final AggregationObject destination : aggregatedOpportunities.values()) { LeastCostPathCalculator.Path path = leastCostPathCalculator.calcLeastCostPath(fromNode, (Node) destination.getNearestBasicLocation(), departureTime, null, null); - expSum += destination.getSum() * Math.exp(planCalcScoreConfigGroup.getBrainExpBeta() * path.travelCost); + expSum += destination.getSum() * Math.exp(scoringConfigGroup.getBrainExpBeta() * path.travelCost); } return expSum; } @@ -64,7 +64,7 @@ public double computeContributionOfOpportunity(ActivityFacility origin, @Override public LeastCostPathCalculatorAccessibilityContributionCalculator duplicate() { LeastCostPathCalculatorAccessibilityContributionCalculator leastCostPathCalculatorAccessibilityContributionCalculator = - new LeastCostPathCalculatorAccessibilityContributionCalculator(this.planCalcScoreConfigGroup, this.leastCostPathCalculator, this.scenario); + new LeastCostPathCalculatorAccessibilityContributionCalculator(this.scoringConfigGroup, this.leastCostPathCalculator, this.scenario); return leastCostPathCalculatorAccessibilityContributionCalculator; } diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/NetworkModeAccessibilityExpContributionCalculator.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/NetworkModeAccessibilityExpContributionCalculator.java index cfaf0906478..ff5aee3d9fa 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/NetworkModeAccessibilityExpContributionCalculator.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/NetworkModeAccessibilityExpContributionCalculator.java @@ -12,7 +12,7 @@ import org.matsim.contrib.accessibility.utils.*; import org.matsim.contrib.roadpricing.RoadPricingScheme; import org.matsim.core.config.groups.NetworkConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.gbl.Gbl; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; @@ -40,7 +40,7 @@ final class NetworkModeAccessibilityExpContributionCalculator implements Accessi private final Scenario scenario; private final TravelDisutility travelDisutility; - private final PlanCalcScoreConfigGroup planCalcScoreConfigGroup; + private final ScoringConfigGroup scoringConfigGroup; private final NetworkConfigGroup networkConfigGroup; private Network subNetwork; @@ -68,7 +68,7 @@ public NetworkModeAccessibilityExpContributionCalculator(String mode, final Trav Gbl.assertNotNull(travelDisutilityFactory); this.travelDisutility = travelDisutilityFactory.createTravelDisutility(travelTime); - planCalcScoreConfigGroup = scenario.getConfig().planCalcScore(); + scoringConfigGroup = scenario.getConfig().scoring(); networkConfigGroup = scenario.getConfig().network(); RoadPricingScheme scheme = (RoadPricingScheme) scenario.getScenarioElement( RoadPricingScheme.ELEMENT_NAME ); @@ -78,9 +78,9 @@ public NetworkModeAccessibilityExpContributionCalculator(String mode, final Trav //FastMultiNodeDijkstraFactory fastMultiNodeDijkstraFactory = new FastMultiNodeDijkstraFactory(true); //this.multiNodePathCalculator = (MultiNodePathCalculator) fastMultiNodeDijkstraFactory.createPathCalculator(network, travelDisutility, travelTime); - betaWalkTT = planCalcScoreConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - planCalcScoreConfigGroup.getPerforming_utils_hr(); + betaWalkTT = scoringConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - scoringConfigGroup.getPerforming_utils_hr(); - this.walkSpeed_m_s = scenario.getConfig().plansCalcRoute().getTeleportedModeSpeeds().get(TransportMode.walk); + this.walkSpeed_m_s = scenario.getConfig().routing().getTeleportedModeSpeeds().get(TransportMode.walk); } @@ -137,7 +137,7 @@ public double computeContributionOfOpportunity(ActivityFacility origin, double congestedCarUtilityRoad2Node = -travelDisutility.getLinkTravelDisutility(nearestLink, departureTime, null, null) * distanceFraction; // Combine all utility components (using the identity: exp(a+b) = exp(a) * exp(b)) - double modeSpecificConstant = AccessibilityUtils.getModeSpecificConstantForAccessibilities(mode, planCalcScoreConfigGroup); + double modeSpecificConstant = AccessibilityUtils.getModeSpecificConstantForAccessibilities(mode, scoringConfigGroup); for (final AggregationObject destination : aggregatedOpportunities.values()) { @@ -151,7 +151,7 @@ public double computeContributionOfOpportunity(ActivityFacility origin, // Pre-computed effect of all opportunities reachable from destination network node double sumExpVjkWalk = destination.getSum(); - expSum += Math.exp(this.planCalcScoreConfigGroup.getBrainExpBeta() * (walkUtilityMeasuringPoint2Road + modeSpecificConstant + expSum += Math.exp(this.scoringConfigGroup.getBrainExpBeta() * (walkUtilityMeasuringPoint2Road + modeSpecificConstant + congestedCarUtilityRoad2Node + congestedCarUtility)) * sumExpVjkWalk; } return expSum; diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/SwissRailRaptorAccessibilityContributionCalculator.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/SwissRailRaptorAccessibilityContributionCalculator.java index b64c6fa7b4e..6fcd4466276 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/SwissRailRaptorAccessibilityContributionCalculator.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/SwissRailRaptorAccessibilityContributionCalculator.java @@ -25,7 +25,7 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.contrib.accessibility.utils.AggregationObject; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.gbl.Gbl; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.facilities.*; @@ -44,7 +44,7 @@ class SwissRailRaptorAccessibilityContributionCalculator implements Accessibilit private static final Logger LOG = LogManager.getLogger( SwissRailRaptorAccessibilityContributionCalculator.class ); private SwissRailRaptor raptor; private String mode; - private PlanCalcScoreConfigGroup planCalcScoreConfigGroup; + private ScoringConfigGroup scoringConfigGroup; private Scenario scenario; Map, ArrayList> aggregatedMeasurePoints; @@ -58,7 +58,7 @@ class SwissRailRaptorAccessibilityContributionCalculator implements Accessibilit Map, Collection> stopsPerAggregatedOpportunity = new LinkedHashMap<>(); - public SwissRailRaptorAccessibilityContributionCalculator(String mode, PlanCalcScoreConfigGroup planCalcScoreConfigGroup, Scenario scenario) { + public SwissRailRaptorAccessibilityContributionCalculator(String mode, ScoringConfigGroup scoringConfigGroup, Scenario scenario) { this.mode = mode; TransitSchedule schedule = scenario.getTransitSchedule(); @@ -69,12 +69,12 @@ public SwissRailRaptorAccessibilityContributionCalculator(String mode, PlanCalcS this.raptorData = SwissRailRaptorData.create(schedule, null, raptorConfig, ptNetwork, null); this.raptor = new SwissRailRaptor.Builder(raptorData, scenario.getConfig()).build(); - this.planCalcScoreConfigGroup = planCalcScoreConfigGroup; + this.scoringConfigGroup = scoringConfigGroup; this.scenario = scenario; - this.betaWalkTT = planCalcScoreConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - planCalcScoreConfigGroup.getPerforming_utils_hr(); + this.betaWalkTT = scoringConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - scoringConfigGroup.getPerforming_utils_hr(); - this.walkSpeed_m_h = scenario.getConfig().plansCalcRoute().getTeleportedModeSpeeds().get(TransportMode.walk) * 3600.; + this.walkSpeed_m_h = scenario.getConfig().routing().getTeleportedModeSpeeds().get(TransportMode.walk) * 3600.; } @@ -167,8 +167,8 @@ public double computeContributionOfOpportunity(ActivityFacility origin, //check whether direct walk time is cheaper travelCost = Math.min(travelCost, directWalkCost); - double modeSpecificConstant = AccessibilityUtils.getModeSpecificConstantForAccessibilities(mode, planCalcScoreConfigGroup); - expSum += Math.exp(this.planCalcScoreConfigGroup.getBrainExpBeta() * (-travelCost + modeSpecificConstant)); + double modeSpecificConstant = AccessibilityUtils.getModeSpecificConstantForAccessibilities(mode, scoringConfigGroup); + expSum += Math.exp(this.scoringConfigGroup.getBrainExpBeta() * (-travelCost + modeSpecificConstant)); } return expSum; } @@ -177,7 +177,7 @@ public double computeContributionOfOpportunity(ActivityFacility origin, @Override public SwissRailRaptorAccessibilityContributionCalculator duplicate() { SwissRailRaptorAccessibilityContributionCalculator swissRailRaptorAccessibilityContributionCalculator = - new SwissRailRaptorAccessibilityContributionCalculator(this.mode, this.planCalcScoreConfigGroup, this.scenario); + new SwissRailRaptorAccessibilityContributionCalculator(this.mode, this.scoringConfigGroup, this.scenario); swissRailRaptorAccessibilityContributionCalculator.aggregatedMeasurePoints = this.aggregatedMeasurePoints; swissRailRaptorAccessibilityContributionCalculator.aggregatedOpportunities = this.aggregatedOpportunities; swissRailRaptorAccessibilityContributionCalculator.stopsPerAggregatedOpportunity = this.stopsPerAggregatedOpportunity; diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/TravelTimeBasedTravelDisutility.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/TravelTimeBasedTravelDisutility.java index 34ee8375753..6a70a5911fa 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/TravelTimeBasedTravelDisutility.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/TravelTimeBasedTravelDisutility.java @@ -18,30 +18,30 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.accessibility; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; import org.matsim.vehicles.Vehicle; /** * A simple cost calculator which only respects time to calculate generalized costs - * This is based on org.matsim.core.router.costcalculators.TravelTimeAndDistanceBasedTravelDisutility + * This is based on org.matsim.core.router.costcalculators.TravelTimeAndDistanceBasedTravelDisutility * * @author mrieser, thomas */ class TravelTimeBasedTravelDisutility implements TravelDisutility{ - + protected final TravelTime timeCalculator; private final double marginalCostOfTime; - public TravelTimeBasedTravelDisutility(final TravelTime timeCalculator, PlanCalcScoreConfigGroup cnScoringGroup) { + public TravelTimeBasedTravelDisutility(final TravelTime timeCalculator, ScoringConfigGroup cnScoringGroup) { this.timeCalculator = timeCalculator; /* Usually, the travel-utility should be negative (it's a disutility) * but the cost should be positive. Thus negate the utility. diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/TripRouterAccessibilityContributionCalculator.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/TripRouterAccessibilityContributionCalculator.java index 0f3dece8928..2f027d9863c 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/TripRouterAccessibilityContributionCalculator.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/TripRouterAccessibilityContributionCalculator.java @@ -38,7 +38,7 @@ import org.matsim.contrib.accessibility.utils.Distances; import org.matsim.contrib.accessibility.utils.NetworkUtil; import org.matsim.core.config.groups.NetworkConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.gbl.Gbl; import org.matsim.core.network.NetworkUtils; import org.matsim.core.router.TripRouter; @@ -60,7 +60,7 @@ class TripRouterAccessibilityContributionCalculator implements AccessibilityCont private static final Logger LOG = LogManager.getLogger( TripRouterAccessibilityContributionCalculator.class ); private TripRouter tripRouter ; private String mode; - private PlanCalcScoreConfigGroup planCalcScoreConfigGroup; + private ScoringConfigGroup scoringConfigGroup; private NetworkConfigGroup networkConfigGroup; private Scenario scenario; @@ -79,18 +79,18 @@ class TripRouterAccessibilityContributionCalculator implements AccessibilityCont private final TravelTime travelTime; - public TripRouterAccessibilityContributionCalculator(String mode, TripRouter tripRouter, PlanCalcScoreConfigGroup planCalcScoreConfigGroup, Scenario scenario, - TravelTime travelTime, TravelDisutilityFactory travelDisutilityFactory) { + public TripRouterAccessibilityContributionCalculator(String mode, TripRouter tripRouter, ScoringConfigGroup scoringConfigGroup, Scenario scenario, + TravelTime travelTime, TravelDisutilityFactory travelDisutilityFactory) { LOG.warn("This is currently heavliy oriented on the need of car-based computatations. Revise beofre using for other modes!"); this.mode = mode; this.tripRouter = tripRouter; - this.planCalcScoreConfigGroup = planCalcScoreConfigGroup; + this.scoringConfigGroup = scoringConfigGroup; this.networkConfigGroup = scenario.getConfig().network(); this.scenario = scenario; - betaWalkTT = planCalcScoreConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - planCalcScoreConfigGroup.getPerforming_utils_hr(); + betaWalkTT = scoringConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - scoringConfigGroup.getPerforming_utils_hr(); - this.walkSpeed_m_s = scenario.getConfig().plansCalcRoute().getTeleportedModeSpeeds().get(TransportMode.walk); + this.walkSpeed_m_s = scenario.getConfig().routing().getTeleportedModeSpeeds().get(TransportMode.walk); this.travelTime = travelTime; this.travelDisutilityFactory = travelDisutilityFactory; @@ -152,21 +152,21 @@ public double computeContributionOfOpportunity(ActivityFacility origin, // Note: The following computation where the end link length is added is only correct once the end link is removed from the route // in the NetworkRoutingModule (route.setDistance(RouteUtils.calcDistance(route, 1.0, 0.0, this.network));) - if (this.planCalcScoreConfigGroup.getModes().get(leg.getMode()).getMarginalUtilityOfDistance() != 0.) { + if (this.scoringConfigGroup.getModes().get(leg.getMode()).getMarginalUtilityOfDistance() != 0.) { LOG.warn("A computation including a marginal utility of distance will only be correct if the route time/distance" + "inconsistency in the NetworkRoutingModule is solved."); } - utility += (leg.getRoute().getDistance() + endLinkLength) * this.planCalcScoreConfigGroup.getModes().get(leg.getMode()).getMarginalUtilityOfDistance(); - utility += (leg.getRoute().getTravelTime().seconds() + estimatedEndLinkTT) * this.planCalcScoreConfigGroup.getModes().get(leg.getMode()).getMarginalUtilityOfTraveling() / 3600.; - utility += -(leg.getRoute().getTravelTime().seconds() + estimatedEndLinkTT) * this.planCalcScoreConfigGroup.getPerforming_utils_hr() / 3600.; + utility += (leg.getRoute().getDistance() + endLinkLength) * this.scoringConfigGroup.getModes().get(leg.getMode()).getMarginalUtilityOfDistance(); + utility += (leg.getRoute().getTravelTime().seconds() + estimatedEndLinkTT) * this.scoringConfigGroup.getModes().get(leg.getMode()).getMarginalUtilityOfTraveling() / 3600.; + utility += -(leg.getRoute().getTravelTime().seconds() + estimatedEndLinkTT) * this.scoringConfigGroup.getPerforming_utils_hr() / 3600.; } // Utility based on opportunities that are attached to destination node double sumExpVjkWalk = destination.getSum(); // exp(beta * a) * exp(beta * b) = exp(beta * (a+b)) - double modeSpecificConstant = AccessibilityUtils.getModeSpecificConstantForAccessibilities(mode, planCalcScoreConfigGroup); - expSum += Math.exp(this.planCalcScoreConfigGroup.getBrainExpBeta() * (utility + modeSpecificConstant + walkUtilityMeasuringPoint2Road + congestedCarUtilityRoad2Node)) * sumExpVjkWalk; + double modeSpecificConstant = AccessibilityUtils.getModeSpecificConstantForAccessibilities(mode, scoringConfigGroup); + expSum += Math.exp(this.scoringConfigGroup.getBrainExpBeta() * (utility + modeSpecificConstant + walkUtilityMeasuringPoint2Road + congestedCarUtilityRoad2Node)) * sumExpVjkWalk; } return expSum; @@ -176,7 +176,7 @@ public double computeContributionOfOpportunity(ActivityFacility origin, @Override public TripRouterAccessibilityContributionCalculator duplicate() { TripRouterAccessibilityContributionCalculator tripRouterAccessibilityContributionCalculator = - new TripRouterAccessibilityContributionCalculator(this.mode, this.tripRouter, this.planCalcScoreConfigGroup, + new TripRouterAccessibilityContributionCalculator(this.mode, this.tripRouter, this.scoringConfigGroup, this.scenario, this.travelTime, this.travelDisutilityFactory); tripRouterAccessibilityContributionCalculator.subNetwork = this.subNetwork; tripRouterAccessibilityContributionCalculator.aggregatedMeasurePoints = this.aggregatedMeasurePoints; diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/run/RunAccessibilityExample.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/run/RunAccessibilityExample.java index 53d94a2c1de..7db337954bd 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/run/RunAccessibilityExample.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/run/RunAccessibilityExample.java @@ -46,7 +46,7 @@ public static void main(String[] args) { throw new RuntimeException("No config.xml file provided. The config file needs to reference a network file and a facilities file.") ; } Config config = ConfigUtils.loadConfig(args[0]); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); AccessibilityConfigGroup accConfig = ConfigUtils.addOrGetModule(config, AccessibilityConfigGroup.class ) ; accConfig.setComputingAccessibilityForMode(Modes4Accessibility.freespeed, true); @@ -54,11 +54,11 @@ public static void main(String[] args) { run(scenario); // The run method is extracted so that a test can operate on it. } - + public static void run(final Scenario scenario) { List activityTypes = AccessibilityUtils.collectAllFacilityOptionTypes(scenario); LOG.info("The following activity types were found: " + activityTypes); - + Controler controler = new Controler(scenario); for (final String actType : activityTypes) { // Add an overriding module for each activity type. final AccessibilityModule module = new AccessibilityModule(); diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GnuplotScriptWriter.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GnuplotScriptWriter.java index d9c1c029634..797211edc2b 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GnuplotScriptWriter.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GnuplotScriptWriter.java @@ -34,7 +34,7 @@ */ public final class GnuplotScriptWriter { private static final Logger log = LogManager.getLogger( GnuplotScriptWriter.class ) ; - + private GnuplotScriptWriter() {} // do not instantiate public static void createGnuplotScript(Config config, List activityTypes) { @@ -49,37 +49,37 @@ public static void createGnuplotScript(Config config, List activityTypes log.error("skipping everything except freespeed for debugging purposes; remove in production code. dz, nov'14") ; continue ; } - + // the following might be made configurable if this is ever re-used: Boolean doPopulationWeightedPlot = true ; Boolean doNonPopulationWeightedPlot = true ; - - + + if (doPopulationWeightedPlot == false && doNonPopulationWeightedPlot == false) { throw new RuntimeException("At least one plot (pop-weighted or non-pop-weighted) needs to be activated."); } - + // produce gnuplot scripts try { - BufferedWriter writer = IOUtils.getBufferedWriter( config.controler().getOutputDirectory() + "/" + actType + BufferedWriter writer = IOUtils.getBufferedWriter( config.controller().getOutputDirectory() + "/" + actType + "/" + mode + "/t.gpl" ) ; // pm3d is an splot style for drawing palette-mapped 3d and 4d data as color/gray maps and surfaces (docu p.134) // To use pm3d coloring to generate a two-dimensional plot rather than a 3D surface, use set view map // or set pm3d map (p.135) writer.write("set pm3d map\n"); - + // flush { begin | center | end } writer.write("set pm3d flush begin\n") ; - + // corners2color { mean|geomean|median|min|max|c1|c2|c3|c4 } writer.write("set pm3d corners2color c1\n"); - + // The set style data command changes the default plotting style for data plots (docu p.148) // There are many plotting styles available in gnuplot. They are listed alphabetically below. The commands // set style data and set style function change the default plotting style for subsequent plot and splot // commands. (docu p.42) writer.write("set style data pm3d\n"); - + // Palette is a color storage for use by pm3d, filled color contours or polygons, color histograms, color gradient // background, and whatever it is or it will be implemented (docu p.137) // Gray-to-rgb mapping can be manually set by use of palette defined: A color gradient is defined and used @@ -87,86 +87,86 @@ public static void createGnuplotScript(Config config, List activityTypes // space [0,1]x[0,1]x[0,1]. You must specify the gray values and the corresponding RGB values between which // linear interpolation will be done (docu p.139) writer.write("set palette defined ( 0. '#ff0000', 0.82 '#ff0000', 0.86 '#00ff00', 0.9 '#0000ff', 1.0 '#0000ff' )\n"); - + // The set zrange command sets the range that will be displayed on the z axis. The zrange is used only by // splot and is ignored by plot (docu p.166) writer.write("#set zrange [-40:10]\n"); - + // The set cbrange command sets the range of values which are colored using the current palette by styles // with pm3d, with image and with palette. Values outside of the color range use color of the nearest // extreme (docu p.167) writer.write("#set cbrange [-0:10]\n"); - + // gnuplot supports many different graphics devices. Use set terminal to tell gnuplot what kind of output // to generate (docu p.152) // This terminal produces files in the Adobe Portable Document Format (PDF), useable for printing or display // with tools like Acrobat Reader (docu p.206) //writer.write("set term pdf size 25cm,20cm\n"); writer.write("set term pdf font 'Helvetica,6' size 25cm,20cm\n"); - + // The set view command sets the viewing angle for splots. It controls how the 3D coordinates of the plot are // mapped into the 2D screen space. It provides controls for both rotation and scaling of the plotted data, but // supports orthographic projections only (docu p.156) writer.write("#set view 45,30;\n"); writer.write("\n") ; - + // see docu p.137 writer.write("# set palette model HSV functions gray, 1, 1\n"); writer.write("\n"); - + // New user-defined variables and functions of one through twelve variables may be declared and used anywhere, // including on the plot command itself (docu p.30) // define minimum and maximum functions writer.write("min(a,b) = (a < b) ? a : b\n"); writer.write("max(a,b) = (a < b) ? b : a\n"); - + // define two variables writer.write("accmin=3 ; # accessibilities below this are red\n"); writer.write("accmax=9 ; # accessibilities above this are blue. max is around 12\n"); - + // define a function to determine the shade of gray. gray(acc) will have a value from 0 through 1 // Acc values equal to or below accmin lead to 0; acc values equal to or above accmax lead to 1 writer.write("gray(acc) = 2.*min( 1, max(0 , (acc-accmin)/(accmax-accmin) ) ) ;\n") ; writer.write("# I have no idea why this needs to be multiplied by 2. kai, feb'14\n") ; writer.write("\n") ; - + // consider population density // define two variables writer.write("densmax=1000 ; # 2726 is the maximum value in NMB\n") ; writer.write("maxwhite = 240 ; # 255 means that we go all the way to full white\n") ; - + while (doPopulationWeightedPlot == true || doNonPopulationWeightedPlot == true) { // define a function that gets the higher the smaller the population density // maxwhite*1 for pop dens = 0; maxwhite*0 for pop dens higher than densmax if (doPopulationWeightedPlot == true) { writer.write("val(dens) = max(0,maxwhite*(densmax-dens)/densmax) ;\n") ; - + // By default, screens are displayed to the standard output. The set output command redirects the display // to the specified file or device (docu p.132) writer.write("set out 'accessibility-pop-weighted.pdf'\n"); - + // The set title command produces a plot title that is centered at the top of the plot. set title is a special // case of set label (docu p.155) //writer.write("set title 'accessibility to " + actType + " by " + mode + " (population-weighted)'\n") ; - + doPopulationWeightedPlot = false; - + } else if (doNonPopulationWeightedPlot == true) { writer.write("val(dens) = 0. ; # unset this comment to get the non-pop-weighted version (for paper)\n"); writer.write("set out 'accessibility.pdf'\n"); //writer.write("set title 'accessibility to " + actType + " by " + mode + " (non-population-weighted)'\n") ; - + doNonPopulationWeightedPlot = false; } writer.write("\n") ; - + // define three color functions // so far not clear to me where the functions come from, dz mai14 writer.write("blue(acc,dens) = min(255, val(dens)+255*max(0,1.-2.*gray(acc)) ) ;\n") ; writer.write("green(acc,dens) = min(255, val(dens)+255*max(0,min(2.*gray(acc),2.-2.*gray(acc))) ) ;\n") ; writer.write("red(acc,dens) = min(255, val(dens)+255*max(0,2.*gray(acc)-1) ) ;\n") ; writer.write("\n") ; - + // define color function based on accessibility and population density // int(x) = integer part of x, truncated toward zero (docu p.26) // Example: rgb(r,g,b) = 65536 * int(r) + 256 * int(g) + int(b) (docu p.35) @@ -175,8 +175,8 @@ public static void createGnuplotScript(Config config, List activityTypes writer.write("\n") ; writer.write("unset colorbox ; # useless with lc rgb variable\n") ; writer.write("\n") ; // end new - - // plot csv file based on three values; first two are coordinates; third takes into account accessibility and + + // plot csv file based on three values; first two are coordinates; third takes into account accessibility and // population density and is calculated based on above-defined rgb formula // The "lc rgbcolor variable" tells the program to read RGB color information for each line in the data file. // This requires a corresponding additional column in the using specifier. The extra column is interpreted as a @@ -186,27 +186,27 @@ public static void createGnuplotScript(Config config, List activityTypes // writer.write("splot \"accessibilities.csv\" u 1:2:(rgb($3,$8)) lc rgb variable\n"); // writer.write("splot \"accessibilities.csv\" u 1:2:(rgb($3,$8)) notitle lc rgb variable\n"); } - + writer.close(); } catch (Exception ee ) { - ee.printStackTrace(); + ee.printStackTrace(); throw new RuntimeException( "writing t.gpl did not work") ; } - - + + // start running gnuplot with above-created script - + // If working on a Windows system, it is important that the environment variable PATH includes the gnuplot folder // so that gnuplot can be run from the folder where the data is stored (otherwise the relative paths won't work) String cmd = "gnuplot t.gpl"; - + // Doesn't work if root of directory is not passed - String stdoutFileName = config.controler().getOutputDirectory() + actType + "/" + mode + "/gnuplot.log"; + String stdoutFileName = config.controller().getOutputDirectory() + actType + "/" + mode + "/gnuplot.log"; // String stdoutFileName = config.controler().getOutputDirectory() + "gnuplot.log"; int timeout = 99999; - + // 4th argument = workingDirectory. Since we are working with relative paths, workingDirectory needs to be passed. - ExeRunner.run(cmd, stdoutFileName, timeout, config.controler().getOutputDirectory() + actType + "/" + mode); + ExeRunner.run(cmd, stdoutFileName, timeout, config.controller().getOutputDirectory() + actType + "/" + mode); } } } diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/LeastCostPathTreeExtended.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/LeastCostPathTreeExtended.java index 0378f9c7f71..74d2dd7d216 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/LeastCostPathTreeExtended.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/LeastCostPathTreeExtended.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.accessibility.utils; @@ -36,7 +36,7 @@ import org.matsim.contrib.matrixbasedptrouter.utils.TempDirectoryUtil; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.network.NetworkUtils; import org.matsim.core.router.util.TravelDisutility; @@ -54,17 +54,17 @@ * accumulate distance and toll separately along the route. *

* To re-iterate: This class does not lead to a different tree than the base class. - * + * * @author thomas - * + * */ public final class LeastCostPathTreeExtended extends LeastCostPathTree{ - + protected static final Logger log = LogManager.getLogger(LeastCostPathTreeExtended.class); - + private Map, NodeDataExtended> nodeDataExt = null; private RoadPricingScheme scheme = null; - + /** * constructor * @param controler Controler, to get the RoadPricingScheme if available @@ -75,13 +75,13 @@ public LeastCostPathTreeExtended(final TravelTime tt, final TravelDisutility td, } /** - * + * * @param network * @param origin * @param time */ public final void calculateExtended(final Network network, final Node origin, final double time) { - + this.nodeDataExt = new ConcurrentHashMap, NodeDataExtended>((int) (network.getNodes().size() * 1.1), 0.95f); if(this.nodeDataExt.get(origin.getId()) == null){ NodeDataExtended nde = new NodeDataExtended(); @@ -89,17 +89,17 @@ public final void calculateExtended(final Network network, final Node origin, fi nde.toll = 0.; this.nodeDataExt.put(origin.getId(), nde); } - + calculate(network, origin, time); } - + /** - * @param link - * @param currTime + * @param link + * @param currTime */ @Override protected final void additionalComputationsHook( final Link link, final double currTime ) { - + Node fromNode = link.getFromNode(); // get current distance and toll so far NodeDataExtended nde = nodeDataExt.get( fromNode.getId() ); @@ -113,10 +113,10 @@ protected final void additionalComputationsHook( final Link link, final double c if(cost != null) toll = cost.amount; } - + double visitDistance = currDistance + link.getLength(); double visitToll = currToll + toll; - + // put new nodes into nodeDataExtended Node toNode = link.getToNode(); NodeDataExtended ndeNew = this.nodeDataExt.get( toNode.getId() ); @@ -126,19 +126,19 @@ protected final void additionalComputationsHook( final Link link, final double c } ndeNew.visit(visitDistance, visitToll); } - + // //////////////////////////////////////////////////////////////////// // get methods // //////////////////////////////////////////////////////////////////// - + public final Map, NodeDataExtended> getTreeExtended() { return this.nodeDataExt; } - + // //////////////////////////////////////////////////////////////////// // inner classes // //////////////////////////////////////////////////////////////////// - + public static class NodeDataExtended { private double distance = 0.; // meter private double toll = 0.; // money @@ -161,11 +161,11 @@ public final double getToll() { return this.toll; } } - + // //////////////////////////////////////////////////////////////////// - // testing + // testing // //////////////////////////////////////////////////////////////////// - + /** * for testing * @param args @@ -173,13 +173,13 @@ public final double getToll() { public static void main(String args[]){ // create temp output dir String tmpOutputLocation = TempDirectoryUtil.createCustomTempDirectory("test"); - + // create network Network network = LeastCostPathTreeExtended.createTriangularNetwork(); // create scenario Config config = ConfigUtils.createConfig(); // set last iteration and output - ControlerConfigGroup controlerCG = (ControlerConfigGroup) config.getModule(ControlerConfigGroup.GROUP_NAME); + ControllerConfigGroup controlerCG = (ControllerConfigGroup) config.getModule(ControllerConfigGroup.GROUP_NAME); controlerCG.setLastIteration( 1 ); controlerCG.setOutputDirectory( tmpOutputLocation ); // set scenario @@ -190,7 +190,7 @@ public static void main(String args[]){ controler.run(); // init lcpte LeastCostPathTreeExtended lcpte = new LeastCostPathTreeExtended(controler.getLinkTravelTimes(), controler.createTravelDisutilityCalculator(), (RoadPricingSchemeImpl) controler.getScenario().getScenarioElement(RoadPricingScheme.ELEMENT_NAME)); - + // contains all network nodes Map, ? extends Node> networkNodesMap = network.getNodes(); Id originNodeID = Id.create(1, Node.class); @@ -201,15 +201,15 @@ public static void main(String args[]){ double disutility = lcpte.getTree().get( destinationNodeId ).getCost(); double distance = lcpte.getTreeExtended().get( destinationNodeId ).getDistance(); double toll = lcpte.getTreeExtended().get( destinationNodeId ).getToll(); - + log.info("Time = " + time); - log.info("Disutility = " + disutility); + log.info("Disutility = " + disutility); log.info("Distance = " + distance ); log.info("Toll = " + toll); - + TempDirectoryUtil.cleanUpCustomTempDirectories(); } - + /** * creating a test network * the path 1,2,4 has a total length of 1000m with a free speed travel time of 10m/s @@ -226,12 +226,12 @@ private static Network createTriangularNetwork() { * / \ * / \ *(1)-------(3)-------(4) - *(50m,0.1m/s)(50m,0.1m/s) + *(50m,0.1m/s)(50m,0.1m/s) */ MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); Network network = (Network) scenario.getNetwork(); - + // add nodes Node node1 = NetworkUtils.createAndAddNode(network, Id.create(1, Node.class), new Coord(0, 0)); Node node2 = NetworkUtils.createAndAddNode(network, Id.create(2, Node.class), new Coord(50, 100)); @@ -251,8 +251,8 @@ private static Network createTriangularNetwork() { final Node fromNode3 = node3; final Node toNode3 = node4; NetworkUtils.createAndAddLink(network,Id.create(4, Link.class), fromNode3, toNode3, 50.0, 0.1, 3600.0, (double) 1 ); - + return network; } - + } diff --git a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/AccessibilityIntegrationTest.java b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/AccessibilityIntegrationTest.java index fa3e94febc8..b843e1ae3b5 100644 --- a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/AccessibilityIntegrationTest.java +++ b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/AccessibilityIntegrationTest.java @@ -49,7 +49,7 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.FacilitiesConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -132,14 +132,14 @@ public void testWithBoundingBoxConfigFile() { acg.setUseParallelization(false); ModeParams ptParams = new ModeParams(TransportMode.transit_walk); - config.planCalcScore().addModeParams(ptParams); + config.scoring().addModeParams(ptParams); MatrixBasedPtRouterConfigGroup mbConfig = ConfigUtils.addOrGetModule(config, MatrixBasedPtRouterConfigGroup.class) ; - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setRoutingRandomness(0.); final Scenario sc = ScenarioUtils.loadScenario(config); - final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.plansCalcRoute(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; + final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.routing(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; sc.addScenarioElement(PtMatrix.NAME, ptMatrix); Controler controler = new Controler(sc); @@ -171,13 +171,13 @@ public void testWithBoundingBox() { acg.setBoundingBoxTop(max); acg.setBoundingBoxLeft(min); acg.setBoundingBoxRight(max); - - config.plansCalcRoute().setRoutingRandomness(0.); + + config.routing().setRoutingRandomness(0.); final Scenario sc = createTestScenario(config); MatrixBasedPtRouterConfigGroup mbConfig = ConfigUtils.addOrGetModule(config, MatrixBasedPtRouterConfigGroup.class ) ; - final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.plansCalcRoute(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; + final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.routing(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; sc.addScenarioElement(PtMatrix.NAME, ptMatrix); Controler controler = new Controler(sc); @@ -213,11 +213,11 @@ public void testWithBoundingBoxUsingOpportunityWeights() { acg.setUseOpportunityWeights(true); acg.setWeightExponent(2.); - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setRoutingRandomness(0.); final Scenario sc = createTestScenarioUsingOpportunityWeights(config) ; MatrixBasedPtRouterConfigGroup mbConfig = ConfigUtils.addOrGetModule(config, MatrixBasedPtRouterConfigGroup.class ) ; - final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.plansCalcRoute(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; + final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.routing(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; sc.addScenarioElement(PtMatrix.NAME, ptMatrix); Controler controler = new Controler(sc); @@ -240,11 +240,11 @@ public void install() { public void testWithExtentDeterminedByNetwork() { final Config config = createTestConfig() ; - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setRoutingRandomness(0.); final Scenario sc = createTestScenario(config) ; MatrixBasedPtRouterConfigGroup mbConfig = ConfigUtils.addOrGetModule(config, MatrixBasedPtRouterConfigGroup.class ) ; - final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.plansCalcRoute(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; + final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.routing(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; sc.addScenarioElement(PtMatrix.NAME, ptMatrix); Controler controler = new Controler(sc); @@ -280,11 +280,11 @@ public void testWithExtentDeterminedShapeFile() { // acg.setShapeFileCellBasedAccessibility(url.getPath()); // yyyyyy todo acg.setShapeFileCellBasedAccessibility(f.getAbsolutePath()); - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setRoutingRandomness(0.); final Scenario sc = createTestScenario(config) ; MatrixBasedPtRouterConfigGroup mbConfig = ConfigUtils.addOrGetModule(config, MatrixBasedPtRouterConfigGroup.class ) ; - final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.plansCalcRoute(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; + final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.routing(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; sc.addScenarioElement(PtMatrix.NAME, ptMatrix); Controler controler = new Controler(sc); @@ -329,10 +329,10 @@ public void testWithPredefinedMeasuringPoints() { final Scenario sc = createTestScenario(config) ; MatrixBasedPtRouterConfigGroup mbConfig = ConfigUtils.addOrGetModule(config, MatrixBasedPtRouterConfigGroup.class ) ; - final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.plansCalcRoute(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; + final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.routing(), BoundingBox.createBoundingBox(sc.getNetwork()), mbConfig) ; sc.addScenarioElement(PtMatrix.NAME, ptMatrix); - - config.plansCalcRoute().setRoutingRandomness(0.); + + config.routing().setRoutingRandomness(0.); Controler controler = new Controler(sc); @@ -409,7 +409,7 @@ private Config createTestConfig() { config.transit().setVehiclesFile(utils.getClassInputDirectory() + "vehicles.xml"); ModeParams ptParams = new ModeParams(TransportMode.transit_walk); - config.planCalcScore().addModeParams(ptParams); + config.scoring().addModeParams(ptParams); MatrixBasedPtRouterConfigGroup mbConfig = new MatrixBasedPtRouterConfigGroup(); mbConfig.setPtStopsInputFile(utils.getClassInputDirectory() + "ptStops.csv"); @@ -419,9 +419,9 @@ private Config createTestConfig() { mbConfig.setUsingTravelTimesAndDistances(true); config.addModule(mbConfig); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); return config; } diff --git a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/TinyAccessibilityTest.java b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/TinyAccessibilityTest.java index bb5bcc2d5e7..29283b26ede 100644 --- a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/TinyAccessibilityTest.java +++ b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/TinyAccessibilityTest.java @@ -24,7 +24,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Coord; @@ -122,11 +121,11 @@ private Config createTestConfig() { acg.setComputingAccessibilityForMode(Modes4Accessibility.freespeed, true); acg.setComputingAccessibilityForMode(Modes4Accessibility.car, true); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setRoutingRandomness(0.); return config; } diff --git a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/TinyMultimodalAccessibilityTest.java b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/TinyMultimodalAccessibilityTest.java index c2abfc8df95..bde5a98c612 100644 --- a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/TinyMultimodalAccessibilityTest.java +++ b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/TinyMultimodalAccessibilityTest.java @@ -105,9 +105,9 @@ private Config createTestConfig() { acg.setComputingAccessibilityForMode(Modes4Accessibility.pt, true); acg.setUseParallelization(false); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); return config; } diff --git a/contribs/accidents/src/main/java/org/matsim/contrib/accidents/AccidentWriter.java b/contribs/accidents/src/main/java/org/matsim/contrib/accidents/AccidentWriter.java index 7476fab2e96..8f0b09a8ae2 100644 --- a/contribs/accidents/src/main/java/org/matsim/contrib/accidents/AccidentWriter.java +++ b/contribs/accidents/src/main/java/org/matsim/contrib/accidents/AccidentWriter.java @@ -41,14 +41,14 @@ class AccidentWriter { private static String convertSecondToHHMMSSString(int nSecondTime) { return LocalTime.MIN.plusSeconds(nSecondTime).toString(); } - + public void write(Scenario scenario, IterationEndsEvent event, Map, AccidentLinkInfo> linkId2info, AnalysisEventHandler analzyer) { AccidentsConfigGroup accidentsCfg = (AccidentsConfigGroup) scenario.getConfig().getModules().get(AccidentsConfigGroup.GROUP_NAME); - + double timeBinSize = scenario.getConfig().travelTimeCalculator().getTraveltimeBinSize(); - + //File with Linkinfo for Tests - File linkInfoFile = new File(scenario.getConfig().controler().getOutputDirectory() + "ITERS/it." + event.getIteration() + "/" + scenario.getConfig().controler().getRunId() + "." + event.getIteration() + ".linkInfo.csv"); + File linkInfoFile = new File(scenario.getConfig().controller().getOutputDirectory() + "ITERS/it." + event.getIteration() + "/" + scenario.getConfig().controller().getRunId() + "." + event.getIteration() + ".linkInfo.csv"); BufferedWriter linkInformation = null; try { linkInformation = new BufferedWriter (new FileWriter(linkInfoFile)); @@ -62,7 +62,7 @@ public void write(Scenario scenario, IterationEndsEvent event, Map, Acc } linkInformation.write("demandPerDay ;"); linkInformation.newLine(); - + for (AccidentLinkInfo info : linkId2info.values()) { double demandPerDay = 0.0; linkInformation.write(info.getLinkId().toString()); @@ -77,15 +77,15 @@ public void write(Scenario scenario, IterationEndsEvent event, Map, Acc linkInformation.write(Double.toString(demand)); linkInformation.write(";"); } - linkInformation.write(Double.toString(demandPerDay)); + linkInformation.write(Double.toString(demandPerDay)); linkInformation.newLine(); } linkInformation.close(); } catch (IOException e3) { e3.printStackTrace(); } - - File accidentCostsBVWPFile = new File(scenario.getConfig().controler().getOutputDirectory() + "ITERS/it." + event.getIteration() + "/" + scenario.getConfig().controler().getRunId() + "." + event.getIteration() + ".accidentCosts_BVWP.csv"); + + File accidentCostsBVWPFile = new File(scenario.getConfig().controller().getOutputDirectory() + "ITERS/it." + event.getIteration() + "/" + scenario.getConfig().controller().getRunId() + "." + event.getIteration() + ".accidentCosts_BVWP.csv"); BufferedWriter accidentCostsBVWP = null; try { accidentCostsBVWP = new BufferedWriter (new FileWriter(accidentCostsBVWPFile)); @@ -100,7 +100,7 @@ public void write(Scenario scenario, IterationEndsEvent event, Map, Acc accidentCostsBVWP.write("Costs per Day [EUR] ;"); accidentCostsBVWP.write("Costs per Year [EUR] ;"); accidentCostsBVWP.newLine(); - + } catch (IOException e1) { e1.printStackTrace(); } @@ -109,7 +109,7 @@ public void write(Scenario scenario, IterationEndsEvent event, Map, Acc nf.setMaximumFractionDigits(2); nf.setGroupingUsed(false); - for (AccidentLinkInfo info : linkId2info.values()) { + for (AccidentLinkInfo info : linkId2info.values()) { double accidentCostsPerDay_BVWP = 0.0; double accidentCostsPerYear_BVWP = 0.0; @@ -123,12 +123,12 @@ public void write(Scenario scenario, IterationEndsEvent event, Map, Acc } catch (IOException e1) { e1.printStackTrace(); } - + for (double endTime = timeBinSize ; endTime <= scenario.getConfig().travelTimeCalculator().getMaxTime(); endTime = endTime + timeBinSize ) { - + double time = (endTime - timeBinSize/2.); int timeBinNr = (int) (time / timeBinSize); - + if (linkComputationMethod.toString().equals( AccidentsConfigGroup.AccidentsComputationMethod.BVWP.toString() )){ accidentCostsPerDay_BVWP += info.getTimeSpecificInfo().get(timeBinNr).getAccidentCosts(); try { diff --git a/contribs/accidents/src/main/java/org/matsim/contrib/accidents/runExample/RunAccidents.java b/contribs/accidents/src/main/java/org/matsim/contrib/accidents/runExample/RunAccidents.java index b9fe07dc88c..a25d3512e71 100644 --- a/contribs/accidents/src/main/java/org/matsim/contrib/accidents/runExample/RunAccidents.java +++ b/contribs/accidents/src/main/java/org/matsim/contrib/accidents/runExample/RunAccidents.java @@ -44,44 +44,44 @@ public class RunAccidents { private static final Logger log = LogManager.getLogger(RunAccidents.class); - - public static void main(String[] args) throws IOException { + + public static void main(String[] args) throws IOException { RunAccidents main = new RunAccidents(); main.run(); } private void run() throws MalformedURLException, IOException { log.info("Loading scenario..."); - + String configFile = "path/to/configFile.xml"; - + Config config = ConfigUtils.loadConfig(configFile ); - + AccidentsConfigGroup accidentsSettings = ConfigUtils.addOrGetModule(config, AccidentsConfigGroup.class); accidentsSettings.setEnableAccidentsModule(true); - + final Scenario scenario = ScenarioUtils.loadScenario(config); - + // Preprocess network AccidentsNetworkModification networkModification = new AccidentsNetworkModification(scenario); - + String[] tunnelLinks = readCSVFile("tunnelLinksCSVfile"); String[] planfreeLinks = readCSVFile("planfreeLinksCSVfile"); - + networkModification.setLinkAttributsBasedOnOSMFile("osmlandUseFile", "EPSG:31468" , tunnelLinks, planfreeLinks ); - + Controler controler = new Controler(scenario); controler.addOverridingModule(new AccidentsModule()); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); controler.run(); } - + private String[] readCSVFile(String csvFile) { ArrayList> links = new ArrayList<>(); BufferedReader br = IOUtils.getBufferedReader(csvFile); - + String line = null; try { line = br.readLine(); @@ -92,7 +92,7 @@ private String[] readCSVFile(String csvFile) { try { int countWarning = 0; while ((line = br.readLine()) != null) { - + String[] columns = line.split(";"); Id linkId = null; for (int column = 0; column < columns.length; column++) { @@ -105,7 +105,7 @@ private String[] readCSVFile(String csvFile) { log.warn("This message is only given once."); } countWarning++; - } + } } log.info("Adding link ID " + linkId); links.add(linkId); @@ -113,7 +113,7 @@ private String[] readCSVFile(String csvFile) { } catch (IOException e) { e.printStackTrace(); } - + String[] linkIDsArray = (String[]) links.toArray(); return linkIDsArray ; } diff --git a/contribs/accidents/src/test/java/org/matsim/contrib/accidents/RunTest.java b/contribs/accidents/src/test/java/org/matsim/contrib/accidents/RunTest.java index 3fa83d471d3..b98c144164f 100644 --- a/contribs/accidents/src/test/java/org/matsim/contrib/accidents/RunTest.java +++ b/contribs/accidents/src/test/java/org/matsim/contrib/accidents/RunTest.java @@ -19,57 +19,57 @@ /** * @author ikaddoura, mmayobre - * - * + * + * */ public class RunTest { @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - + @Test public void test1() { String configFile = utils.getPackageInputDirectory() + "/trial_scenario/trial_scenario_config.xml"; String outputDirectory = utils.getOutputDirectory(); String runId = "run1"; - + Config config = ConfigUtils.loadConfig(configFile); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - - config.controler().setOutputDirectory(outputDirectory); - config.controler().setRunId(runId); - + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + + config.controller().setOutputDirectory(outputDirectory); + config.controller().setRunId(runId); + AccidentsConfigGroup accidentsSettings = ConfigUtils.addOrGetModule(config, AccidentsConfigGroup.class); accidentsSettings.setEnableAccidentsModule(true); - + final Scenario scenario = ScenarioUtils.loadScenario(config); - + // pre-process network for (Link link : scenario.getNetwork().getLinks().values()) { link.getAttributes().putAttribute(accidentsSettings.getAccidentsComputationMethodAttributeName(), AccidentsComputationMethod.BVWP.toString()); - + int numberOfLanesBVWP; if (link.getNumberOfLanes() > 4){ numberOfLanesBVWP = 4; } else { numberOfLanesBVWP = (int) link.getNumberOfLanes(); } - + if (link.getFreespeed() > 16.) { link.getAttributes().putAttribute( AccidentsConfigGroup.BVWP_ROAD_TYPE_ATTRIBUTE_NAME, "1,0," + numberOfLanesBVWP); } else { link.getAttributes().putAttribute( AccidentsConfigGroup.BVWP_ROAD_TYPE_ATTRIBUTE_NAME, "1,2," + numberOfLanesBVWP); - } + } } - + Controler controler = new Controler(scenario); - + controler.addOverridingModule(new AccidentsModule() ); - + controler.run(); - + BufferedReader br = IOUtils.getBufferedReader(outputDirectory + "ITERS/it.0/run1.0.accidentCosts_BVWP.csv"); - + String line = null; try { line = br.readLine(); @@ -80,27 +80,27 @@ public void test1() { try { int lineCounter = 0; while ((line = br.readLine()) != null) { - + String[] columns = line.split(";"); for (int column = 0; column < columns.length; column++) { - + if (lineCounter == 0 && column == 25) { double accidentCosts = Double.valueOf(columns[column]); Assert.assertEquals("wrong accident costs", 10.38, accidentCosts , MatsimTestUtils.EPSILON); } - + if (lineCounter == 1 && column == 25) { double accidentCosts = Double.valueOf(columns[column]); Assert.assertEquals("wrong accident costs", 16.68, accidentCosts , MatsimTestUtils.EPSILON); } - + } - + lineCounter++; } } catch (IOException e) { e.printStackTrace(); } - + } } diff --git a/contribs/accidents/src/test/java/org/matsim/contrib/accidents/RunTestEquil.java b/contribs/accidents/src/test/java/org/matsim/contrib/accidents/RunTestEquil.java index 3cd2bf28fe2..d537b8c40e4 100644 --- a/contribs/accidents/src/test/java/org/matsim/contrib/accidents/RunTestEquil.java +++ b/contribs/accidents/src/test/java/org/matsim/contrib/accidents/RunTestEquil.java @@ -20,54 +20,54 @@ public class RunTestEquil { @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - - @Test + + @Test public void test1() { String configFile = utils.getPackageInputDirectory() + "/equil_scenario/config.xml"; String outputDirectory = utils.getOutputDirectory(); String runId = "run1"; - + Config config = ConfigUtils.loadConfig( configFile ); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - - config.controler().setOutputDirectory( outputDirectory ); - config.controler().setRunId( runId ); - config.controler().setLastIteration(0); - + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + + config.controller().setOutputDirectory( outputDirectory ); + config.controller().setRunId( runId ); + config.controller().setLastIteration(0); + AccidentsConfigGroup accidentsSettings = ConfigUtils.addOrGetModule(config, AccidentsConfigGroup.class); accidentsSettings.setEnableAccidentsModule(true); - + final Scenario scenario = ScenarioUtils.loadScenario(config); Controler controler = new Controler (scenario); controler.addOverridingModule(new AccidentsModule() ); - - scenario.getNetwork().getLinks().get(Id.createLinkId("6")).setFreespeed(10); + + scenario.getNetwork().getLinks().get(Id.createLinkId("6")).setFreespeed(10); scenario.getNetwork().getLinks().get(Id.createLinkId("6")).setNumberOfLanes(3); - scenario.getNetwork().getLinks().get(Id.createLinkId("15")).setFreespeed(10); + scenario.getNetwork().getLinks().get(Id.createLinkId("15")).setFreespeed(10); scenario.getNetwork().getLinks().get(Id.createLinkId("15")).setNumberOfLanes(2); - + // pre-process network for (Link link : scenario.getNetwork().getLinks().values()) { link.getAttributes().putAttribute(accidentsSettings.getAccidentsComputationMethodAttributeName(), AccidentsComputationMethod.BVWP.toString()); - + int numberOfLanesBVWP; if (link.getNumberOfLanes() > 4){ numberOfLanesBVWP = 4; } else { numberOfLanesBVWP = (int) link.getNumberOfLanes(); } - + if (link.getFreespeed() > 16.) { link.getAttributes().putAttribute( AccidentsConfigGroup.BVWP_ROAD_TYPE_ATTRIBUTE_NAME, "1,0," + numberOfLanesBVWP); } else { link.getAttributes().putAttribute( AccidentsConfigGroup.BVWP_ROAD_TYPE_ATTRIBUTE_NAME, "1,2," + numberOfLanesBVWP); - } + } } - + controler.run(); - + BufferedReader br = IOUtils.getBufferedReader(outputDirectory + "ITERS/it.0/run1.0.accidentCosts_BVWP.csv"); - + String line = null; try { line = br.readLine(); @@ -78,10 +78,10 @@ public void test1() { try { int lineCounter = 0; while ((line = br.readLine()) != null) { - + String[] columns = line.split(";"); for (int column = 0; column < columns.length; column++) { - + // link 22 if (lineCounter == 1 && column == 121) { double accidentCosts = Double.valueOf(columns[column]); @@ -98,7 +98,7 @@ public void test1() { double accidentCostsManualCalculation = (agents * lengthKM * 61.785) / 1000. * 10; Assert.assertEquals("wrong accident costs", accidentCostsManualCalculation, accidentCosts , 0.01); } - + // link 6 if (lineCounter == 16 && column == 121) { double accidentCosts = Double.valueOf(columns[column]); @@ -106,8 +106,8 @@ public void test1() { int lengthKM = 10; double accidentCostsManualCalculation = (agents * lengthKM * 34.735) / 1000. * 10; Assert.assertEquals("wrong accident costs", accidentCostsManualCalculation, accidentCosts , 0.01); - } - + } + // link 15 if (lineCounter == 6 && column == 121) { double accidentCosts = Double.valueOf(columns[column]); @@ -117,7 +117,7 @@ public void test1() { Assert.assertEquals("wrong accident costs", accidentCostsManualCalculation, accidentCosts , 0.01); } } - + lineCounter++; } } catch (IOException e) { diff --git a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/ActivitiesAnalyzer.java b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/ActivitiesAnalyzer.java index 39c5b49040b..bb4239c27c9 100644 --- a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/ActivitiesAnalyzer.java +++ b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/ActivitiesAnalyzer.java @@ -39,11 +39,11 @@ import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.utils.charts.XYLineChart; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import java.awt.*; import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.*; import java.util.List; @@ -54,21 +54,21 @@ * * @author cdobler */ -public class ActivitiesAnalyzer implements ActivityStartEventHandler, ActivityEndEventHandler, +public class ActivitiesAnalyzer implements ActivityStartEventHandler, ActivityEndEventHandler, StartupListener, BeforeMobsimListener, IterationEndsListener { public static String defaultActivitiesFileName = "activityCounts"; - + private final boolean autoConfig; - + private double endTime = 30*3600; - + private String activitiesFileName = defaultActivitiesFileName; private final Set observedAgents; private boolean createGraphs; private final Map> activityCountData = new TreeMap>(); private final LinkedList overallCount = new LinkedList(); - + /** * This is how most people will probably will use this class. * It has to be created an registered as ControlerListener. @@ -76,56 +76,56 @@ public class ActivitiesAnalyzer implements ActivityStartEventHandler, ActivityEn * get paths to output files, ...). */ public ActivitiesAnalyzer() { - + this.autoConfig = true; this.createGraphs = true; this.observedAgents = null; - + reset(0); } - + public ActivitiesAnalyzer(String activitiesFileName, Set activityTypes, boolean createGraphs) { this(activitiesFileName, activityTypes, null, createGraphs); } - + public ActivitiesAnalyzer(String activitiesFileName, Set activityTypes, Set observedAgents, boolean createGraphs) { - + this.autoConfig = false; - + this.activitiesFileName = activitiesFileName; this.createGraphs = createGraphs; - + // use all activity defined in the set for (String activityType : activityTypes) { this.activityCountData.put(activityType, new LinkedList()); } - + if (observedAgents != null) { // make a copy to prevent people changing the set over the iterations - this.observedAgents = new HashSet(observedAgents); + this.observedAgents = new HashSet(observedAgents); } else this.observedAgents = null; - + reset(0); } - + public void setCreateGraphs(boolean createGraphs) { this.createGraphs = createGraphs; } - + public void setEndTime(double endTime) { this.endTime = endTime; } - + @Override public void handleEvent(ActivityEndEvent event) { - + if (observedAgents != null && !observedAgents.contains(event.getPersonId())) return; - + LinkedList list = this.activityCountData.get(event.getActType()); - + // ignore not observed activity types if (list == null) return; - + changeCount(event.getTime(), list, -1); changeCount(event.getTime(), this.overallCount, -1); } @@ -133,22 +133,22 @@ public void handleEvent(ActivityEndEvent event) { @Override public void handleEvent(ActivityStartEvent event) { - + if (observedAgents != null && !observedAgents.contains(event.getPersonId())) return; - + LinkedList list = this.activityCountData.get(event.getActType()); // ignore not observed activity types if (list == null) return; - + changeCount(event.getTime(), list, 1); changeCount(event.getTime(), this.overallCount, 1); } - + private void changeCount(double time, LinkedList list, int delta) { - + ActivityData activityData = list.getLast(); - + /* * If there is already another entry for the same time step, re-use it. * Otherwise create a new one. @@ -159,7 +159,7 @@ private void changeCount(double time, LinkedList list, int delta) list.add(new ActivityData(time, activityData.activityCount + delta)); } } - + @Override public void reset(final int iter) { for (List list : this.activityCountData.values()) { @@ -169,40 +169,40 @@ public void reset(final int iter) { this.overallCount.clear(); this.overallCount.add(new ActivityData(0.0, 0)); } - + @Override public void notifyStartup(StartupEvent event) { - + MatsimServices controler = event.getServices(); - + if (autoConfig) { // use all activity types defined in the config - Set activityTypes = new TreeSet(event.getServices().getConfig().planCalcScore().getActivityTypes()); + Set activityTypes = new TreeSet(event.getServices().getConfig().scoring().getActivityTypes()); for (String activityType : activityTypes) { this.activityCountData.put(activityType, new LinkedList()); } - + controler.getEvents().addHandler(this); } } - + @Override public void notifyBeforeMobsim(BeforeMobsimEvent event) { - + ActivityData overallActivityData = this.overallCount.getLast(); for (Person person : event.getServices().getScenario().getPopulation().getPersons().values()) { - + if (this.observedAgents != null && !this.observedAgents.contains(person.getId())) continue; - + Plan plan = person.getSelectedPlan(); Activity firstActivity = (Activity) plan.getPlanElements().get(0); LinkedList list = activityCountData.get(firstActivity.getType()); - + // ignore not observed activity types if (list == null) continue; - + ActivityData activityData = list.getLast(); activityData.activityCount += 1; overallActivityData.activityCount += 1; @@ -211,19 +211,19 @@ public void notifyBeforeMobsim(BeforeMobsimEvent event) { @Override public void notifyIterationEnds(IterationEndsEvent event) { - + OutputDirectoryHierarchy outputDirectoryHierarchy = event.getServices().getControlerIO(); - + try { for (String activityType : this.activityCountData.keySet()) { String fileName = outputDirectoryHierarchy.getIterationFilename(event.getIteration(), this.activitiesFileName + "_" + activityType + ".txt"); BufferedWriter activitiesWriter = IOUtils.getBufferedWriter(fileName); - + activitiesWriter.write("TIME"); activitiesWriter.write("\t"); activitiesWriter.write(activityType.toUpperCase()); activitiesWriter.write("\n"); - + List list = this.activityCountData.get(activityType); for (ActivityData activityData : list) { activitiesWriter.write(String.valueOf(activityData.time)); @@ -231,18 +231,18 @@ public void notifyIterationEnds(IterationEndsEvent event) { activitiesWriter.write(String.valueOf(activityData.activityCount)); activitiesWriter.write("\n"); } - + activitiesWriter.flush(); activitiesWriter.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } - + if (this.createGraphs) { // create chart when data of more than one iteration is available. XYLineChart chart; - + /* * number of performed activities */ @@ -250,7 +250,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { for (String activityType : this.activityCountData.keySet()) { List list = this.activityCountData.get(activityType); int length = list.size(); - + double[] times = new double[length * 2 - 1]; double[] counts = new double[length * 2 - 1]; Iterator iter = list.iterator(); @@ -287,13 +287,13 @@ public void notifyIterationEnds(IterationEndsEvent event) { i += 2; } chart.addSeries("overall", times, counts); - + NumberAxis domainAxis = (NumberAxis) chart.getChart().getXYPlot().getDomainAxis(); domainAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 11)); domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); domainAxis.setAutoRange(false); domainAxis.setRange(0, endTime / 3600.0); - + chart.addMatsimLogo(); String fileName = outputDirectoryHierarchy.getIterationFilename(event.getIteration(), this.activitiesFileName + ".png"); chart.saveAsPng(fileName, 800, 600); @@ -301,7 +301,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { } private static class ActivityData { - + public final double time; public int activityCount; @@ -311,4 +311,4 @@ public ActivityData(double time, int activityCount) { } } -} \ No newline at end of file +} diff --git a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/TripsAnalyzer.java b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/TripsAnalyzer.java index e5ad1a32205..390adb131b9 100644 --- a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/TripsAnalyzer.java +++ b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/TripsAnalyzer.java @@ -22,6 +22,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; @@ -45,7 +46,6 @@ import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.utils.charts.XYLineChart; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; /** * Calculates: @@ -53,7 +53,7 @@ * - average leg travel time over all modes * - number of trips per mode * - number of trips over all modes - * + * * @author cdobler */ public class TripsAnalyzer implements PersonDepartureEventHandler, PersonArrivalEventHandler, @@ -63,23 +63,23 @@ public class TripsAnalyzer implements PersonDepartureEventHandler, PersonArrival public static String defaultDurationsFileName = "tripDurations"; private final boolean autoConfig; - + private final Set sortedModes = new TreeSet(); private final Set observedAgents; private final Map departureTimes = new HashMap(); private final Map> legTravelTimes = new HashMap>(); - + private String tripsFileName; private String durationsFileName; private boolean createGraphs; - + private BufferedWriter tripsWriter; private BufferedWriter durationWriter; - + private double[][] tripsHistory; private double[][] durationHistory; private int minIteration; - + /** * This is how most people will probably will use this class. * It has to be created an registered as ControlerListener. @@ -87,47 +87,47 @@ public class TripsAnalyzer implements PersonDepartureEventHandler, PersonArrival * get paths to output files, ...). */ public TripsAnalyzer() { - + this.autoConfig = true; this.createGraphs = true; - + // modes which are analyzed by default this.sortedModes.add(TransportMode.bike); this.sortedModes.add(TransportMode.car); this.sortedModes.add(TransportMode.pt); this.sortedModes.add(TransportMode.ride); this.sortedModes.add(TransportMode.walk); - + this.observedAgents = null; } - + public TripsAnalyzer(String tripsFileName, String durationsFileName, Set modes, boolean createGraphs) { this(tripsFileName, durationsFileName, modes, null, createGraphs); } - + public TripsAnalyzer(String tripsFileName, String durationsFileName, Set modes, Set observedAgents, boolean createGraphs) { this.autoConfig = false; - + this.tripsFileName = tripsFileName; this.durationsFileName = durationsFileName; this.sortedModes.addAll(modes); if (observedAgents != null) { // make a copy to prevent people changing the set over the iterations - this.observedAgents = new HashSet(observedAgents); + this.observedAgents = new HashSet(observedAgents); } else this.observedAgents = null; this.createGraphs = createGraphs; } - + public void setCreateGraphs(boolean createGraphs) { this.createGraphs = createGraphs; } - + public Set getModes() { return this.sortedModes; } - + @Override public void reset(int iteration) { for(List modeTravelTime : legTravelTimes.values()) { @@ -137,12 +137,12 @@ public void reset(int iteration) { @Override public void handleEvent(PersonArrivalEvent event) { - + if (observedAgents != null && !observedAgents.contains(event.getPersonId())) return; - + Double departureTime = departureTimes.remove(event.getPersonId()); if (departureTime == null) throw new RuntimeException("No departure time for agent " + event.getPersonId() + " was found!"); - + double travelTime = event.getTime() - departureTime; String mode = event.getLegMode(); List modeTravelTimes = legTravelTimes.get(mode); @@ -159,16 +159,16 @@ public void handleEvent(PersonDepartureEvent event) { public void notifyStartup(final StartupEvent event) { MatsimServices controler = event.getServices(); - this.minIteration = controler.getConfig().controler().getFirstIteration(); - int maxIter = controler.getConfig().controler().getLastIteration(); + this.minIteration = controler.getConfig().controller().getFirstIteration(); + int maxIter = controler.getConfig().controller().getLastIteration(); int iterations = maxIter - this.minIteration; this.tripsHistory = new double[this.sortedModes.size() + 1][iterations + 1]; - this.durationHistory = new double[this.sortedModes.size() + 1][iterations + 1]; - + this.durationHistory = new double[this.sortedModes.size() + 1][iterations + 1]; + if (autoConfig) { this.tripsFileName = event.getServices().getControlerIO().getOutputFilename(defaultTripsFileName); this.durationsFileName = event.getServices().getControlerIO().getOutputFilename(defaultDurationsFileName); - + controler.getEvents().addHandler(this); } @@ -183,7 +183,7 @@ public void notifyStartup(final StartupEvent event) { this.tripsWriter.write(mode.toUpperCase()); this.durationWriter.write("\t"); this.durationWriter.write(mode.toUpperCase()); - + this.legTravelTimes.put(mode, new LinkedList()); } this.tripsWriter.write("\t"); @@ -192,12 +192,12 @@ public void notifyStartup(final StartupEvent event) { this.durationWriter.write("\t"); this.durationWriter.write("OVERALL"); this.durationWriter.write("\n"); - + } catch (IOException e) { throw new UncheckedIOException(e); } } - + @Override public void notifyIterationEnds(IterationEndsEvent event) { try { @@ -205,7 +205,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { this.tripsWriter.write(String.valueOf(iteration)); this.durationWriter.write(String.valueOf(iteration)); int index = iteration - this.minIteration; - + int i = 0; int overallTrips = 0; double overallTravelTime = 0.0; @@ -213,7 +213,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { List modeTravelTimes = legTravelTimes.get(mode); double sumTravelTimes = 0.0; for (double travelTime : modeTravelTimes) sumTravelTimes += travelTime; - + int modeTrips = modeTravelTimes.size(); overallTrips += modeTrips; overallTravelTime += sumTravelTimes; @@ -221,19 +221,19 @@ public void notifyIterationEnds(IterationEndsEvent event) { double averageTravelTime = sumTravelTimes / modeTrips; this.tripsHistory[i][index] = modeTrips; this.durationHistory[i][index] = averageTravelTime; - + this.tripsWriter.write("\t"); this.tripsWriter.write(String.valueOf(modeTrips)); this.durationWriter.write("\t"); this.durationWriter.write(String.valueOf(averageTravelTime)); - + i++; } - + double averageTravelTime = overallTravelTime / overallTrips; this.tripsHistory[sortedModes.size()][index] = overallTrips; this.durationHistory[sortedModes.size()][index] = averageTravelTime; - + this.tripsWriter.write("\t"); this.tripsWriter.write(String.valueOf(overallTrips)); this.tripsWriter.write("\n"); @@ -250,26 +250,26 @@ public void notifyIterationEnds(IterationEndsEvent event) { } catch (IOException e) { throw new RuntimeException(e); } - + if (this.createGraphs && event.getIteration() != this.minIteration) { int index = event.getIteration() - this.minIteration; // create chart when data of more than one iteration is available. XYLineChart chart; - + double[] iterations = new double[index + 1]; for (int i = 0; i <= index; i++) { iterations[i] = i + this.minIteration; } double[] values = new double[index + 1]; - + int i; - + /* * average leg duration */ chart = new XYLineChart("Average Leg Travel Times Statistics", "iteration", "time"); - + i = 0; for (String mode : sortedModes) { System.arraycopy(this.durationHistory[i], 0, values, 0, index + 1); @@ -278,15 +278,15 @@ public void notifyIterationEnds(IterationEndsEvent event) { } System.arraycopy(this.durationHistory[i], 0, values, 0, index + 1); chart.addSeries("overall", iterations, values); - + chart.addMatsimLogo(); chart.saveAsPng(this.durationsFileName + ".png", 800, 600); - + /* * number of trips */ chart = new XYLineChart("Number of Trips per Mode Statistics", "iteration", "number of trips"); - + i = 0; for (String mode : sortedModes) { System.arraycopy(this.tripsHistory[i], 0, values, 0, index + 1); @@ -295,7 +295,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { } System.arraycopy(this.tripsHistory[i], 0, values, 0, index + 1); chart.addSeries("overall", iterations, values); - + chart.addMatsimLogo(); chart.saveAsPng(this.tripsFileName + ".png", 800, 600); } @@ -306,7 +306,7 @@ public void notifyShutdown(ShutdownEvent event) { try { if (this.tripsWriter != null) { this.tripsWriter.flush(); - this.tripsWriter.close(); + this.tripsWriter.close(); } if (this.durationWriter != null) { this.durationWriter.flush(); diff --git a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/kai/KNAnalysisEventsHandler.java b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/kai/KNAnalysisEventsHandler.java index 3bde897e73c..ad1e9cfe938 100644 --- a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/kai/KNAnalysisEventsHandler.java +++ b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/kai/KNAnalysisEventsHandler.java @@ -43,13 +43,13 @@ import org.matsim.core.router.TripStructureUtils.Trip; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.utils.objectattributes.ObjectAttributes; import org.matsim.utils.objectattributes.ObjectAttributesXmlWriter; import org.matsim.vehicles.Vehicle; import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.*; import java.util.Map.Entry; @@ -100,7 +100,7 @@ enum StatType { private Vehicle2DriverEventHandler delegate = new Vehicle2DriverEventHandler() ; - // general trip counter. Would, in theory, not necessary to do this per StatType, but I find it too brittle + // general trip counter. Would, in theory, not necessary to do this per StatType, but I find it too brittle // to avoid under- or over-counting with respect to loops. // private final Map legCount = new TreeMap() ; diff --git a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/kai/RunKNEventsAnalyzer.java b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/kai/RunKNEventsAnalyzer.java index 205cf58ba3b..462943c36f4 100644 --- a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/kai/RunKNEventsAnalyzer.java +++ b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/kai/RunKNEventsAnalyzer.java @@ -37,70 +37,70 @@ public class RunKNEventsAnalyzer { public static void main(String[] args) { - + if ( args.length < 3 ) { System.out.println("Usage: cmd eventsFile popFile netFile [popAttrFile] [tollFile] [futureTollFile]. Aborting ..." ) ; System.exit(-1); } - + String eventsFilename = args[0] ; String populationFilename = args[1] ; String networkFilename = args[2] ; - + String popAttrFilename = null ; if ( args.length > 3 && args[3]!=null ) { popAttrFilename = args[3] ; } - + String tollFilename = null ; if ( args.length > 4 && args[4]!=null ) { tollFilename = args[4] ; } - + String otherLinksFilename = null ; if ( args.length > 5 && args[5]!=null ) { otherLinksFilename = args[5] ; } - + // === Config config = ConfigUtils.createConfig() ; - + String[] modes ={"car","commercial"}; config.qsim().setMainModes( Arrays.asList(modes) ); - config.plansCalcRoute().setNetworkModes(Arrays.asList(modes)); - + config.routing().setNetworkModes(Arrays.asList(modes)); + config.network().setInputFile( networkFilename ); config.plans().setInputFile( populationFilename ); config.plans().setInputPersonAttributeFile( popAttrFilename ); ConfigUtils.addOrGetModule(config, RoadPricingConfigGroup.GROUP_NAME, RoadPricingConfigGroup.class).setTollLinksFile(tollFilename); // === - + Scenario scenario = ScenarioUtils.loadScenario(config) ; // ((ScenarioImpl)scenario).createVehicleContainer() ; // GautengControler_subpopulations.createVehiclePerPerson(scenario); - + // === - + EventsManager events = new EventsManagerImpl() ; - + Vehicle2DriverEventHandler vehicle2Driver = new Vehicle2DriverEventHandler(); events.addHandler(vehicle2Driver); - + final KNAnalysisEventsHandler.Builder builder = new KNAnalysisEventsHandler.Builder(scenario) ; builder.setOtherTollLinkFile( otherLinksFilename ); final KNAnalysisEventsHandler calcLegTimes = builder.build(); - + events.addHandler( calcLegTimes ); - + new MatsimEventsReader(events).readFile(eventsFilename) ; - -// String myDate = date.getYear() + "-" + date.getMonthOfYear() + "-" + date.getDayOfMonth() + "-" + + +// String myDate = date.getYear() + "-" + date.getMonthOfYear() + "-" + date.getDayOfMonth() + "-" + // date.getHourOfDay() + "h" + minute ; String myDate = "" ; - + calcLegTimes.writeStats(myDate + "_stats_"); } diff --git a/contribs/analysis/src/main/java/org/matsim/contrib/travelsummary/events2traveldiaries/RunEventsToTravelDiaries.java b/contribs/analysis/src/main/java/org/matsim/contrib/travelsummary/events2traveldiaries/RunEventsToTravelDiaries.java index 403f4d0bdb5..436cb4c800f 100644 --- a/contribs/analysis/src/main/java/org/matsim/contrib/travelsummary/events2traveldiaries/RunEventsToTravelDiaries.java +++ b/contribs/analysis/src/main/java/org/matsim/contrib/travelsummary/events2traveldiaries/RunEventsToTravelDiaries.java @@ -51,7 +51,7 @@ public static void main(String[] args) { printHelp(); try { config = ConfigUtils.loadConfig(args[0]); - outputDirectory = config.controler().getOutputDirectory(); + outputDirectory = config.controller().getOutputDirectory(); eventsFileName = args[1]; diff --git a/contribs/application/src/main/java/org/matsim/application/ApplicationUtils.java b/contribs/application/src/main/java/org/matsim/application/ApplicationUtils.java index ff3b129cd80..89086cb00d3 100644 --- a/contribs/application/src/main/java/org/matsim/application/ApplicationUtils.java +++ b/contribs/application/src/main/java/org/matsim/application/ApplicationUtils.java @@ -6,7 +6,6 @@ import org.matsim.application.options.CrsOptions; import org.matsim.application.options.InputOptions; import org.matsim.application.options.OutputOptions; -import org.matsim.application.options.ShpOptions; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.scenario.ScenarioUtils; @@ -129,8 +128,8 @@ public static Scenario loadScenario(String runId, Path runDirectory, CrsOptions Config config = ConfigUtils.createConfig(); config.global().setCoordinateSystem(crs.getInputCRS()); - config.controler().setOutputDirectory(runDirectory.toString()); - config.controler().setRunId(resolvedRunId); + config.controller().setOutputDirectory(runDirectory.toString()); + config.controller().setRunId(resolvedRunId); config.plans().setInputFile(populationFile.toString()); config.network().setInputFile(networkFile.toString()); diff --git a/contribs/application/src/main/java/org/matsim/application/MATSimApplication.java b/contribs/application/src/main/java/org/matsim/application/MATSimApplication.java index 85b7c057064..c1951c1b2a4 100644 --- a/contribs/application/src/main/java/org/matsim/application/MATSimApplication.java +++ b/contribs/application/src/main/java/org/matsim/application/MATSimApplication.java @@ -11,9 +11,10 @@ import org.matsim.application.commands.RunScenario; import org.matsim.application.commands.ShowGUI; import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigAliases; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.controler.Controler; @@ -177,13 +178,13 @@ public Integer call() throws Exception { } if (iterations > -1) - config.controler().setLastIteration(iterations); + config.controller().setLastIteration(iterations); if (output != null) - config.controler().setOutputDirectory(output.toString()); + config.controller().setOutputDirectory(output.toString()); if (runId != null) - config.controler().setRunId(runId); + config.controller().setRunId(runId); final Scenario scenario = createScenario(config); @@ -199,7 +200,7 @@ public Integer call() throws Exception { if (post != PostProcessOption.disabled) { - List commands = preparePostProcessing(Path.of(config.controler().getOutputDirectory()), config.controler().getRunId()); + List commands = preparePostProcessing(Path.of(config.controller().getOutputDirectory()), config.controller().getRunId()); for (MATSimAppCommand command : commands) { @@ -230,6 +231,9 @@ private static void applySpecs(Config config, Path specs) { ObjectMapper mapper = new ObjectMapper(new YAMLFactory() .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)); + ConfigAliases aliases = new ConfigAliases(); + Deque emptyStack = new ArrayDeque<>(); + try (BufferedReader reader = Files.newBufferedReader(specs)) { JsonNode node = mapper.readTree(reader); @@ -238,10 +242,10 @@ private static void applySpecs(Config config, Path specs) { while (fields.hasNext()) { Map.Entry field = fields.next(); - - ConfigGroup group = config.getModules().get(field.getKey()); + String configGroupName = aliases.resolveAlias(field.getKey(), emptyStack); + ConfigGroup group = config.getModules().get(configGroupName); if (group == null) { - log.warn("Config group not found: {}", field.getKey()); + log.warn("Config group not found: {}", configGroupName); continue; } @@ -313,7 +317,7 @@ protected List getCustomModules() { */ protected List getConfigurableModules() { return Lists.newArrayList( - new ControlerConfigGroup(), + new ControllerConfigGroup(), new GlobalConfigGroup(), new QSimConfigGroup() ); @@ -370,14 +374,14 @@ protected final void addRunOption(Config config, String option, Object value) { else postfix = "-" + option + "_" + value; - String outputDir = config.controler().getOutputDirectory(); + String outputDir = config.controller().getOutputDirectory(); if (outputDir.endsWith("/")) { - config.controler().setOutputDirectory(outputDir.substring(0, outputDir.length() - 1) + postfix + "/"); + config.controller().setOutputDirectory(outputDir.substring(0, outputDir.length() - 1) + postfix + "/"); } else - config.controler().setOutputDirectory(outputDir + postfix); + config.controller().setOutputDirectory(outputDir + postfix); // dot should not be part of run id - config.controler().setRunId(config.controler().getRunId() + postfix.replace(".", "")); + config.controller().setRunId(config.controller().getRunId() + postfix.replace(".", "")); } /** diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionAnalysis.java b/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionAnalysis.java index f273c87adfe..eca4eee1e0b 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionAnalysis.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionAnalysis.java @@ -142,8 +142,8 @@ private Config prepareConfig() { config.transit().setTransitScheduleFile(ApplicationUtils.matchInput("transitSchedule", input.getRunDirectory()).toAbsolutePath().toString()); config.transit().setVehiclesFile(ApplicationUtils.matchInput("transitVehicles", input.getRunDirectory()).toAbsolutePath().toString()); config.plans().setInputFile(null); - config.parallelEventHandling().setNumberOfThreads(null); - config.parallelEventHandling().setEstimatedNumberOfEvents(null); + config.eventsManager().setNumberOfThreads(null); + config.eventsManager().setEstimatedNumberOfEvents(null); config.global().setNumberOfThreads(1); return config; diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionByVehicleCategory.java b/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionByVehicleCategory.java index 7b02f55fa53..20bf17af5c6 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionByVehicleCategory.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionByVehicleCategory.java @@ -135,8 +135,8 @@ public Integer call() throws Exception { config.transit().setVehiclesFile(globFile(runDirectory, runId, "transitVehicles")); config.global().setCoordinateSystem(crs.getInputCRS()); config.plans().setInputFile(null); - config.parallelEventHandling().setNumberOfThreads(null); - config.parallelEventHandling().setEstimatedNumberOfEvents(null); + config.eventsManager().setNumberOfThreads(null); + config.eventsManager().setEstimatedNumberOfEvents(null); config.global().setNumberOfThreads(1); EmissionsConfigGroup eConfig = ConfigUtils.addOrGetModule(config, EmissionsConfigGroup.class); diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/noise/NoiseAnalysis.java b/contribs/application/src/main/java/org/matsim/application/analysis/noise/NoiseAnalysis.java index 964ce79c6a8..3e99b052194 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/noise/NoiseAnalysis.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/noise/NoiseAnalysis.java @@ -71,7 +71,7 @@ public Integer call() throws Exception { if (!runDirectory.endsWith("/")) runDirectory = runDirectory + "/"; config.global().setCoordinateSystem(crs.getInputCRS()); - config.controler().setRunId(runId); + config.controller().setRunId(runId); if (!runId.equals("")) { config.network().setInputFile(runDirectory + runId + ".output_network.xml.gz"); config.plans().setInputFile(runDirectory + runId + ".output_plans.xml.gz"); @@ -79,7 +79,7 @@ public Integer call() throws Exception { config.network().setInputFile(runDirectory + "output_network.xml.gz"); config.plans().setInputFile(runDirectory + "output_plans.xml.gz"); } - config.controler().setOutputDirectory(runDirectory); + config.controller().setOutputDirectory(runDirectory); // adjust the default noise parameters NoiseConfigGroup noiseParameters = ConfigUtils.addOrGetModule(config, NoiseConfigGroup.class); diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/population/TripAnalysis.java b/contribs/application/src/main/java/org/matsim/application/analysis/population/TripAnalysis.java index 9ff85eb7b67..35f11ab09d6 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/population/TripAnalysis.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/population/TripAnalysis.java @@ -92,6 +92,7 @@ public Integer call() throws Exception { Table persons = Table.read().csv(CsvReadOptions.builder(IOUtils.getBufferedReader(input.getPath("persons.csv"))) .columnTypesPartial(Map.of("person", ColumnType.TEXT)) + .sample(false) .separator(';').build()); int total = persons.rowCount(); @@ -132,6 +133,7 @@ public Integer call() throws Exception { Table trips = Table.read().csv(CsvReadOptions.builder(IOUtils.getBufferedReader(input.getPath("trips.csv"))) .columnTypesPartial(columnTypes) + .sample(false) .separator(';').build()); diff --git a/contribs/application/src/main/java/org/matsim/application/prepare/freight/optimization/DetermineAverageTruckLoad.java b/contribs/application/src/main/java/org/matsim/application/prepare/freight/optimization/DetermineAverageTruckLoad.java index 6dd30f93606..8318bef7292 100644 --- a/contribs/application/src/main/java/org/matsim/application/prepare/freight/optimization/DetermineAverageTruckLoad.java +++ b/contribs/application/src/main/java/org/matsim/application/prepare/freight/optimization/DetermineAverageTruckLoad.java @@ -6,8 +6,6 @@ import org.apache.commons.csv.CSVRecord; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.checkerframework.checker.units.qual.C; -import org.locationtech.jts.geom.Geometry; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Identifiable; @@ -16,7 +14,6 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CrsOptions; -import org.matsim.application.options.ShpOptions; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.NetworkUtils; @@ -28,7 +25,6 @@ import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; -import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.core.utils.gis.ShapeFileReader; import org.opengis.feature.simple.SimpleFeature; @@ -37,7 +33,6 @@ import java.io.FileWriter; import java.io.IOException; import java.net.URI; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -342,7 +337,7 @@ private boolean checkIfTripIsRelevant(String mode, String from, String to, Strin private LeastCostPathCalculator createRouter(Network network) { Config config = ConfigUtils.createConfig(); - config.plansCalcRoute().setRoutingRandomness(0); + config.routing().setRoutingRandomness(0); TravelTime travelTime = new FreeSpeedTravelTime(); TravelDisutility travelDisutility = new RandomizingTimeDistanceTravelDisutilityFactory (TransportMode.car, config).createTravelDisutility(travelTime); diff --git a/contribs/application/src/main/java/org/matsim/application/prepare/freight/tripExtraction/ExtractRelevantFreightTrips.java b/contribs/application/src/main/java/org/matsim/application/prepare/freight/tripExtraction/ExtractRelevantFreightTrips.java index 870cd1be48f..196e114634c 100644 --- a/contribs/application/src/main/java/org/matsim/application/prepare/freight/tripExtraction/ExtractRelevantFreightTrips.java +++ b/contribs/application/src/main/java/org/matsim/application/prepare/freight/tripExtraction/ExtractRelevantFreightTrips.java @@ -82,7 +82,7 @@ public Integer call() throws Exception { config.network().setInputFile(networkPath.toString()); Scenario outputScenario = ScenarioUtils.loadScenario(config); config.plans().setInputFile(freightDataDirectory.toString()); - config.plansCalcRoute().setRoutingRandomness(0); + config.routing().setRoutingRandomness(0); Scenario scenario = ScenarioUtils.loadScenario(config); Network network = scenario.getNetwork(); Population originalPlans = scenario.getPopulation(); diff --git a/contribs/application/src/main/java/org/matsim/application/prepare/network/CreateGeoJsonNetwork.java b/contribs/application/src/main/java/org/matsim/application/prepare/network/CreateGeoJsonNetwork.java index dc770d9c607..5d4a67851ff 100644 --- a/contribs/application/src/main/java/org/matsim/application/prepare/network/CreateGeoJsonNetwork.java +++ b/contribs/application/src/main/java/org/matsim/application/prepare/network/CreateGeoJsonNetwork.java @@ -45,7 +45,7 @@ public class CreateGeoJsonNetwork implements MATSimAppCommand { @CommandLine.Option(names = "--match-id", description = "Pattern to filter links by id") private String matchId; - @CommandLine.Option(names = "--mode-filter", split = ",", defaultValue = "car", + @CommandLine.Option(names = "--mode-filter", split = ",", defaultValue = "car,freight,drt", description = "Only keep links if they have one of the specified modes. Specify 'none' to disable.") private Set modes; diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/CarrierReaderFromCSV.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/CarrierReaderFromCSV.java index 591a895aa84..b8dc592921e 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/CarrierReaderFromCSV.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/CarrierReaderFromCSV.java @@ -27,10 +27,8 @@ 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.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; @@ -236,7 +234,7 @@ public void setFixedNumberOfVehiclePerTypeAndLocation(int fixedNumberOfVehiclePe * Reads and create the carriers with reading the information from the csv file. * * @param scenario - * @param freightConfigGroup + * @param freightCarriersConfigGroup * @param csvLocationCarrier * @param polygonsInShape * @param defaultJspritIterations @@ -244,14 +242,14 @@ public void setFixedNumberOfVehiclePerTypeAndLocation(int fixedNumberOfVehiclePe * @param shapeCategory * @throws IOException */ - public static void readAndCreateCarrierFromCSV(Scenario scenario, FreightConfigGroup freightConfigGroup, + public static void readAndCreateCarrierFromCSV(Scenario scenario, FreightCarriersConfigGroup freightCarriersConfigGroup, Path csvLocationCarrier, Collection polygonsInShape, int defaultJspritIterations, CoordinateTransformation crsTransformationNetworkAndShape, String shapeCategory) throws IOException { Set allNewCarrierInformation = readCarrierInformation(csvLocationCarrier); - checkNewCarrier(allNewCarrierInformation, freightConfigGroup, scenario, polygonsInShape, shapeCategory); + checkNewCarrier(allNewCarrierInformation, freightCarriersConfigGroup, scenario, polygonsInShape, shapeCategory); log.info("The read carrier information from the csv are checked without errors."); - createNewCarrierAndAddVehicleTypes(scenario, allNewCarrierInformation, freightConfigGroup, polygonsInShape, + createNewCarrierAndAddVehicleTypes(scenario, allNewCarrierInformation, freightCarriersConfigGroup, polygonsInShape, defaultJspritIterations, crsTransformationNetworkAndShape); } @@ -307,23 +305,23 @@ else if (!record.get("fleetSize").isBlank()) * Checks if the read carrier information are consistent. * * @param allNewCarrierInformation - * @param freightConfigGroup + * @param freightCarriersConfigGroup * @param scenario * @param polygonsInShape * @param shapeCategory */ static void checkNewCarrier(Set allNewCarrierInformation, - FreightConfigGroup freightConfigGroup, Scenario scenario, Collection polygonsInShape, String shapeCategory) { + FreightCarriersConfigGroup freightCarriersConfigGroup, Scenario scenario, Collection polygonsInShape, String shapeCategory) { - FreightUtils.addOrGetCarriers(scenario); + CarriersUtils.addOrGetCarriers(scenario); for (CarrierInformationElement carrierElement : allNewCarrierInformation) { - if (FreightUtils.getCarriers(scenario).getCarriers() + if (CarriersUtils.getCarriers(scenario).getCarriers() .containsKey(Id.create(carrierElement.getName(), Carrier.class))) throw new RuntimeException("The Carrier " + carrierElement.getName() + " being loaded from the csv is already in the given Carrier file. It is not possible to add to an existing Carrier. Please check!"); CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader(carrierVehicleTypes) - .readFile(freightConfigGroup.getCarriersVehicleTypesFile()); + .readFile(freightCarriersConfigGroup.getCarriersVehicleTypesFile()); if (carrierElement.getVehicleTypes() != null) for (String type : carrierElement.getVehicleTypes()) { if (!carrierVehicleTypes.getVehicleTypes().containsKey(Id.create(type, VehicleType.class))) @@ -410,20 +408,20 @@ static void checkNewCarrier(Set allNewCarrierInformat * * @param scenario * @param allNewCarrierInformation - * @param freightConfigGroup + * @param freightCarriersConfigGroup * @param polygonsInShape * @param defaultJspritIterations * @param crsTransformationNetworkAndShape */ static void createNewCarrierAndAddVehicleTypes(Scenario scenario, - Set allNewCarrierInformation, FreightConfigGroup freightConfigGroup, + Set allNewCarrierInformation, FreightCarriersConfigGroup freightCarriersConfigGroup, Collection polygonsInShape, int defaultJspritIterations, CoordinateTransformation crsTransformationNetworkAndShape) { - Carriers carriers = FreightUtils.addOrGetCarriers(scenario); + Carriers carriers = CarriersUtils.addOrGetCarriers(scenario); CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); - CarrierVehicleTypes usedCarrierVehicleTypes = FreightUtils.getCarrierVehicleTypes(scenario); - new CarrierVehicleTypeReader(carrierVehicleTypes).readFile(freightConfigGroup.getCarriersVehicleTypesFile()); + CarrierVehicleTypes usedCarrierVehicleTypes = CarriersUtils.getCarrierVehicleTypes(scenario); + new CarrierVehicleTypeReader(carrierVehicleTypes).readFile(freightCarriersConfigGroup.getCarriersVehicleTypesFile()); for (CarrierInformationElement singleNewCarrier : allNewCarrierInformation) { if (singleNewCarrier.getVehicleTypes() == null) { @@ -437,11 +435,11 @@ static void createNewCarrierAndAddVehicleTypes(Scenario scenario, if (carrierCapabilities.getFleetSize() == null && singleNewCarrier.getFleetSize() != null) carrierCapabilities.setFleetSize(singleNewCarrier.getFleetSize()); if (singleNewCarrier.getJspritIterations() > 0) - CarrierUtils.setJspritIterations(thisCarrier, singleNewCarrier.getJspritIterations()); + CarriersUtils.setJspritIterations(thisCarrier, singleNewCarrier.getJspritIterations()); } else { - thisCarrier = CarrierUtils.createCarrier(Id.create(singleNewCarrier.getName(), Carrier.class)); + thisCarrier = CarriersUtils.createCarrier(Id.create(singleNewCarrier.getName(), Carrier.class)); if (singleNewCarrier.getJspritIterations() > 0) - CarrierUtils.setJspritIterations(thisCarrier, singleNewCarrier.getJspritIterations()); + CarriersUtils.setJspritIterations(thisCarrier, singleNewCarrier.getJspritIterations()); carrierCapabilities = CarrierCapabilities.Builder.newInstance() .setFleetSize(singleNewCarrier.getFleetSize()).build(); carriers.addCarrier(thisCarrier); @@ -497,8 +495,8 @@ static void createNewCarrierAndAddVehicleTypes(Scenario scenario, thisCarrier.setCarrierCapabilities(carrierCapabilities); } for (Carrier carrier : carriers.getCarriers().values()) { - if (CarrierUtils.getJspritIterations(carrier) == Integer.MIN_VALUE) { - CarrierUtils.setJspritIterations(carrier, defaultJspritIterations); + if (CarriersUtils.getJspritIterations(carrier) == Integer.MIN_VALUE) { + CarriersUtils.setJspritIterations(carrier, defaultJspritIterations); log.warn("The jspritIterations are now set to the default value of " + defaultJspritIterations + " in this simulation!"); } diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java index fa3357d473c..8c1f113a6d0 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java @@ -31,8 +31,7 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.*; import org.matsim.core.network.NetworkUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.geotools.MGC; @@ -648,7 +647,7 @@ else if (samplingOption.equals("changeDemandOnLocation")) { .setCapacityDemand(demandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); - FreightUtils.getCarriers(scenario).getCarriers() + CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getServices() .put(thisService.getId(), thisService); } @@ -688,7 +687,7 @@ else if (samplingOption.equals("changeDemandOnLocation")) { .setCapacityDemand(demandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); - FreightUtils.getCarriers(scenario).getCarriers().values().iterator().next().getServices() + CarriersUtils.getCarriers(scenario).getCarriers().values().iterator().next().getServices() .put(thisService.getId(), thisService); } distributedDemand = distributedDemand + demandForThisLink; @@ -740,7 +739,7 @@ else if (samplingOption.equals("changeDemandOnLocation")) { .setCapacityDemand(demandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); - FreightUtils.getCarriers(scenario).getCarriers() + CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getServices() .put(thisService.getId(), thisService); } @@ -919,7 +918,7 @@ else if (population == null) .setPickupServiceTime(serviceTimePickup).setPickupTimeWindow(timeWindowPickup) .setDeliveryServiceTime(serviceTimeDelivery).setDeliveryTimeWindow(timeWindowDelivery) .build(); - FreightUtils.getCarriers(scenario).getCarriers() + CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getShipments() .put(thisShipment.getId(), thisShipment); } @@ -1021,7 +1020,7 @@ else if (numberOfPickupLocations != null) { .setPickupServiceTime(serviceTimePickup).setPickupTimeWindow(timeWindowPickup) .setDeliveryServiceTime(serviceTimeDelivery).setDeliveryTimeWindow(timeWindowDelivery) .build(); - FreightUtils.getCarriers(scenario).getCarriers() + CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)) .getShipments().put(thisShipment.getId(), thisShipment); } @@ -1078,7 +1077,7 @@ else if (numberOfPickupLocations != null) { .newInstance(idNewShipment, linkPickup.getId(), linkDelivery.getId(), demandForThisLink) .setPickupServiceTime(serviceTimePickup).setPickupTimeWindow(timeWindowPickup) .setDeliveryServiceTime(serviceTimeDelivery).setDeliveryTimeWindow(timeWindowDelivery).build(); - FreightUtils.getCarriers(scenario).getCarriers() + CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getShipments() .put(thisShipment.getId(), thisShipment); distributedDemand = distributedDemand + demandForThisLink; @@ -1103,10 +1102,10 @@ private static String createJobId(Scenario scenario, DemandInformationElement ne String newJobId; if (linkDelivery != null) { newJobId = "Shipment_" + linkPickup + "_" + linkDelivery; - if (FreightUtils.getCarriers(scenario).getCarriers() + if (CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getShipments() .containsKey(Id.create(newJobId, CarrierShipment.class))) { - for (int x = 1; FreightUtils.getCarriers(scenario).getCarriers() + for (int x = 1; CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getShipments() .containsKey(Id.create(newJobId, CarrierShipment.class)); x++) { newJobId = "Shipment_" + linkPickup + "_" + linkDelivery + "_" + x; @@ -1114,10 +1113,10 @@ private static String createJobId(Scenario scenario, DemandInformationElement ne } } else { newJobId = "Service_" + linkPickup; - if (FreightUtils.getCarriers(scenario).getCarriers() + if (CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getServices() .containsKey(Id.create(newJobId, CarrierShipment.class))) { - for (int x = 1; FreightUtils.getCarriers(scenario).getCarriers() + for (int x = 1; CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getServices() .containsKey(Id.create(newJobId, CarrierShipment.class)); x++) { newJobId = "Service_" + linkPickup + "_" + x; @@ -1143,7 +1142,7 @@ private static void reduceNumberOfJobsIfSameCharacteristics(Scenario scenario, if (newDemandInformationElement.getTypeOfDemand().equals("shipment")) { HashMap, CarrierShipment> shipmentsToRemove = new HashMap, CarrierShipment>(); ArrayList shipmentsToAdd = new ArrayList(); - Carrier thisCarrier = FreightUtils.getCarriers(scenario).getCarriers() + Carrier thisCarrier = CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)); for (Id baseShipmentId : thisCarrier.getShipments().keySet()) { if (!shipmentsToRemove.containsKey(baseShipmentId)) { @@ -1194,7 +1193,7 @@ private static void reduceNumberOfJobsIfSameCharacteristics(Scenario scenario, if (newDemandInformationElement.getTypeOfDemand().equals("service")) { HashMap, CarrierService> servicesToRemove = new HashMap, CarrierService>(); ArrayList servicesToAdd = new ArrayList(); - Carrier thisCarrier = FreightUtils.getCarriers(scenario).getCarriers() + Carrier thisCarrier = CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)); for (Id baseServiceId : thisCarrier.getServices().keySet()) { if (!servicesToRemove.containsKey(baseServiceId)) { diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java index 8eabf5ddb01..2f52ac86d17 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java @@ -26,17 +26,17 @@ import org.matsim.api.core.v01.population.Population; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.ShpOptions; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierPlanWriter; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.controler.CarrierModule; -import org.matsim.contrib.freight.controler.CarrierScoringFunctionFactory; -import org.matsim.contrib.freight.controler.FreightUtils; -import org.matsim.contrib.freight.usecases.chessboard.CarrierScoringFunctionFactoryImpl; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierPlanWriter; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.controler.CarrierModule; +import org.matsim.freight.carriers.controler.CarrierScoringFunctionFactory; +import org.matsim.freight.carriers.usecases.chessboard.CarrierScoringFunctionFactoryImpl; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -232,17 +232,17 @@ public Integer call() throws IOException, InvalidAttributeValueException, Execut private Config prepareConfig(int lastMATSimIteration, String coordinateSystem) { Config config = ConfigUtils.createConfig(); // ScenarioUtils.loadScenario(config); - config.controler().setOutputDirectory(outputLocation.toString()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - new OutputDirectoryHierarchy(config.controler().getOutputDirectory(), config.controler().getRunId(), - config.controler().getOverwriteFileSetting(), ControlerConfigGroup.CompressionType.gzip); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - config.controler().setLastIteration(lastMATSimIteration); + config.controller().setOutputDirectory(outputLocation.toString()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + new OutputDirectoryHierarchy(config.controller().getOutputDirectory(), config.controller().getRunId(), + config.controller().getOverwriteFileSetting(), ControllerConfigGroup.CompressionType.gzip); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + config.controller().setLastIteration(lastMATSimIteration); config.global().setRandomSeed(4177); config.global().setCoordinateSystem(coordinateSystem); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setTravelTimeSliceWidth(1800); - freightConfigGroup.setTimeWindowHandling(FreightConfigGroup.TimeWindowHandling.enforceBeginnings); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setTravelTimeSliceWidth(1800); + freightCarriersConfigGroup.setTimeWindowHandling(FreightCarriersConfigGroup.TimeWindowHandling.enforceBeginnings); return config; } @@ -281,11 +281,11 @@ private static void setNetworkAndNetworkChangeEvents(Config config, String netwo */ private static void prepareVehicles(Config config, String vehicleTypesFileLocation) { - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); if (Objects.equals(vehicleTypesFileLocation, "")) throw new RuntimeException("No path to the vehicleTypes selected"); else { - freightConfigGroup.setCarriersVehicleTypesFile(vehicleTypesFileLocation); + freightCarriersConfigGroup.setCarriersVehicleTypesFile(vehicleTypesFileLocation); log.info("Get vehicleTypes from: " + vehicleTypesFileLocation); } } @@ -306,8 +306,8 @@ private void createCarrier(Scenario scenario, CarrierInputOptions selectedCarrie String carriersFileLocation, Path csvLocationCarrier, Collection polygonsInShape, int defaultJspritIterations, CoordinateTransformation crsTransformationNetworkAndShape) throws IOException { - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(scenario.getConfig(), - FreightConfigGroup.class); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(scenario.getConfig(), + FreightCarriersConfigGroup.class); switch (selectedCarrierInputOption) { case addCSVDataToExistingCarrierFileData -> { // reads an existing carrier file and adds the information based on the read csv @@ -315,10 +315,10 @@ private void createCarrier(Scenario scenario, CarrierInputOptions selectedCarrie if (Objects.equals(carriersFileLocation, "")) throw new RuntimeException("No path to the carrier file selected"); else { - freightConfigGroup.setCarriersFile(carriersFileLocation); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); + freightCarriersConfigGroup.setCarriersFile(carriersFileLocation); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); log.info("Load carriers from: " + carriersFileLocation); - CarrierReaderFromCSV.readAndCreateCarrierFromCSV(scenario, freightConfigGroup, csvLocationCarrier, + CarrierReaderFromCSV.readAndCreateCarrierFromCSV(scenario, freightCarriersConfigGroup, csvLocationCarrier, polygonsInShape, defaultJspritIterations, crsTransformationNetworkAndShape, shapeCategory); } } @@ -327,14 +327,14 @@ private void createCarrier(Scenario scenario, CarrierInputOptions selectedCarrie if (Objects.equals(carriersFileLocation, "")) throw new RuntimeException("No path to the carrier file selected"); else { - freightConfigGroup.setCarriersFile(carriersFileLocation); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); + freightCarriersConfigGroup.setCarriersFile(carriersFileLocation); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); log.info("Load carriers from: " + carriersFileLocation); } } case createCarriersFromCSV -> // creates all carriers based on the given information in the read carrier csv - CarrierReaderFromCSV.readAndCreateCarrierFromCSV(scenario, freightConfigGroup, csvLocationCarrier, + CarrierReaderFromCSV.readAndCreateCarrierFromCSV(scenario, freightCarriersConfigGroup, csvLocationCarrier, polygonsInShape, defaultJspritIterations, crsTransformationNetworkAndShape, shapeCategory); default -> throw new RuntimeException("no method to create or read carrier selected."); } @@ -415,7 +415,7 @@ private void createDemand(DemandGenerationOptions selectedDemandGenerationOption case useDemandFromCarrierFile -> { // use only the given demand of the read carrier file boolean oneCarrierHasJobs = false; - for (Carrier carrier : FreightUtils.getCarriers(scenario).getCarriers().values()) + for (Carrier carrier : CarriersUtils.getCarriers(scenario).getCarriers().values()) if (carrier.getServices().isEmpty() && carrier.getShipments().isEmpty()) log.warn(carrier.getId().toString() + " has no jobs which can be used"); else { @@ -462,29 +462,29 @@ private static void solveSelectedSolution(OptionsOfVRPSolutions selectedSolution case runJspritAndMATSim -> { // solves the VRP with jsprit and runs MATSim afterwards new CarrierPlanWriter((Carriers) controler.getScenario().getScenarioElement("carriers")) - .write(config.controler().getOutputDirectory() + "/output_carriersNoPlans.xml"); + .write(config.controller().getOutputDirectory() + "/output_carriersNoPlans.xml"); runJsprit(controler, false); controler.run(); new CarrierPlanWriter((Carriers) controler.getScenario().getScenarioElement("carriers")) - .write(config.controler().getOutputDirectory() + "/output_carriersWithPlans.xml"); + .write(config.controller().getOutputDirectory() + "/output_carriersWithPlans.xml"); } case runJspritAndMATSimWithDistanceConstraint -> { // solves the VRP with jsprit by using the distance constraint and runs MATSim // afterwards new CarrierPlanWriter((Carriers) controler.getScenario().getScenarioElement("carriers")) - .write(config.controler().getOutputDirectory() + "/output_carriersNoPlans.xml"); + .write(config.controller().getOutputDirectory() + "/output_carriersNoPlans.xml"); runJsprit(controler, true); controler.run(); new CarrierPlanWriter((Carriers) controler.getScenario().getScenarioElement("carriers")) - .write(config.controler().getOutputDirectory() + "/output_carriersWithPlans.xml"); + .write(config.controller().getOutputDirectory() + "/output_carriersWithPlans.xml"); } case runJsprit -> { // solves only the VRP with jsprit new CarrierPlanWriter((Carriers) controler.getScenario().getScenarioElement("carriers")) - .write(config.controler().getOutputDirectory() + "/output_carriersNoPlans.xml"); + .write(config.controller().getOutputDirectory() + "/output_carriersNoPlans.xml"); runJsprit(controler, false); new CarrierPlanWriter((Carriers) controler.getScenario().getScenarioElement("carriers")) - .write(config.controler().getOutputDirectory() + "/output_carriersWithPlans.xml"); + .write(config.controller().getOutputDirectory() + "/output_carriersWithPlans.xml"); log.warn( "##Finished with the jsprit solution. If you also want to run MATSim, please change case of optionsOfVRPSolutions"); System.exit(0); @@ -492,10 +492,10 @@ private static void solveSelectedSolution(OptionsOfVRPSolutions selectedSolution case runJspritWithDistanceConstraint -> { // solves only the VRP with jsprit by using the distance constraint new CarrierPlanWriter((Carriers) controler.getScenario().getScenarioElement("carriers")) - .write(config.controler().getOutputDirectory() + "/output_carriersNoPlans.xml"); + .write(config.controller().getOutputDirectory() + "/output_carriersNoPlans.xml"); runJsprit(controler, true); new CarrierPlanWriter((Carriers) controler.getScenario().getScenarioElement("carriers")) - .write(config.controler().getOutputDirectory() + "/output_carriersWithPlans.xml"); + .write(config.controller().getOutputDirectory() + "/output_carriersWithPlans.xml"); log.warn( "##Finished with the jsprit solution. If you also want to run MATSim, please change case of optionsOfVRPSolutions"); System.exit(0); @@ -504,7 +504,7 @@ private static void solveSelectedSolution(OptionsOfVRPSolutions selectedSolution // creates no solution of the VRP and only writes the carrier file with the // generated carriers and demands new CarrierPlanWriter((Carriers) controler.getScenario().getScenarioElement("carriers")) - .write(config.controler().getOutputDirectory() + "/output_carriersNoPlans.xml"); + .write(config.controller().getOutputDirectory() + "/output_carriersNoPlans.xml"); log.warn( "##Finished without solution of the VRP. If you also want to run jsprit and/or MATSim, please change case of optionsOfVRPSolutions"); System.exit(0); @@ -524,11 +524,11 @@ private static void solveSelectedSolution(OptionsOfVRPSolutions selectedSolution */ private static void runJsprit(Controler controler, boolean usingRangeRestriction) throws ExecutionException, InterruptedException { - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(controler.getConfig(), - FreightConfigGroup.class); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(controler.getConfig(), + FreightCarriersConfigGroup.class); if (usingRangeRestriction) - freightConfigGroup.setUseDistanceConstraintForTourPlanning( - FreightConfigGroup.UseDistanceConstraintForTourPlanning.basedOnEnergyConsumption); - FreightUtils.runJsprit(controler.getScenario()); + freightCarriersConfigGroup.setUseDistanceConstraintForTourPlanning( + FreightCarriersConfigGroup.UseDistanceConstraintForTourPlanning.basedOnEnergyConsumption); + CarriersUtils.runJsprit(controler.getScenario()); } } diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGenerationUtils.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGenerationUtils.java index 6c4a09703c4..b2d70951be8 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGenerationUtils.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGenerationUtils.java @@ -29,10 +29,10 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.*; import org.matsim.application.options.ShpOptions; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierService; -import org.matsim.contrib.freight.carrier.CarrierShipment; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierService; +import org.matsim.freight.carriers.CarrierShipment; +import org.matsim.freight.carriers.CarriersUtils; import org.matsim.core.controler.Controler; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.geotools.MGC; @@ -99,11 +99,11 @@ static void preparePopulation(Population population, double sampleSizeInputPopul static void createDemandLocationsFile(Controler controler) { Network network = controler.getScenario().getNetwork(); - File file = new File(controler.getConfig().controler().getOutputDirectory() + "/outputFacilitiesFile.tsv"); + File file = new File(controler.getConfig().controller().getOutputDirectory() + "/outputFacilitiesFile.tsv"); try (FileWriter writer = new FileWriter(file, true)) { writer.write("id x y type ServiceLocation pickupLocation deliveryLocation\n"); - for (Carrier thisCarrier : FreightUtils.getCarriers(controler.getScenario()).getCarriers().values()) { + for (Carrier thisCarrier : CarriersUtils.getCarriers(controler.getScenario()).getCarriers().values()) { for (CarrierService thisService : thisCarrier.getServices().values()) { Coord coord = FreightDemandGenerationUtils .getCoordOfMiddlePointOfLink(network.getLinks().get(thisService.getLocationLinkId())); 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 0c72be12c3b..0f788f5f9d6 100644 --- a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java +++ b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java @@ -38,14 +38,13 @@ import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.ShpOptions; import org.matsim.application.options.ShpOptions.Index; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; -import org.matsim.contrib.freight.controler.*; -import org.matsim.contrib.freight.usecases.chessboard.CarrierTravelDisutilities; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.controler.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; +import org.matsim.freight.carriers.usecases.chessboard.CarrierTravelDisutilities; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.VspExperimentalConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; @@ -172,34 +171,34 @@ public Integer call() throws Exception { Config config = readAndCheckConfig(configPath, modelName, sampleName, output); - output = Path.of(config.controler().getOutputDirectory()); + output = Path.of(config.controller().getOutputDirectory()); Scenario scenario = ScenarioUtils.loadScenario(config); NetworkUtils.runNetworkCleaner(scenario.getNetwork()); // e.g. for vulkaneifel network - FreightConfigGroup freightConfigGroup; + FreightCarriersConfigGroup freightCarriersConfigGroup; switch (usedCreationOption) { case useExistingCarrierFileWithSolution -> { log.info("Existing carriers (including carrier vehicle types ) should be set in the freight config group"); if (includeExistingModels) throw new Exception( "You set that existing models should included to the new model. This is only possible for a creation of the new carrier file and not by using an existing."); - freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - if (config.vehicles() != null && freightConfigGroup.getCarriersVehicleTypesFile() == null) - freightConfigGroup.setCarriersVehicleTypesFile(config.vehicles().getVehiclesFile()); - log.info("Load carriers from: " + freightConfigGroup.getCarriersFile()); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); + freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + if (config.vehicles() != null && freightCarriersConfigGroup.getCarriersVehicleTypesFile() == null) + freightCarriersConfigGroup.setCarriersVehicleTypesFile(config.vehicles().getVehiclesFile()); + log.info("Load carriers from: " + freightCarriersConfigGroup.getCarriersFile()); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); } case useExistingCarrierFileWithoutSolution -> { log.info("Existing carriers (including carrier vehicle types ) should be set in the freight config group"); if (includeExistingModels) throw new Exception( "You set that existing models should included to the new model. This is only possible for a creation of the new carrier file and not by using an existing."); - freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - if (config.vehicles() != null && freightConfigGroup.getCarriersVehicleTypesFile() == null) - freightConfigGroup.setCarriersVehicleTypesFile(config.vehicles().getVehiclesFile()); - log.info("Load carriers from: " + freightConfigGroup.getCarriersFile()); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); + freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + if (config.vehicles() != null && freightCarriersConfigGroup.getCarriersVehicleTypesFile() == null) + freightCarriersConfigGroup.setCarriersVehicleTypesFile(config.vehicles().getVehiclesFile()); + log.info("Load carriers from: " + freightCarriersConfigGroup.getCarriersFile()); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); solveSeparatedVRPs(scenario, null); } default -> { @@ -236,23 +235,23 @@ public Integer call() throws Exception { } default -> throw new RuntimeException("No traffic type selected."); } - if (config.controler().getRunId() == null) - new CarrierPlanWriter(FreightUtils.addOrGetCarriers(scenario)) - .write(scenario.getConfig().controler().getOutputDirectory() + "/output_CarrierDemand.xml"); + if (config.controller().getRunId() == null) + new CarrierPlanWriter(CarriersUtils.addOrGetCarriers(scenario)) + .write(scenario.getConfig().controller().getOutputDirectory() + "/output_CarrierDemand.xml"); else - new CarrierPlanWriter(FreightUtils.addOrGetCarriers(scenario)) - .write(scenario.getConfig().controler().getOutputDirectory() + "/" - + scenario.getConfig().controler().getRunId() + ".output_CarrierDemand.xml"); + new CarrierPlanWriter(CarriersUtils.addOrGetCarriers(scenario)) + .write(scenario.getConfig().controller().getOutputDirectory() + "/" + + scenario.getConfig().controller().getRunId() + ".output_CarrierDemand.xml"); solveSeparatedVRPs(scenario, regionLinksMap); } } - if (config.controler().getRunId() == null) - new CarrierPlanWriter(FreightUtils.addOrGetCarriers(scenario)).write( - scenario.getConfig().controler().getOutputDirectory() + "/output_CarrierDemandWithPlans.xml"); + if (config.controller().getRunId() == null) + new CarrierPlanWriter(CarriersUtils.addOrGetCarriers(scenario)).write( + scenario.getConfig().controller().getOutputDirectory() + "/output_CarrierDemandWithPlans.xml"); else - new CarrierPlanWriter(FreightUtils.addOrGetCarriers(scenario)) + new CarrierPlanWriter(CarriersUtils.addOrGetCarriers(scenario)) .write( - scenario.getConfig().controler().getOutputDirectory() + "/" + scenario.getConfig().controler().getRunId() + ".output_CarrierDemandWithPlans.xml"); + scenario.getConfig().controller().getOutputDirectory() + "/" + scenario.getConfig().controller().getRunId() + ".output_CarrierDemandWithPlans.xml"); Controler controler = prepareControler(scenario); controler.run(); SmallScaleCommercialTrafficUtils.createPlansBasedOnCarrierPlans(controler.getScenario(), @@ -270,11 +269,11 @@ private void solveSeparatedVRPs(Scenario originalScenario, Map, Carrier> allCarriers = new HashMap<>( - FreightUtils.getCarriers(originalScenario).getCarriers()); + CarriersUtils.getCarriers(originalScenario).getCarriers()); Map, Carrier> solvedCarriers = new HashMap<>(); List> keyList = new ArrayList<>(allCarriers.keySet()); - FreightUtils.getCarriers(originalScenario).getCarriers().values().forEach(carrier -> { - if (CarrierUtils.getJspritIterations(carrier) == 0) { + CarriersUtils.getCarriers(originalScenario).getCarriers().values().forEach(carrier -> { + if (CarriersUtils.getJspritIterations(carrier) == 0) { allCarriers.remove(carrier.getId()); solvedCarriers.put(carrier.getId(), carrier); } @@ -320,7 +319,7 @@ private void solveSeparatedVRPs(Scenario originalScenario, Map newCarrier.getAttributes() .putAttribute(attribute, carrier.getAttributes().getAttribute(attribute))); @@ -369,18 +368,18 @@ private void solveSeparatedVRPs(Scenario originalScenario, Map { + CarriersUtils.getCarriers(originalScenario).getCarriers().putAll(solvedCarriers); + CarriersUtils.getCarriers(originalScenario).getCarriers().values().forEach(carrier -> { if (regionLinksMap != null && !carrier.getAttributes().getAsMap().containsKey("tourStartArea")) { List startAreas = new ArrayList<>(); for (ScheduledTour tour : carrier.getSelectedPlan().getScheduledTours()) { @@ -433,15 +432,15 @@ private Config readAndCheckConfig(Path configPath, String modelName, String samp Config config = ConfigUtils.loadConfig(configPath.toString()); if (output == null || output.toString().isEmpty()) - config.controler().setOutputDirectory(Path.of(config.controler().getOutputDirectory()).resolve(modelName) + config.controller().setOutputDirectory(Path.of(config.controller().getOutputDirectory()).resolve(modelName) .resolve(usedSmallScaleCommercialTrafficType.toString() + "_" + sampleName + "pct" + "_" + java.time.LocalDate.now() + "_" + java.time.LocalTime.now().toSecondOfDay() + "_" + resistanceFactor) .toString()); else - config.controler().setOutputDirectory(output.toString()); - new OutputDirectoryHierarchy(config.controler().getOutputDirectory(), config.controler().getRunId(), - config.controler().getOverwriteFileSetting(), ControlerConfigGroup.CompressionType.gzip); - new File(Path.of(config.controler().getOutputDirectory()).resolve("calculatedData").toString()).mkdir(); + config.controller().setOutputDirectory(output.toString()); + 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"); @@ -449,7 +448,7 @@ private Config readAndCheckConfig(Path configPath, String modelName, String samp 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.controler().getOutputDirectory() == null) + if (config.controller().getOutputDirectory() == null) throw new Exception("No output directory was set"); return config; @@ -466,7 +465,7 @@ private Controler prepareControler(Scenario scenario) { @Override public void install() { bind(CarrierStrategyManager.class).toProvider( - new MyCarrierPlanStrategyManagerFactory(FreightUtils.getCarrierVehicleTypes(scenario))); + new MyCarrierPlanStrategyManagerFactory(CarriersUtils.getCarrierVehicleTypes(scenario))); bind(CarrierScoringFunctionFactory.class).toInstance(new MyCarrierScoringFunctionFactory()); } }); @@ -490,7 +489,7 @@ private void createCarriers(Scenario scenario, TripDistributionMatrix odMatrix, Map stopDurationTimeSelector = createStopDurationTimeDistributionPerCategory( smallScaleCommercialTrafficType); - CarrierVehicleTypes carrierVehicleTypes = FreightUtils.getCarrierVehicleTypes(scenario); + CarrierVehicleTypes carrierVehicleTypes = CarriersUtils.getCarrierVehicleTypes(scenario); Map, VehicleType> additionalCarrierVehicleTypes = scenario.getVehicles().getVehicleTypes(); additionalCarrierVehicleTypes.values().forEach( vehicleType -> carrierVehicleTypes.getVehicleTypes().putIfAbsent(vehicleType.getId(), vehicleType)); @@ -583,7 +582,7 @@ private void createCarriers(Scenario scenario, TripDistributionMatrix odMatrix, assert possibleVehicleTypes != null; for (String possibleVehicleType : possibleVehicleTypes) { - if (FreightUtils.getCarrierVehicleTypes(scenario).getVehicleTypes().containsKey( + if (CarriersUtils.getCarrierVehicleTypes(scenario).getVehicleTypes().containsKey( Id.create(possibleVehicleType, VehicleType.class))) vehicleTypes.add(possibleVehicleType); } @@ -675,7 +674,7 @@ private void createServices(Scenario scenario, ArrayList noPossibleLinks CarrierService thisService = CarrierService.Builder.newInstance(idNewService, linkId) .setServiceDuration(serviceTimePerStop).setServiceStartTimeWindow(serviceTimeWindow).build(); - FreightUtils.getCarriers(scenario).getCarriers().get(Id.create(carrierName, Carrier.class)).getServices() + CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create(carrierName, Carrier.class)).getServices() .put(thisService.getId(), thisService); } @@ -693,12 +692,12 @@ private void createNewCarrierAndAddVehicleTypes(Scenario scenario, Integer purpo ValueSelectorUnderGivenProbability tourStartTimeSelector, ValueSelectorUnderGivenProbability tourDurationTimeSelector) { - Carriers carriers = FreightUtils.addOrGetCarriers(scenario); - CarrierVehicleTypes carrierVehicleTypes = FreightUtils.getCarrierVehicleTypes(scenario); + Carriers carriers = CarriersUtils.addOrGetCarriers(scenario); + CarrierVehicleTypes carrierVehicleTypes = CarriersUtils.getCarrierVehicleTypes(scenario); CarrierCapabilities carrierCapabilities; - Carrier thisCarrier = CarrierUtils.createCarrier(Id.create(carrierName, Carrier.class)); + Carrier thisCarrier = CarriersUtils.createCarrier(Id.create(carrierName, Carrier.class)); if (smallScaleCommercialTrafficType.equals("commercialPersonTraffic") && purpose == 3) thisCarrier.getAttributes().putAttribute("subpopulation", smallScaleCommercialTrafficType + "_service"); else @@ -707,7 +706,7 @@ private void createNewCarrierAndAddVehicleTypes(Scenario scenario, Integer purpo thisCarrier.getAttributes().putAttribute("purpose", purpose); thisCarrier.getAttributes().putAttribute("tourStartArea", startZone); if (jspritIterations > 0) - CarrierUtils.setJspritIterations(thisCarrier, jspritIterations); + CarriersUtils.setJspritIterations(thisCarrier, jspritIterations); carrierCapabilities = CarrierCapabilities.Builder.newInstance().setFleetSize(fleetSize).build(); carriers.addCarrier(thisCarrier); @@ -971,7 +970,7 @@ public CarrierStrategyManager get() { travelDisutility, modeTravelTimes.get(TransportMode.car)); // final GenericStrategyManager strategyManager = new GenericStrategyManager<>(); - final CarrierStrategyManager strategyManager = FreightUtils.createDefaultCarrierStrategyManager(); + final CarrierStrategyManager strategyManager = CarrierControlerUtils.createDefaultCarrierStrategyManager(); strategyManager.setMaxPlansPerAgent(5); { GenericPlanStrategyImpl strategy = new GenericPlanStrategyImpl<>( @@ -1085,7 +1084,7 @@ private double getDistanceParameter(CarrierVehicle vehicle) { public void handleLeg(Leg leg) { if (leg.getRoute() instanceof NetworkRoute nRoute) { Id vehicleId = nRoute.getVehicleId(); - CarrierVehicle vehicle = CarrierUtils.getCarrierVehicle(carrier, vehicleId); + CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); Gbl.assertNotNull(vehicle); employedVehicles.add(vehicle); double distance = 0.0; 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 9d7ab8ad305..3d8563424a1 100644 --- a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java +++ b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java @@ -40,19 +40,20 @@ import org.matsim.api.core.v01.population.*; import org.matsim.application.options.ShpOptions; import org.matsim.application.options.ShpOptions.Index; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; -import org.matsim.contrib.freight.carrier.Tour.Pickup; -import org.matsim.contrib.freight.carrier.Tour.ServiceActivity; -import org.matsim.contrib.freight.carrier.Tour.TourElement; -import org.matsim.contrib.freight.controler.FreightUtils; -import org.matsim.contrib.freight.jsprit.MatsimJspritFactory; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; +import org.matsim.freight.carriers.Tour.Pickup; +import org.matsim.freight.carriers.Tour.ServiceActivity; +import org.matsim.freight.carriers.Tour.TourElement; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.utils.io.IOUtils; +import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; +import org.matsim.vehicles.Vehicles; import java.io.BufferedWriter; import java.io.IOException; @@ -170,7 +171,7 @@ private static void writeCSVWithCategoryHeader(HashMap idCounter = new HashMap<>(); Population populationFromCarrier = (Population) scenario.getScenarioElement("allpersons"); + Vehicles allVehicles = VehicleUtils.getOrCreateAllvehicles(scenario); + for (Person person : populationFromCarrier.getPersons().values()) { Plan plan = popFactory.createPlan(); String carrierName = person.getId().toString().split("freight_")[1].split("_veh_")[0]; - Carrier relatedCarrier = FreightUtils.addOrGetCarriers(scenario).getCarriers() + Carrier relatedCarrier = CarriersUtils.addOrGetCarriers(scenario).getCarriers() .get(Id.create(carrierName, Carrier.class)); String subpopulation = relatedCarrier.getAttributes().getAttribute("subpopulation").toString(); final String mode; @@ -239,11 +242,12 @@ else if (subpopulation.contains("goodsTraffic")) if (relatedCarrier.getAttributes().getAsMap().containsKey("tourStartArea")) newPerson.getAttributes().putAttribute("tourStartArea", relatedCarrier.getAttributes().getAttribute("tourStartArea")); - VehicleUtils.insertVehicleIdsIntoAttributes(newPerson, (new HashMap<>() { - { - put(mode, (Id.createVehicleId(person.getId().toString()))); - } - })); + + Id vehicleId = Id.createVehicleId(person.getId().toString()); + + VehicleUtils.insertVehicleIdsIntoAttributes(newPerson, Map.of(mode, vehicleId)); + VehicleUtils.insertVehicleTypesIntoAttributes(newPerson, Map.of(mode, allVehicles.getVehicles().get(vehicleId).getType().getId())); + population.addPerson(newPerson); } @@ -460,10 +464,10 @@ static void readExistingModels(Scenario scenario, double sampleScenario, } } carrierToRemove.forEach(carrier -> carriers.getCarriers().remove(carrier.getId())); - FreightUtils.getCarrierVehicleTypes(scenario).getVehicleTypes().putAll(usedVehicleTypes.getVehicleTypes()); + CarriersUtils.getCarrierVehicleTypes(scenario).getVehicleTypes().putAll(usedVehicleTypes.getVehicleTypes()); carriers.getCarriers().values().forEach(carrier -> { - Carrier newCarrier = CarrierUtils + Carrier newCarrier = CarriersUtils .createCarrier(Id.create(modelName + "_" + carrier.getId().toString(), Carrier.class)); newCarrier.getAttributes().putAttribute("subpopulation", modelTrafficType); if (modelPurpose != null) @@ -490,7 +494,7 @@ else if (!carrier.getShipments().isEmpty()) newCarrier.getAttributes().putAttribute("tourStartArea", String.join(";", startAreas)); - CarrierUtils.setJspritIterations(newCarrier, 0); + CarriersUtils.setJspritIterations(newCarrier, 0); // recalculate score for selectedPlan VehicleRoutingProblem vrp = MatsimJspritFactory .createRoutingProblemBuilder(carrier, scenario.getNetwork()).build(); @@ -500,10 +504,10 @@ else if (!carrier.getShipments().isEmpty()) double costs = solutionCostsCalculator.getCosts(solution) * (-1); carrier.getSelectedPlan().setScore(costs); } else { - CarrierUtils.setJspritIterations(newCarrier, CarrierUtils.getJspritIterations(carrier)); + CarriersUtils.setJspritIterations(newCarrier, CarriersUtils.getJspritIterations(carrier)); newCarrier.getCarrierCapabilities().setFleetSize(carrier.getCarrierCapabilities().getFleetSize()); } - FreightUtils.addOrGetCarriers(scenario).getCarriers().put(newCarrier.getId(), newCarrier); + CarriersUtils.addOrGetCarriers(scenario).getCarriers().put(newCarrier.getId(), newCarrier); }); } } 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 6f747bc2ee5..ada637b06d7 100644 --- a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGeneration.java +++ b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGeneration.java @@ -27,11 +27,10 @@ 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.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.Tour.Pickup; -import org.matsim.contrib.freight.carrier.Tour.ServiceActivity; -import org.matsim.contrib.freight.carrier.Tour.TourElement; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.Tour.Pickup; +import org.matsim.freight.carriers.Tour.ServiceActivity; +import org.matsim.freight.carriers.Tour.TourElement; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.utils.io.IOUtils; @@ -278,7 +277,7 @@ static void reduceDemandBasedOnExistingCarriers(Scenario scenario, HashMap> trafficVolumePerTypeAndZone_start, HashMap> trafficVolumePerTypeAndZone_stop) { - for (Carrier carrier : FreightUtils.addOrGetCarriers(scenario).getCarriers().values()) { + for (Carrier carrier : CarriersUtils.addOrGetCarriers(scenario).getCarriers().values()) { if (!carrier.getAttributes().getAsMap().containsKey("subpopulation") || !carrier.getAttributes().getAttribute("subpopulation").equals(smallScaleCommercialTrafficType)) continue; 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 698f43a967a..68c03dedb7e 100644 --- a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrix.java +++ b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrix.java @@ -33,9 +33,8 @@ 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.contrib.freight.jsprit.NetworkBasedTransportCosts; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; import org.opengis.feature.simple.SimpleFeature; @@ -43,6 +42,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.net.MalformedURLException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; diff --git a/contribs/application/src/test/java/org/matsim/application/MATSimApplicationTest.java b/contribs/application/src/test/java/org/matsim/application/MATSimApplicationTest.java index 69931f9032c..9be98d76122 100644 --- a/contribs/application/src/test/java/org/matsim/application/MATSimApplicationTest.java +++ b/contribs/application/src/test/java/org/matsim/application/MATSimApplicationTest.java @@ -11,7 +11,7 @@ import org.matsim.application.prepare.population.TrajectoryToPlans; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.utils.io.IOUtils; @@ -47,7 +47,7 @@ public void config() { Config config = controler.getConfig(); - assertThat(config.controler().getRunId()).isEqualTo("Test123"); + assertThat(config.controller().getRunId()).isEqualTo("Test123"); assertThat(config.global().getNumberOfThreads()).isEqualTo(4); assertThat(config.plans().getInputCRS()).isEqualTo("EPSG:1234"); @@ -60,12 +60,12 @@ public void yaml() { Controler controler = MATSimApplication.prepare(TestScenario.class, ConfigUtils.createConfig(), "--yaml", yml.toString()); - assertThat(controler.getConfig().controler().getRunId()) + assertThat(controler.getConfig().controller().getRunId()) .isEqualTo("567"); - PlanCalcScoreConfigGroup score = controler.getConfig().planCalcScore(); + ScoringConfigGroup score = controler.getConfig().scoring(); - PlanCalcScoreConfigGroup.ScoringParameterSet params = score.getScoringParameters(null); + ScoringConfigGroup.ScoringParameterSet params = score.getScoringParameters(null); assertThat(params.getOrCreateModeParams("car").getConstant()) .isEqualTo(-1); @@ -81,12 +81,12 @@ public void sample() { Controler controler = MATSimApplication.prepare(TestScenario.class, ConfigUtils.createConfig(), "--10pct"); - assertThat(controler.getConfig().controler().getRunId()) + assertThat(controler.getConfig().controller().getRunId()) .isEqualTo("run-10pct"); controler = MATSimApplication.prepare(TestScenario.class, ConfigUtils.createConfig()); - assertThat(controler.getConfig().controler().getRunId()) + assertThat(controler.getConfig().controller().getRunId()) .isEqualTo("run-25pct"); } @@ -166,9 +166,9 @@ public void run() { Config config = ConfigUtils.createConfig(); Path out = Path.of(utils.getOutputDirectory()).resolve("out"); - config.controler().setOutputDirectory(out.toString()); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(1); + config.controller().setOutputDirectory(out.toString()); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(1); int ret = MATSimApplication.execute(TestScenario.class, config); @@ -197,7 +197,7 @@ public TestScenario() { @Override protected Config prepareConfig(Config config) { - config.controler().setRunId(sample.adjustName("run-25pct")); + config.controller().setRunId(sample.adjustName("run-25pct")); return config; } diff --git a/contribs/application/src/test/java/org/matsim/application/analysis/LogFileAnalysisTest.java b/contribs/application/src/test/java/org/matsim/application/analysis/LogFileAnalysisTest.java index 13c79e7877e..4b1c121aa72 100644 --- a/contribs/application/src/test/java/org/matsim/application/analysis/LogFileAnalysisTest.java +++ b/contribs/application/src/test/java/org/matsim/application/analysis/LogFileAnalysisTest.java @@ -24,15 +24,15 @@ public void output() throws IOException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(2); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(2); int execute = MATSimApplication.execute(MATSimApplicationTest.TestScenario.class, config); Assertions.assertThat(execute) .isEqualTo(0); - Path out = Path.of(config.controler().getOutputDirectory()); + Path out = Path.of(config.controller().getOutputDirectory()); new LogFileAnalysis().execute( "--input", ApplicationUtils.matchInput("logfile.log", out).toString(), "--output-memory-stats", out.resolve("mem_stats.csv").toString(), diff --git a/contribs/application/src/test/java/org/matsim/freightDemandGeneration/CarrierReaderFromCSVTest.java b/contribs/application/src/test/java/org/matsim/freightDemandGeneration/CarrierReaderFromCSVTest.java index cca68b4d44b..9d2ec63b41c 100644 --- a/contribs/application/src/test/java/org/matsim/freightDemandGeneration/CarrierReaderFromCSVTest.java +++ b/contribs/application/src/test/java/org/matsim/freightDemandGeneration/CarrierReaderFromCSVTest.java @@ -17,12 +17,11 @@ 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.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.controler.FreightUtils; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; -import org.matsim.contrib.freight.carrier.CarrierUtils; -import org.matsim.contrib.freight.carrier.CarrierVehicle; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.CarrierVehicle; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.NetworkUtils; @@ -49,9 +48,9 @@ public void carrierCreation() throws IOException { config.network().setInputFile( "https://raw.githubusercontent.com/matsim-org/matsim/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"); Scenario scenario = ScenarioUtils.loadScenario(config); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(scenario.getConfig(), - FreightConfigGroup.class); - freightConfigGroup.setCarriersVehicleTypesFile(utils.getPackageInputDirectory() + "testVehicleTypes.xml"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(scenario.getConfig(), + FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setCarriersVehicleTypesFile(utils.getPackageInputDirectory() + "testVehicleTypes.xml"); Path carrierCSVLocation = Path.of(utils.getPackageInputDirectory() + "testCarrierCSV.csv"); Path shapeFilePath = Path.of(utils.getPackageInputDirectory() + "testShape/testShape.shp"); ShpOptions shp = new ShpOptions(shapeFilePath, "WGS84", null); @@ -59,22 +58,22 @@ public void carrierCreation() throws IOException { Set allNewCarrierInformation = CarrierReaderFromCSV .readCarrierInformation(carrierCSVLocation); String shapeCategory = "Ortsteil"; - CarrierReaderFromCSV.checkNewCarrier(allNewCarrierInformation, freightConfigGroup, scenario, polygonsInShape, shapeCategory); - CarrierReaderFromCSV.createNewCarrierAndAddVehicleTypes(scenario, allNewCarrierInformation, freightConfigGroup, + CarrierReaderFromCSV.checkNewCarrier(allNewCarrierInformation, freightCarriersConfigGroup, scenario, polygonsInShape, shapeCategory); + CarrierReaderFromCSV.createNewCarrierAndAddVehicleTypes(scenario, allNewCarrierInformation, freightCarriersConfigGroup, polygonsInShape, 1, null); - Assert.assertEquals(3, FreightUtils.getCarriers(scenario).getCarriers().size()); + Assert.assertEquals(3, CarriersUtils.getCarriers(scenario).getCarriers().size()); Assert.assertTrue( - FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier1", Carrier.class))); + CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier1", Carrier.class))); Assert.assertTrue( - FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier2", Carrier.class))); + CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier2", Carrier.class))); Assert.assertTrue( - FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier3", Carrier.class))); + CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier3", Carrier.class))); // check carrier 1 - Carrier testCarrier1 = FreightUtils.getCarriers(scenario).getCarriers() + Carrier testCarrier1 = CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create("testCarrier1", Carrier.class)); Assert.assertEquals(FleetSize.INFINITE, testCarrier1.getCarrierCapabilities().getFleetSize()); - Assert.assertEquals(10, CarrierUtils.getJspritIterations(testCarrier1)); + Assert.assertEquals(10, CarriersUtils.getJspritIterations(testCarrier1)); Assert.assertEquals(4, testCarrier1.getCarrierCapabilities().getCarrierVehicles().size()); Object2IntMap depotSums = new Object2IntOpenHashMap<>(); Map> typesPerDepot = new HashMap<>(); @@ -101,10 +100,10 @@ public void carrierCreation() throws IOException { Assert.assertTrue(typesPerDepot.get("j(2,4)R").contains("testVehicle2")); // check carrier 2 - Carrier testCarrier2 = FreightUtils.getCarriers(scenario).getCarriers() + Carrier testCarrier2 = CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create("testCarrier2", Carrier.class)); Assert.assertEquals(FleetSize.FINITE, testCarrier2.getCarrierCapabilities().getFleetSize()); - Assert.assertEquals(15, CarrierUtils.getJspritIterations(testCarrier2)); + Assert.assertEquals(15, CarriersUtils.getJspritIterations(testCarrier2)); Assert.assertEquals(9, testCarrier2.getCarrierCapabilities().getCarrierVehicles().size()); depotSums = new Object2IntOpenHashMap<>(); typesPerDepot = new HashMap<>(); @@ -126,10 +125,10 @@ public void carrierCreation() throws IOException { // check carrier 3 Network network = NetworkUtils.readNetwork( "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"); - Carrier testCarrier3 = FreightUtils.getCarriers(scenario).getCarriers() + Carrier testCarrier3 = CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create("testCarrier3", Carrier.class)); Assert.assertEquals(FleetSize.INFINITE, testCarrier3.getCarrierCapabilities().getFleetSize()); - Assert.assertEquals(1, CarrierUtils.getJspritIterations(testCarrier3)); + Assert.assertEquals(1, CarriersUtils.getJspritIterations(testCarrier3)); Assert.assertEquals(2, testCarrier3.getCarrierCapabilities().getCarrierVehicles().size()); depotSums = new Object2IntOpenHashMap<>(); typesPerDepot = new HashMap<>(); diff --git a/contribs/application/src/test/java/org/matsim/freightDemandGeneration/DemandReaderFromCSVTest.java b/contribs/application/src/test/java/org/matsim/freightDemandGeneration/DemandReaderFromCSVTest.java index fdc2aa30d12..d9ff39a695c 100644 --- a/contribs/application/src/test/java/org/matsim/freightDemandGeneration/DemandReaderFromCSVTest.java +++ b/contribs/application/src/test/java/org/matsim/freightDemandGeneration/DemandReaderFromCSVTest.java @@ -18,12 +18,7 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; import org.matsim.application.options.ShpOptions; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierService; -import org.matsim.contrib.freight.carrier.CarrierShipment; -import org.matsim.contrib.freight.carrier.TimeWindow; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.*; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.NetworkUtils; @@ -78,9 +73,9 @@ public void demandCreation() throws IOException { config.network().setInputFile( "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"); Scenario scenario = ScenarioUtils.loadScenario(config); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(scenario.getConfig(), - FreightConfigGroup.class); - freightConfigGroup.setCarriersVehicleTypesFile(utils.getPackageInputDirectory() + "testVehicleTypes.xml"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(scenario.getConfig(), + FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setCarriersVehicleTypesFile(utils.getPackageInputDirectory() + "testVehicleTypes.xml"); Path carrierCSVLocation = Path.of(utils.getPackageInputDirectory() + "testCarrierCSV.csv"); Path demandCSVLocation = Path.of(utils.getPackageInputDirectory() + "testDemandCSV.csv"); String shapeCategory = "Ortsteil"; @@ -94,24 +89,24 @@ public void demandCreation() throws IOException { // run methods Set allNewCarrierInformation = CarrierReaderFromCSV .readCarrierInformation(carrierCSVLocation); - CarrierReaderFromCSV.createNewCarrierAndAddVehicleTypes(scenario, allNewCarrierInformation, freightConfigGroup, + CarrierReaderFromCSV.createNewCarrierAndAddVehicleTypes(scenario, allNewCarrierInformation, freightCarriersConfigGroup, polygonsInShape, 1, null); Set demandInformation = DemandReaderFromCSV.readDemandInformation(demandCSVLocation); DemandReaderFromCSV.checkNewDemand(scenario, demandInformation, polygonsInShape, shapeCategory); DemandReaderFromCSV.createDemandForCarriers(scenario, polygonsInShape, demandInformation, population, false, null); - Assert.assertEquals(3, FreightUtils.getCarriers(scenario).getCarriers().size()); + Assert.assertEquals(3, CarriersUtils.getCarriers(scenario).getCarriers().size()); Assert.assertTrue( - FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier1", Carrier.class))); + CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier1", Carrier.class))); Assert.assertTrue( - FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier2", Carrier.class))); + CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier2", Carrier.class))); Assert.assertTrue( - FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier3", Carrier.class))); + CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("testCarrier3", Carrier.class))); // check carrier 1 Network network = NetworkUtils.readNetwork( "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"); - Carrier testCarrier1 = FreightUtils.getCarriers(scenario).getCarriers() + Carrier testCarrier1 = CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create("testCarrier1", Carrier.class)); Assert.assertEquals(14, testCarrier1.getServices().size()); Assert.assertEquals(0, testCarrier1.getShipments().size()); @@ -157,7 +152,7 @@ public void demandCreation() throws IOException { Assert.assertTrue(locationsPerServiceElement.get("serviceElement2").contains("i(2,0)")); // check carrier 2 - Carrier testCarrier2 = FreightUtils.getCarriers(scenario).getCarriers() + Carrier testCarrier2 = CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create("testCarrier2", Carrier.class)); Assert.assertEquals(0, testCarrier2.getServices().size()); Assert.assertEquals(11, testCarrier2.getShipments().size()); @@ -208,7 +203,7 @@ public void demandCreation() throws IOException { Assert.assertEquals(2, locationsPerShipmentElement.get("ShipmenElement2_delivery").size()); // check carrier 3 - Carrier testCarrier3 = FreightUtils.getCarriers(scenario).getCarriers() + Carrier testCarrier3 = CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create("testCarrier3", Carrier.class)); Assert.assertEquals(0, testCarrier3.getServices().size()); Assert.assertEquals(4, testCarrier3.getShipments().size()); diff --git a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/RunGenerateSmallScaleCommercialTrafficTest.java b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/RunGenerateSmallScaleCommercialTrafficTest.java index 7e05a64a48e..d0f4620ac71 100644 --- a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/RunGenerateSmallScaleCommercialTrafficTest.java +++ b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/RunGenerateSmallScaleCommercialTrafficTest.java @@ -25,9 +25,9 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarriersUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.population.PopulationUtils; @@ -81,7 +81,7 @@ public void testMainRunAndResults() { Population population = null; String carriersWOSolutionFileLocation = null; String carriersWSolutionFileLocation = null; - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); for (File outputFiles : Objects.requireNonNull(Objects.requireNonNull(outputFolder.listFiles())[0].listFiles())) { @@ -92,13 +92,13 @@ public void testMainRunAndResults() { if (outputFiles.getName().contains("output_CarrierDemandWithPlans.xml")) carriersWSolutionFileLocation = outputFiles.getPath(); if (outputFiles.getName().contains("output_carriersVehicleTypes.xml.gz")) - freightConfigGroup.setCarriersVehicleTypesFile(outputFiles.getPath()); + freightCarriersConfigGroup.setCarriersVehicleTypesFile(outputFiles.getPath()); } - freightConfigGroup.setCarriersFile(carriersWOSolutionFileLocation); - FreightUtils.loadCarriersAccordingToFreightConfig(scenarioWOSolution); - freightConfigGroup.setCarriersFile(carriersWSolutionFileLocation); - FreightUtils.loadCarriersAccordingToFreightConfig(scenarioWSolution); + freightCarriersConfigGroup.setCarriersFile(carriersWOSolutionFileLocation); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenarioWOSolution); + freightCarriersConfigGroup.setCarriersFile(carriersWSolutionFileLocation); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenarioWSolution); assert population != null; for (Person person : population.getPersons().values()) { @@ -109,10 +109,10 @@ public void testMainRunAndResults() { Assert.assertTrue(person.getAttributes().getAsMap().containsKey("purpose")); } - Assert.assertEquals(FreightUtils.addOrGetCarriers(scenarioWSolution).getCarriers().size(), - FreightUtils.addOrGetCarriers(scenarioWOSolution).getCarriers().size(), 0); + Assert.assertEquals(CarriersUtils.addOrGetCarriers(scenarioWSolution).getCarriers().size(), + CarriersUtils.addOrGetCarriers(scenarioWOSolution).getCarriers().size(), 0); int countedTours = 0; - for (Carrier carrier_withSolution : FreightUtils.addOrGetCarriers(scenarioWSolution).getCarriers().values()) { + for (Carrier carrier_withSolution : CarriersUtils.addOrGetCarriers(scenarioWSolution).getCarriers().values()) { countedTours += carrier_withSolution.getSelectedPlan().getScheduledTours().size(); } Assert.assertEquals(population.getPersons().size(), countedTours, 0); 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 1d2109fcec7..fe522f7462d 100644 --- a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGenerationTest.java +++ b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGenerationTest.java @@ -27,10 +27,9 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.application.options.ShpOptions; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; -import org.matsim.contrib.freight.carrier.CarrierUtils; -import org.matsim.contrib.freight.controler.FreightUtils; +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; @@ -407,15 +406,15 @@ public void testAddingExistingScenarios() throws Exception { SmallScaleCommercialTrafficUtils.readExistingModels(scenario, sample, regionLinksMap); - Assert.assertEquals(3, FreightUtils.getCarriers(scenario).getCarriers().size(), MatsimTestUtils.EPSILON); - Assert.assertEquals(1, FreightUtils.getCarrierVehicleTypes(scenario).getVehicleTypes().size(), MatsimTestUtils.EPSILON); - Assert.assertTrue(FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleServiceCarrier_carrier1", Carrier.class))); - Assert.assertTrue(FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleServiceCarrier_carrier2", Carrier.class))); - Assert.assertTrue(FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleShipmentCarrier_carrier1", Carrier.class))); + Assert.assertEquals(3, CarriersUtils.getCarriers(scenario).getCarriers().size(), MatsimTestUtils.EPSILON); + Assert.assertEquals(1, CarriersUtils.getCarrierVehicleTypes(scenario).getVehicleTypes().size(), MatsimTestUtils.EPSILON); + Assert.assertTrue(CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleServiceCarrier_carrier1", Carrier.class))); + Assert.assertTrue(CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleServiceCarrier_carrier2", Carrier.class))); + Assert.assertTrue(CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleShipmentCarrier_carrier1", Carrier.class))); - Carrier addedCarrier1 = FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleServiceCarrier_carrier1", Carrier.class)); + Carrier addedCarrier1 = CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleServiceCarrier_carrier1", Carrier.class)); Assert.assertNotNull(addedCarrier1.getSelectedPlan()); - Assert.assertEquals(0, CarrierUtils.getJspritIterations(addedCarrier1), MatsimTestUtils.EPSILON); + Assert.assertEquals(0, CarriersUtils.getJspritIterations(addedCarrier1), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier1.getCarrierCapabilities().getCarrierVehicles().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier1.getCarrierCapabilities().getVehicleTypes().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(3, addedCarrier1.getSelectedPlan().getScheduledTours().size(), MatsimTestUtils.EPSILON); @@ -428,9 +427,9 @@ public void testAddingExistingScenarios() throws Exception { Assert.assertNull(addedCarrier1.getAttributes().getAttribute("vehicleType")); Assert.assertEquals("testArea2_area3", addedCarrier1.getAttributes().getAttribute("tourStartArea")); - Carrier addedCarrier2 = FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleServiceCarrier_carrier2", Carrier.class)); + Carrier addedCarrier2 = CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleServiceCarrier_carrier2", Carrier.class)); Assert.assertNotNull(addedCarrier2.getSelectedPlan()); - Assert.assertEquals(0, CarrierUtils.getJspritIterations(addedCarrier2), MatsimTestUtils.EPSILON); + Assert.assertEquals(0, CarriersUtils.getJspritIterations(addedCarrier2), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier2.getCarrierCapabilities().getCarrierVehicles().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier2.getCarrierCapabilities().getVehicleTypes().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(2, addedCarrier2.getSelectedPlan().getScheduledTours().size(), MatsimTestUtils.EPSILON); @@ -442,9 +441,9 @@ public void testAddingExistingScenarios() throws Exception { Assert.assertNull(addedCarrier2.getAttributes().getAttribute("vehicleType")); Assert.assertEquals("testArea2_area3", addedCarrier2.getAttributes().getAttribute("tourStartArea")); - Carrier addedCarrier3 = FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleShipmentCarrier_carrier1", Carrier.class)); + Carrier addedCarrier3 = CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleShipmentCarrier_carrier1", Carrier.class)); Assert.assertNull(addedCarrier3.getSelectedPlan()); - Assert.assertEquals(50, CarrierUtils.getJspritIterations(addedCarrier3), MatsimTestUtils.EPSILON); + Assert.assertEquals(50, CarriersUtils.getJspritIterations(addedCarrier3), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier3.getCarrierCapabilities().getCarrierVehicles().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier3.getCarrierCapabilities().getVehicleTypes().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(FleetSize.INFINITE, addedCarrier3.getCarrierCapabilities().getFleetSize()); @@ -473,14 +472,14 @@ public void testAddingExistingScenariosWithSample() throws Exception { SmallScaleCommercialTrafficUtils.readExistingModels(scenario, sample, regionLinksMap); - Assert.assertEquals(2, FreightUtils.getCarriers(scenario).getCarriers().size(), MatsimTestUtils.EPSILON); - Assert.assertEquals(1, FreightUtils.getCarrierVehicleTypes(scenario).getVehicleTypes().size(), MatsimTestUtils.EPSILON); - Assert.assertTrue(FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleServiceCarrier_carrier1", Carrier.class))); - Assert.assertTrue(FreightUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleShipmentCarrier_carrier1", Carrier.class))); + Assert.assertEquals(2, CarriersUtils.getCarriers(scenario).getCarriers().size(), MatsimTestUtils.EPSILON); + Assert.assertEquals(1, CarriersUtils.getCarrierVehicleTypes(scenario).getVehicleTypes().size(), MatsimTestUtils.EPSILON); + Assert.assertTrue(CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleServiceCarrier_carrier1", Carrier.class))); + Assert.assertTrue(CarriersUtils.getCarriers(scenario).getCarriers().containsKey(Id.create("exampleShipmentCarrier_carrier1", Carrier.class))); - Carrier addedCarrier1 = FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleServiceCarrier_carrier1", Carrier.class)); + Carrier addedCarrier1 = CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleServiceCarrier_carrier1", Carrier.class)); Assert.assertNotNull(addedCarrier1.getSelectedPlan()); - Assert.assertEquals(0, CarrierUtils.getJspritIterations(addedCarrier1), MatsimTestUtils.EPSILON); + Assert.assertEquals(0, CarriersUtils.getJspritIterations(addedCarrier1), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier1.getCarrierCapabilities().getCarrierVehicles().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier1.getCarrierCapabilities().getVehicleTypes().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier1.getSelectedPlan().getScheduledTours().size(), MatsimTestUtils.EPSILON); @@ -493,9 +492,9 @@ public void testAddingExistingScenariosWithSample() throws Exception { Assert.assertNull(addedCarrier1.getAttributes().getAttribute("vehicleType")); Assert.assertEquals("testArea2_area3", addedCarrier1.getAttributes().getAttribute("tourStartArea")); - Carrier addedCarrier3 = FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleShipmentCarrier_carrier1", Carrier.class)); + Carrier addedCarrier3 = CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("exampleShipmentCarrier_carrier1", Carrier.class)); Assert.assertNull(addedCarrier3.getSelectedPlan()); - Assert.assertEquals(50, CarrierUtils.getJspritIterations(addedCarrier3), MatsimTestUtils.EPSILON); + Assert.assertEquals(50, CarriersUtils.getJspritIterations(addedCarrier3), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier3.getCarrierCapabilities().getCarrierVehicles().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(1, addedCarrier3.getCarrierCapabilities().getVehicleTypes().size(), MatsimTestUtils.EPSILON); Assert.assertEquals(FleetSize.INFINITE, addedCarrier3.getCarrierCapabilities().getFleetSize()); diff --git a/contribs/application/test/input/org/matsim/smallScaleCommercialTrafficGeneration/config_demand.xml b/contribs/application/test/input/org/matsim/smallScaleCommercialTrafficGeneration/config_demand.xml index fa6c5559c71..bc64ce1501a 100644 --- a/contribs/application/test/input/org/matsim/smallScaleCommercialTrafficGeneration/config_demand.xml +++ b/contribs/application/test/input/org/matsim/smallScaleCommercialTrafficGeneration/config_demand.xml @@ -70,15 +70,6 @@ - - - - - - - - - @@ -416,24 +407,6 @@ - - - - - - - - - - - - - - - - - - @@ -560,8 +533,6 @@ - - diff --git a/contribs/av/src/main/java/org/matsim/contrib/av/intermodal/RunTaxiPTIntermodalExample.java b/contribs/av/src/main/java/org/matsim/contrib/av/intermodal/RunTaxiPTIntermodalExample.java index 95fc4ca0f07..9aaecbc61b2 100644 --- a/contribs/av/src/main/java/org/matsim/contrib/av/intermodal/RunTaxiPTIntermodalExample.java +++ b/contribs/av/src/main/java/org/matsim/contrib/av/intermodal/RunTaxiPTIntermodalExample.java @@ -36,7 +36,7 @@ import org.matsim.contrib.taxi.run.MultiModeTaxiModule; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.scenario.ScenarioUtils; @@ -54,8 +54,8 @@ public class RunTaxiPTIntermodalExample { public void run(URL configUrl, boolean OTFVis) { Config config = ConfigUtils.loadConfig(configUrl, new MultiModeTaxiConfigGroup(), new DvrpConfigGroup()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); SwissRailRaptorConfigGroup srrConfig = new SwissRailRaptorConfigGroup(); diff --git a/contribs/av/src/main/java/org/matsim/contrib/av/robotaxi/run/RunDrtAndTaxiExample.java b/contribs/av/src/main/java/org/matsim/contrib/av/robotaxi/run/RunDrtAndTaxiExample.java index 5f1646efe1a..5c95006afa8 100644 --- a/contribs/av/src/main/java/org/matsim/contrib/av/robotaxi/run/RunDrtAndTaxiExample.java +++ b/contribs/av/src/main/java/org/matsim/contrib/av/robotaxi/run/RunDrtAndTaxiExample.java @@ -48,7 +48,7 @@ public static void run(URL configUrl, boolean otfvis) { new DvrpConfigGroup(), new OTFVisConfigGroup()); Scenario scenario = DrtControlerCreator.createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); - config.controler() + config.controller() .setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); Controler controler = new Controler(scenario); controler.addOverridingModule(new MultiModeDrtModule()); diff --git a/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleModule.java b/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleModule.java index 15b2d7f42a9..7bf5a766bf4 100644 --- a/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleModule.java +++ b/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleModule.java @@ -86,7 +86,7 @@ static class ConsistencyCheck implements StartupListener { LOG.warn("There is an inconsistency in the specified maximum velocity for " + bicycleConfigGroup.getBicycleMode() + ":" + " Maximum speed specified in the 'bicycle' config group (used for routing): " + bicycleConfigGroup.getMaxBicycleSpeedForRouting() + " vs." + " maximum speed specified for the vehicle type (used in mobsim): " + mobsimSpeed); - if (scenario.getConfig().plansCalcRoute().getRoutingRandomness() == 0.) { + if (scenario.getConfig().routing().getRoutingRandomness() == 0.) { throw new RuntimeException("The recommended way to deal with the inconsistency between routing and scoring/mobsim is to have a randomized router. Aborting... "); } } diff --git a/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleTravelDisutility.java b/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleTravelDisutility.java index be8c5cca418..8632a8dcf6d 100644 --- a/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleTravelDisutility.java +++ b/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleTravelDisutility.java @@ -22,8 +22,8 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.network.NetworkUtils; import org.matsim.core.router.util.TravelDisutility; @@ -65,9 +65,9 @@ class BicycleTravelDisutility implements TravelDisutility { private Person prevPerson; - BicycleTravelDisutility(BicycleConfigGroup bicycleConfigGroup, PlanCalcScoreConfigGroup cnScoringGroup, - PlansCalcRouteConfigGroup plansCalcRouteConfigGroup, TravelTime timeCalculator, double normalization) { - final PlanCalcScoreConfigGroup.ModeParams bicycleParams = cnScoringGroup.getModes().get(bicycleConfigGroup.getBicycleMode()); + BicycleTravelDisutility(BicycleConfigGroup bicycleConfigGroup, ScoringConfigGroup cnScoringGroup, + RoutingConfigGroup routingConfigGroup, TravelTime timeCalculator, double normalization) { + final ScoringConfigGroup.ModeParams bicycleParams = cnScoringGroup.getModes().get(bicycleConfigGroup.getBicycleMode()); if (bicycleParams == null) { throw new NullPointerException("Mode " + bicycleConfigGroup.getBicycleMode() + " is not part of the valid mode parameters " + cnScoringGroup.getModes().keySet()); } @@ -86,7 +86,7 @@ class BicycleTravelDisutility implements TravelDisutility { this.timeCalculator = timeCalculator; this.normalization = normalization; - this.sigma = plansCalcRouteConfigGroup.getRoutingRandomness(); + this.sigma = routingConfigGroup.getRoutingRandomness(); this.random = sigma != 0 ? MatsimRandom.getLocalInstance() : null; } diff --git a/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleTravelDisutilityFactory.java b/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleTravelDisutilityFactory.java index 0bd8d6aef8c..135bc7e011f 100644 --- a/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleTravelDisutilityFactory.java +++ b/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleTravelDisutilityFactory.java @@ -21,8 +21,8 @@ import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.router.costcalculators.TravelDisutilityFactory; import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; @@ -39,17 +39,19 @@ public final class BicycleTravelDisutilityFactory implements TravelDisutilityFac private static final Logger LOG = LogManager.getLogger(BicycleTravelDisutilityFactory.class); @Inject BicycleConfigGroup bicycleConfigGroup; - @Inject PlanCalcScoreConfigGroup cnScoringGroup; - @Inject PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; - + @Inject + ScoringConfigGroup cnScoringGroup; + @Inject + RoutingConfigGroup routingConfigGroup; + private static int normalisationWrnCnt = 0; /* package-private */ BicycleTravelDisutilityFactory(){} - + @Override public TravelDisutility createTravelDisutility(TravelTime timeCalculator) { - double sigma = plansCalcRouteConfigGroup.getRoutingRandomness(); - + double sigma = routingConfigGroup.getRoutingRandomness(); + double normalization = 1; if ( sigma != 0. ) { normalization = 1. / Math.exp(sigma * sigma / 2); @@ -58,6 +60,6 @@ public TravelDisutility createTravelDisutility(TravelTime timeCalculator) { LOG.info(" sigma: " + sigma + "; resulting normalization: " + normalization); } } - return new BicycleTravelDisutility(bicycleConfigGroup, cnScoringGroup, plansCalcRouteConfigGroup, timeCalculator, normalization); + return new BicycleTravelDisutility(bicycleConfigGroup, cnScoringGroup, routingConfigGroup, timeCalculator, normalization); } } diff --git a/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/run/RunBicycleExample.java b/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/run/RunBicycleExample.java index 134f8bf421e..af6d9d58927 100644 --- a/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/run/RunBicycleExample.java +++ b/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/run/RunBicycleExample.java @@ -31,10 +31,10 @@ import org.matsim.contrib.bicycle.BicycleUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.config.groups.QSimConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -71,14 +71,14 @@ public static void main(String[] args) { throw new RuntimeException("More than one argument was provided. There is no procedure for this situation. Thus aborting!" + " Provide either (1) only a suitable config file or (2) no argument at all to run example with given example of resources folder."); } - config.controler().setLastIteration(100); // Modify if motorized interaction is used + config.controller().setLastIteration(100); // Modify if motorized interaction is used boolean considerMotorizedInteraction = false; new RunBicycleExample().run(config ); } static void fillConfigWithBicycleStandardValues(Config config) { - config.controler().setWriteEventsInterval(1); + config.controller().setWriteEventsInterval(1); BicycleConfigGroup bicycleConfigGroup = ConfigUtils.addOrGetModule( config, BicycleConfigGroup.class ); bicycleConfigGroup.setMarginalUtilityOfInfrastructure_m(-0.0002); @@ -97,23 +97,23 @@ static void fillConfigWithBicycleStandardValues(Config config) { config.qsim().setMainModes(mainModeList); - config.strategy().setMaxAgentPlanMemorySize(5); - config.strategy().addStrategySettings( new StrategySettings().setStrategyName("ChangeExpBeta" ).setWeight(0.8 ) ); - config.strategy().addStrategySettings( new StrategySettings().setStrategyName("ReRoute" ).setWeight(0.2 ) ); + config.replanning().setMaxAgentPlanMemorySize(5); + config.replanning().addStrategySettings( new StrategySettings().setStrategyName("ChangeExpBeta" ).setWeight(0.8 ) ); + config.replanning().addStrategySettings( new StrategySettings().setStrategyName("ReRoute" ).setWeight(0.2 ) ); - config.planCalcScore().addActivityParams( new ActivityParams("home").setTypicalDuration(12*60*60 ) ); - config.planCalcScore().addActivityParams( new ActivityParams("work").setTypicalDuration(8*60*60 ) ); + config.scoring().addActivityParams( new ActivityParams("home").setTypicalDuration(12*60*60 ) ); + config.scoring().addActivityParams( new ActivityParams("work").setTypicalDuration(8*60*60 ) ); - config.planCalcScore().addModeParams( new ModeParams("bicycle").setConstant(0. ).setMarginalUtilityOfDistance(-0.0004 ).setMarginalUtilityOfTraveling(-6.0 ).setMonetaryDistanceRate(0. ) ); + config.scoring().addModeParams( new ModeParams("bicycle").setConstant(0. ).setMarginalUtilityOfDistance(-0.0004 ).setMarginalUtilityOfTraveling(-6.0 ).setMonetaryDistanceRate(0. ) ); - config.plansCalcRoute().setNetworkModes(mainModeList); + config.routing().setNetworkModes(mainModeList); } public void run(Config config ) { config.global().setNumberOfThreads(1); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.plansCalcRoute().setRoutingRandomness(3.); + config.routing().setRoutingRandomness(3.); BicycleConfigGroup bicycleConfigGroup = ConfigUtils.addOrGetModule( config, BicycleConfigGroup.class ); @@ -137,9 +137,9 @@ public void run(Config config ) { } public void runWithOwnScoring(Config config, boolean considerMotorizedInteraction) { config.global().setNumberOfThreads(1); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.plansCalcRoute().setRoutingRandomness(3.); + config.routing().setRoutingRandomness(3.); if (considerMotorizedInteraction) { BicycleConfigGroup bicycleConfigGroup = ConfigUtils.addOrGetModule( config, BicycleConfigGroup.class ); diff --git a/contribs/bicycle/src/test/java/org/matsim/contrib/bicycle/run/BicycleTest.java b/contribs/bicycle/src/test/java/org/matsim/contrib/bicycle/run/BicycleTest.java index 329e40cc0c5..0f2dea83a91 100644 --- a/contribs/bicycle/src/test/java/org/matsim/contrib/bicycle/run/BicycleTest.java +++ b/contribs/bicycle/src/test/java/org/matsim/contrib/bicycle/run/BicycleTest.java @@ -39,10 +39,10 @@ import org.matsim.contrib.bicycle.BicycleModule; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.config.groups.QSimConfigGroup.VehiclesSource; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -86,10 +86,10 @@ public void testNormal() { // Normal network config.network().setInputFile("network_normal.xml"); config.plans().setInputFile("population_1200.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); - config.controler().setCreateGraphs(false); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); + config.controller().setCreateGraphs(false); new RunBicycleExample().run(config ); @@ -122,10 +122,10 @@ public void testCobblestone() { config.plans().setInputFile("population_1200.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); - config.controler().setCreateGraphs(false); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); + config.controller().setCreateGraphs(false); new RunBicycleExample().run(config ); { @@ -153,10 +153,10 @@ public void testPedestrian() { // Links 4-8 and 13-17 are pedestrian zones config.network().setInputFile("network_pedestrian.xml"); config.plans().setInputFile("population_1200.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); - config.controler().setCreateGraphs(false); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); + config.controller().setCreateGraphs(false); new RunBicycleExample().run(config ); @@ -182,10 +182,10 @@ public void testLane() { // Links 2-4/8-10 and 11-13/17-19 have cycle lanes (cycleway=lane) config.network().setInputFile("network_lane.xml"); config.plans().setInputFile("population_1200.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); - config.controler().setCreateGraphs(false); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); + config.controller().setCreateGraphs(false); new RunBicycleExample().run(config ); @@ -211,10 +211,10 @@ public void testGradient() { // Nodes 5-8 have a z-coordinate > 0, i.e. the links leading to those nodes have a slope config.network().setInputFile("network_gradient.xml"); config.plans().setInputFile("population_1200.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); - config.controler().setCreateGraphs(false); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); + config.controller().setCreateGraphs(false); new RunBicycleExample().run(config ); @@ -241,10 +241,10 @@ public void testGradientLane() { // and links 4-5 and 13-14 have cycle lanes config.network().setInputFile("network_gradient_lane.xml"); config.plans().setInputFile("population_1200.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); - config.controler().setCreateGraphs(false); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); + config.controller().setCreateGraphs(false); new RunBicycleExample().run(config ); @@ -270,13 +270,13 @@ public void testNormal10It() { // Normal network config.network().setInputFile("network_normal.xml"); config.plans().setInputFile("population_1200.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); // 10 iterations - config.controler().setLastIteration(10); - config.controler().setWriteEventsInterval(10); - config.controler().setWritePlansInterval(10); - config.controler().setCreateGraphs(false); + config.controller().setLastIteration(10); + config.controller().setWriteEventsInterval(10); + config.controller().setWritePlansInterval(10); + config.controller().setCreateGraphs(false); new RunBicycleExample().run(config ); @@ -345,9 +345,9 @@ public void testNormal10It() { // the following comes from inlining RunBicycleExample, which we need since we need to modify scenario data: config.global().setNumberOfThreads(1 ); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists ); - config.plansCalcRoute().setRoutingRandomness(3. ); + config.routing().setRoutingRandomness(3. ); final String bicycle = bicycleConfigGroup.getBicycleMode(); @@ -444,10 +444,10 @@ public void testInfrastructureSpeedFactor() { Config config = ConfigUtils.createConfig(utils.getClassInputDirectory() ); config.addModule(new BicycleConfigGroup()); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); config.qsim().setStartTime(6. * 3600.); config.qsim().setEndTime(10. * 3600.); @@ -456,43 +456,43 @@ public void testInfrastructureSpeedFactor() { mainModeList.add(TransportMode.car); config.qsim().setMainModes(mainModeList); - config.strategy().setMaxAgentPlanMemorySize(5); + config.replanning().setMaxAgentPlanMemorySize(5); { StrategySettings strategySettings = new StrategySettings(); strategySettings.setStrategyName("ChangeExpBeta"); strategySettings.setWeight(1.0); - config.strategy().addStrategySettings(strategySettings); + config.replanning().addStrategySettings(strategySettings); } ActivityParams homeActivity = new ActivityParams("home"); homeActivity.setTypicalDuration(12*60*60); - config.planCalcScore().addActivityParams(homeActivity); + config.scoring().addActivityParams(homeActivity); ActivityParams workActivity = new ActivityParams("work"); workActivity.setTypicalDuration(8*60*60); - config.planCalcScore().addActivityParams(workActivity); + config.scoring().addActivityParams(workActivity); ModeParams bicycle = new ModeParams( bicycleMode ); bicycle.setConstant(0.); bicycle.setMarginalUtilityOfDistance(-0.0004); // util/m bicycle.setMarginalUtilityOfTraveling(-6.0); // util/h bicycle.setMonetaryDistanceRate(0.); - config.planCalcScore().addModeParams(bicycle); + config.scoring().addModeParams(bicycle); - config.plansCalcRoute().setNetworkModes(mainModeList); + config.routing().setNetworkModes(mainModeList); // link 2 has infrastructure speed factor = 1.0, all other links 0.01 config.network().setInputFile("network_infrastructure-speed-factor.xml"); config.plans().setInputFile("population_4.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); config.global().setNumberOfThreads(1); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.plansCalcRoute().setRoutingRandomness(3.); + config.routing().setRoutingRandomness(3.); // --- @@ -539,10 +539,10 @@ public void testInfrastructureSpeedFactorDistanceMoreRelevantThanTravelTime() { Config config = ConfigUtils.createConfig(utils.getClassInputDirectory() ); BicycleConfigGroup bicycleConfigGroup = ConfigUtils.addOrGetModule( config, BicycleConfigGroup.class ); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); config.qsim().setStartTime(6. * 3600.); config.qsim().setEndTime(14. * 3600.); @@ -551,41 +551,41 @@ public void testInfrastructureSpeedFactorDistanceMoreRelevantThanTravelTime() { mainModeList.add(TransportMode.car); config.qsim().setMainModes(mainModeList); - config.strategy().setMaxAgentPlanMemorySize(5); + config.replanning().setMaxAgentPlanMemorySize(5); { StrategySettings strategySettings = new StrategySettings(); strategySettings.setStrategyName("ChangeExpBeta"); strategySettings.setWeight(1.0); - config.strategy().addStrategySettings(strategySettings); + config.replanning().addStrategySettings(strategySettings); } ActivityParams homeActivity = new ActivityParams("home"); homeActivity.setTypicalDuration(12*60*60); - config.planCalcScore().addActivityParams(homeActivity); + config.scoring().addActivityParams(homeActivity); ActivityParams workActivity = new ActivityParams("work"); workActivity.setTypicalDuration(8*60*60); - config.planCalcScore().addActivityParams(workActivity); + config.scoring().addActivityParams(workActivity); ModeParams bicycle = new ModeParams("bicycle"); bicycle.setConstant(0.); bicycle.setMarginalUtilityOfDistance(-999999); // util/m bicycle.setMarginalUtilityOfTraveling(-6.0); // util/h bicycle.setMonetaryDistanceRate(0.); - config.planCalcScore().addModeParams(bicycle); + config.scoring().addModeParams(bicycle); - config.plansCalcRoute().setNetworkModes(mainModeList); + config.routing().setNetworkModes(mainModeList); // link 2 has infrastructure speed factor = 1.0, all other links 0.01 config.network().setInputFile("network_infrastructure-speed-factor.xml"); config.plans().setInputFile("population_4.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); config.global().setNumberOfThreads(1); - config.plansCalcRoute().setRoutingRandomness(3.); + config.routing().setRoutingRandomness(3.); Scenario scenario = ScenarioUtils.loadScenario(config); var vf = scenario.getVehicles().getFactory(); @@ -626,13 +626,13 @@ private Config createConfig( int lastIteration ){ // Normal network config.network().setInputFile( "network_normal.xml" ); config.plans().setInputFile( "population_1200.xml" ); - config.controler().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setLastIteration( lastIteration ); - config.controler().setLastIteration( lastIteration ); - config.controler().setWriteEventsInterval( 10 ); - config.controler().setWritePlansInterval( 10 ); - config.controler().setCreateGraphs( false ); + config.controller().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setLastIteration( lastIteration ); + config.controller().setLastIteration( lastIteration ); + config.controller().setWriteEventsInterval( 10 ); + config.controller().setWritePlansInterval( 10 ); + config.controller().setCreateGraphs( false ); return config; } diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsBuilderImpl.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsBuilderImpl.java index 5ed2c548e58..12a9ae8bfbc 100644 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsBuilderImpl.java +++ b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsBuilderImpl.java @@ -46,7 +46,7 @@ private CadytsBuilderImpl(){} // do not instantiate public static AnalyticalCalibrator buildCalibratorAndAddMeasurements(final Config config, final Counts occupCounts, LookUpItemFromId lookUp, Class idType) { - + if (occupCounts.getCounts().size() == 0) { log.warn("Counts container is empty."); } @@ -54,7 +54,7 @@ public static AnalyticalCalibrator buildCalibratorAndAddMeasurements(fina CadytsConfigGroup cadytsConfig = ConfigUtils.addOrGetModule(config, CadytsConfigGroup.GROUP_NAME, CadytsConfigGroup.class); AnalyticalCalibrator matsimCalibrator = buildCalibrator(config); - + int multiple = cadytsConfig.getTimeBinSize() / 3600 ; // e.g. "3" when timeBinSize_s = 3*3600 = 10800 // If I remember correctly, the following is trying to get around the fact that the counts time bins are fixed at hourly, but we want to @@ -64,16 +64,16 @@ public static AnalyticalCalibrator buildCalibratorAndAddMeasurements(fina // yyyy However, it seems that some of this did not work: We are using "hourly" counts, and dividing the multi-hour values by // the number of hours. ??????? - + // yyyyyy I am currently of the opinion that the multi-hour version should be decoupled from the counts format. There is a // cadyts file format which allows setting mult-hour measurements, and that seems a lot more direct than trying to use a file // format/data structure which is really not meant for this. kai, dec'13 - + //add counts data into calibrator int numberOfAddedMeasurements = 0 ; for (Map.Entry, Count> entry : occupCounts.getCounts().entrySet()) { // (loop over all counting "items" (usually locations/stations) - + T item = lookUp.getItem(Id.create(entry.getKey(), idType)) ; if ( item==null ) { throw new RuntimeException("item is null; entry=" + entry + " idType=" + idType ) ; @@ -83,7 +83,7 @@ public static AnalyticalCalibrator buildCalibratorAndAddMeasurements(fina double count = -1 ; for (Volume volume : entry.getValue().getVolumes().values()){ // (loop over the different time slots) - + if ( timeBinIndex%multiple == 0 ) { // (i.e. first timeBinIndex belonging to given bin) @@ -95,7 +95,7 @@ public static AnalyticalCalibrator buildCalibratorAndAddMeasurements(fina log.warn( " NOT adding measurement: timeBinIndex: " + timeBinIndex + "; multiple: " + multiple ) ; } else { // (i.e. last timeBinIndex belonging to given bin) - + int endTimeOfBin_s = volume.getHourOfDayStartingWithOne()*3600 - 1 ; if ( !( cadytsConfig.getStartTime() <= startTimeOfBin_s && endTimeOfBin_s <= cadytsConfig.getEndTime()) ) { log.warn( " NOT adding measurement: cadytsConfigStartTime: " + cadytsConfig.getStartTime() + "; startTimeOfBin_s: " + startTimeOfBin_s + @@ -105,7 +105,7 @@ public static AnalyticalCalibrator buildCalibratorAndAddMeasurements(fina // matsimCalibrator.addMeasurement(item, startTimeOfBin_s, endTimeOfBin_s, count/multiple, SingleLinkMeasurement.TYPE.FLOW_VEH_H); matsimCalibrator.addMeasurement(item, startTimeOfBin_s, endTimeOfBin_s, count, SingleLinkMeasurement.TYPE.COUNT_VEH ); - // changed this from FLOW_VEH_H to COUNT_VEH on 30/jul/2012 since this is no longer "hourly". + // changed this from FLOW_VEH_H to COUNT_VEH on 30/jul/2012 since this is no longer "hourly". // kai/manuel, jul'12 // Despite the above comment, I am finding this with FLOW_VEH_H. Why? kai, feb'13 // yyyyyy For the test case, this seems to produce weird results. The expected counts are 1 and 5, the expected result is 0 and 4. @@ -120,7 +120,7 @@ public static AnalyticalCalibrator buildCalibratorAndAddMeasurements(fina if ( numberOfAddedMeasurements==0 ) { log.warn("No measurements were added."); } - + if ( matsimCalibrator.getProportionalAssignment() ) { throw new RuntimeException("Gunnar says that this may not work so do not set to true. kai, sep'14") ; } @@ -129,7 +129,7 @@ public static AnalyticalCalibrator buildCalibratorAndAddMeasurements(fina public static AnalyticalCalibrator buildCalibrator(final Config config) { CadytsConfigGroup cadytsConfig = ConfigUtils.addOrGetModule(config, CadytsConfigGroup.GROUP_NAME, CadytsConfigGroup.class ) ; - + //get timeBinSize_s and validate it if ((Time.MIDNIGHT % cadytsConfig.getTimeBinSize())!= 0 ){ throw new RuntimeException("Cadyts requires a divisor of 86400 as time bin size value ."); @@ -138,10 +138,10 @@ public static AnalyticalCalibrator buildCalibrator(final Config config) { throw new RuntimeException("At this point, time bin sizes need to be multiples of 3600. This is not a restriction " + "of Cadyts, but of the counts file format, which only allows for hourly inputs") ; } - - + + AnalyticalCalibrator matsimCalibrator = new AnalyticalCalibrator<>( - config.controler().getOutputDirectory() + "/cadyts.log", + config.controller().getOutputDirectory() + "/cadyts.log", MatsimRandom.getLocalInstance().nextLong(),cadytsConfig.getTimeBinSize() ) ; @@ -159,9 +159,9 @@ public static AnalyticalCalibrator buildCalibrator(final Config config) { if ( matsimCalibrator.getBruteForce() ) { log.warn("setting bruteForce==true for calibrator, but this won't do anything in the way the cadyts matsim integration is set up. kai, mar'14") ; } - - matsimCalibrator.setStatisticsFile(config.controler().getOutputDirectory() + "/calibration-stats.txt"); + + matsimCalibrator.setStatisticsFile(config.controller().getOutputDirectory() + "/calibration-stats.txt"); return matsimCalibrator; } - + } diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsPlanChanger.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsPlanChanger.java index 4f0be74b8d4..f3a02a0bf4a 100644 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsPlanChanger.java +++ b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsPlanChanger.java @@ -43,9 +43,9 @@ public class CadytsPlanChanger implements PlanSelector { public CadytsPlanChanger(Scenario scenario, CadytsContextI cadytsContext) { this.cadytsContext = cadytsContext; - this.beta = scenario.getConfig().planCalcScore().getBrainExpBeta() ; + this.beta = scenario.getConfig().scoring().getBrainExpBeta() ; } - + @Override public Plan selectPlan(final HasPlansAndId person) { final Plan currentPlan = person.getSelectedPlan(); @@ -90,4 +90,4 @@ public Plan selectPlan(final HasPlansAndId person) { public void setCadytsWeight(double cadytsWeight) { this.cadytsWeight = cadytsWeight; } -} \ No newline at end of file +} diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsScoring.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsScoring.java index a19b191361d..e2841dd19b8 100644 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsScoring.java +++ b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/general/CadytsScoring.java @@ -45,7 +45,7 @@ public CadytsScoring(final Plan plan, Config config, final CadytsContextI con this.plansTranslator = context.getPlansTranslator(); this.matsimCalibrator = context.getCalibrator(); this.plan = plan; - this.beta = config.planCalcScore().getBrainExpBeta(); + this.beta = config.scoring().getBrainExpBeta(); } @Override diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsBuilderImplGT.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsBuilderImplGT.java deleted file mode 100644 index 1165c45aed3..00000000000 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsBuilderImplGT.java +++ /dev/null @@ -1,87 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * copyright : (C) 2012 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.contrib.cadyts.pt; - -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.contrib.cadyts.general.CadytsBuilderImpl; -import org.matsim.contrib.cadyts.general.LookUpItemFromId; -import org.matsim.core.config.Config; -import org.matsim.counts.Count; -import org.matsim.counts.Counts; -import org.matsim.counts.Volume; - -import cadyts.calibrators.analytical.AnalyticalCalibrator; -import cadyts.measurements.SingleLinkMeasurement; - -/** - * @author nagel - * @author mrieser - */ -public final class CadytsBuilderImplGT { - // yyyy why "GT"? Is this a typo and should have been PT (or Pt, to be consistent with other classes)? kai, feb'20 - - // yy I also don't know where and when this is used to I am commenting it out to see if someone complains. kai, feb'20 - -// private static Logger log = LogManager.getLogger( CadytsBuilderImplGT.class ) ; -// -// private CadytsBuilderImplGT(){} // do not instantiate -// -// public static AnalyticalCalibrator buildCalibratorAndAddMeasurements(final Config config, final Counts occupCounts, -// LookUpItemFromId lookUp, Class idType ) { -// -// if (occupCounts.getCounts().size() == 0) { -// log.warn("Counts container is empty."); -// } -// -// AnalyticalCalibrator matsimCalibrator = CadytsBuilderImpl.buildCalibrator(config); -// -// //add counts data into calibrator -// int numberOfAddedMeasurements = 0 ; -// for (Map.Entry, Count> entry : occupCounts.getCounts().entrySet()) { -// // (loop over all counting "items" (usually locations/stations) -// -// T item = lookUp.getItem(Id.create(entry.getKey(), idType)) ; -// if ( item==null ) { -// throw new RuntimeException("item is null; entry=" + entry + " idType=" + idType ) ; -// } -// -// double sum = 0; -// for (Volume volume : entry.getValue().getVolumes().values()){ -// // (loop over the different time slots) -// sum += volume.getValue() ; -// } -// numberOfAddedMeasurements++ ; -// matsimCalibrator.addMeasurement(item, 0, 86400, sum, SingleLinkMeasurement.TYPE.COUNT_VEH ); -// } -// -// if ( numberOfAddedMeasurements==0 ) { -// log.warn("No measurements were added."); -// } -// -// if ( matsimCalibrator.getProportionalAssignment() ) { -// throw new RuntimeException("Gunnar says that this may not work so do not set to true. kai, sep'14") ; -// } -// return matsimCalibrator; -// } -} diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtContext.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtContext.java deleted file mode 100644 index e1f918c4ac1..00000000000 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtContext.java +++ /dev/null @@ -1,265 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * copyright : (C) 2013 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.contrib.cadyts.pt; - -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import jakarta.inject.Inject; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.matsim.analysis.IterationStopWatch; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Scenario; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.cadyts.general.CadytsBuilderImpl; -import org.matsim.contrib.cadyts.general.CadytsConfigGroup; -import org.matsim.contrib.cadyts.general.CadytsContextI; -import org.matsim.contrib.cadyts.general.CadytsCostOffsetsXMLFileIO; -import org.matsim.contrib.cadyts.general.PlansTranslator; -import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PtCountsConfigGroup; -import org.matsim.core.controler.OutputDirectoryHierarchy; -import org.matsim.core.controler.events.AfterMobsimEvent; -import org.matsim.core.controler.events.BeforeMobsimEvent; -import org.matsim.core.controler.events.IterationEndsEvent; -import org.matsim.core.controler.events.StartupEvent; -import org.matsim.core.controler.listener.AfterMobsimListener; -import org.matsim.core.controler.listener.BeforeMobsimListener; -import org.matsim.core.controler.listener.IterationEndsListener; -import org.matsim.core.controler.listener.StartupListener; -import org.matsim.core.utils.geometry.CoordinateTransformation; -import org.matsim.core.utils.geometry.transformations.TransformationFactory; -import org.matsim.counts.Counts; -import org.matsim.counts.MatsimCountsReader; -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.TransitStopFacility; - -import cadyts.calibrators.analytical.AnalyticalCalibrator; -import cadyts.measurements.SingleLinkMeasurement.TYPE; -import cadyts.supply.SimResults; - -/** - * @author nagel - * - */ -public class CadytsPtContext implements StartupListener, IterationEndsListener, BeforeMobsimListener, AfterMobsimListener, -CadytsContextI { - // can be/remain public as long as constructor is package-private. kai, feb'20 - - private final static Logger log = LogManager.getLogger(CadytsPtContext.class); - - private final static String LINKOFFSET_FILENAME = "linkCostOffsets.xml"; - private static final String FLOWANALYSIS_FILENAME = "flowAnalysis.txt"; - private static final String OCCUPANCYANALYSIS_FILENAME = "cadytsPtOccupancyAnalysis.txt"; - - private AnalyticalCalibrator calibrator = null; - private final SimResults simResults; - private final Counts occupCounts = new Counts<>(); - // private final Counts boardCounts = new Counts(); - // private final Counts alightCounts = new Counts(); - private final CadytsPtOccupancyAnalyzerI cadytsPtOccupAnalyzer; - private PtPlanToPlanStepBasedOnEvents ptStep ; - - private CadytsConfigGroup cadytsConfig; - private EventsManager events; - private Scenario scenario; - private OutputDirectoryHierarchy controlerIO; - private IterationStopWatch stopWatch; - - @Inject - CadytsPtContext(final Config config, EventsManager events, Scenario scenario, OutputDirectoryHierarchy controlerIO, - IterationStopWatch stopWatch, final CadytsPtOccupancyAnalyzerI cadytsPtOccupancyAnalyzer ) { - this.events = events; - this.scenario = scenario; - this.controlerIO = controlerIO; - this.stopWatch = stopWatch; - cadytsConfig = (CadytsConfigGroup) config.getModule(CadytsConfigGroup.GROUP_NAME); - this.cadytsPtOccupAnalyzer = cadytsPtOccupancyAnalyzer ; - - // === prepare the structure which extracts the measurements from the simulation: - // since there is already some other method, we just need to write a wrapper. - -// this.cadytsPtOccupAnalyzer = new CadytsPtOccupancyAnalyzer(CadytsPtOccupancyAnalyzer.toTransitLineIdSet(cadytsConfig.getCalibratedItems()), cadytsConfig.getTimeBinSize() ); - events.addHandler(this.cadytsPtOccupAnalyzer); - - this.simResults = new SimResults() { - private static final long serialVersionUID = 1L; - @Override - public double getSimValue(TransitStopFacility stop, int startTime_s, int endTime_s, TYPE type) { - final int timeBinSize_s = cadytsConfig.getTimeBinSize() ; - final double countsScaleFactor = config.ptCounts().getCountsScaleFactor() ; - double retval = 0. ; - switch ( type ) { - case COUNT_VEH: - retval = cadytsPtOccupAnalyzer.getOccupancyVolumeForStopAndTime(stop.getId(), startTime_s) * countsScaleFactor ; - break; - case FLOW_VEH_H: - int multiple = timeBinSize_s / 3600 ; // e.g. "3" when timeBinSize_s = 3*3600 = 10800 - retval = cadytsPtOccupAnalyzer.getOccupancyVolumeForStopAndTime(stop.getId(), startTime_s) * countsScaleFactor / multiple ; - break; - default: - throw new RuntimeException("not implemented ...") ; - } -// if ( retval != 0. ) { -// log.warn("retval=" + retval ); -// } - return retval ; - } - @Override - public String toString() { - return cadytsPtOccupAnalyzer.toString() ; - } - } ; - // === end wrapper === - - } - - @Override - public void notifyStartup(StartupEvent event) { - - // === prepare the calibrator by giving measurements to it: - String occupancyCountsFilename = scenario.getConfig().ptCounts().getOccupancyCountsFileName(); - new MatsimCountsReader(this.occupCounts).readFile(occupancyCountsFilename); - - // === build the calibrator: - this.calibrator = CadytsBuilderImpl.buildCalibratorAndAddMeasurements(scenario.getConfig(), this.occupCounts, new TransitStopFacilityLookUp(scenario) , TransitStopFacility.class); - - // === find out which plan is contributing what to each measurement: - this.ptStep = new PtPlanToPlanStepBasedOnEvents<>(scenario, CadytsPtOccupancyAnalyzer.toTransitLineIdSet(cadytsConfig.getCalibratedLines())); - events.addHandler(ptStep); - } - - @Override - public void notifyBeforeMobsim(final BeforeMobsimEvent event) { - this.cadytsPtOccupAnalyzer.reset(event.getIteration()); - for (Person person : scenario.getPopulation().getPersons().values()) { - this.calibrator.addToDemand(ptStep.getCadytsPlan(person.getSelectedPlan())); - } - } - - @Override - public void notifyAfterMobsim(final AfterMobsimEvent event) { - int it = event.getIteration(); - - // Get all stations of all analyzed lines and invoke the method write to get all information of them - Set> stopIds = new HashSet<>(); - for ( String pseudoLineId : this.cadytsConfig.getCalibratedLines()) { - Id lineId = Id.create(pseudoLineId, TransitLine.class); - TransitLine line = scenario.getTransitSchedule().getTransitLines().get(lineId); - for (TransitRoute route : line.getRoutes().values()) { - for (TransitRouteStop stop : route.getStops()) { - stopIds.add(stop.getStopFacility().getId()); - } - } - } - String outFile = controlerIO.getIterationFilename(it, OCCUPANCYANALYSIS_FILENAME); - this.cadytsPtOccupAnalyzer.writeResultsForSelectedStopIds(outFile, this.occupCounts, stopIds); - } - - @Override - public void notifyIterationEnds(final IterationEndsEvent event) { - if (cadytsConfig.isWriteAnalysisFile()) { - String analysisFilepath = controlerIO.getIterationFilename(event.getIteration(), FLOWANALYSIS_FILENAME); - this.calibrator.setFlowAnalysisFile(analysisFilepath); - } - - this.calibrator.afterNetworkLoading(this.simResults); - - // write some output - String filename = controlerIO.getIterationFilename(event.getIteration(), LINKOFFSET_FILENAME); - try { - new CadytsCostOffsetsXMLFileIO<>(new TransitStopFacilityLookUp(scenario), TransitStopFacility.class) - .write(filename, this.calibrator.getLinkCostOffsets()); - } catch (IOException e) { - log.error("Could not write link cost offsets!", e); - } - - generateAndWriteCountsComparisons(event); - } - - // =========================================================================================================================== - // private methods & pure delegate methods only below this line - - private void generateAndWriteCountsComparisons(final IterationEndsEvent event) { - if ( this.cadytsConfig.getTimeBinSize()!=3600 ) { - log.warn("generateAndWriteCountsComparisons() does not work when time bin size != 3600. See comments in code. Skipping the comparison ..." ) ; - return ; - // yyyy there are some conceptual problems behind this which are not resolved: - // () There should reasonably be two methods: one describing what cadyts _thinks_ it is comparing, and one that just - // compares the output. There is one methods writing simCountCompare..., and then this one here - // writing cadytsSimCountCompare... . It is not clarified which one is doing which. - // () The method that just compares the output should not rely on cadyts but compute its own observations. -- - // Unfortunately, this collides with the fact that the time bin size is part of the cadyts configuration. This is, in the end, a - // consequence of the fact that the Counts format assumes hourly counts (other than cadyts, which reasonably allows the - // specify the time span for every observation separately). - // kai, feb'13 - } - - - PtCountsConfigGroup ptCountsConfig = scenario.getConfig().ptCounts(); - if (ptCountsConfig.getOccupancyCountsFileName() == null) { // yyyy this check should reasonably also be done in isActiveInThisIteration. kai,oct'10 - log.warn("generateAndWriteCountsComparisons() does not work since occupancy counts file name not given ") ; - return ; - } - int iter = event.getIteration(); - - stopWatch.beginOperation("compare with pt counts"); - - Network network = scenario.getNetwork(); - CadytsPtCountsComparisonAlgorithm ccaOccupancy = new CadytsPtCountsComparisonAlgorithm(this.cadytsPtOccupAnalyzer, - this.occupCounts, network, scenario.getConfig().ptCounts().getCountsScaleFactor()); - - Double distanceFilter = ptCountsConfig.getDistanceFilter(); - String distanceFilterCenterNodeId = ptCountsConfig.getDistanceFilterCenterNode(); - if ((distanceFilter != null) && (distanceFilterCenterNodeId != null)) { - ccaOccupancy.setDistanceFilter(distanceFilter, distanceFilterCenterNodeId); - } - - ccaOccupancy.calculateComparison(); - - String outputFormat = ptCountsConfig.getOutputFormat(); - if (outputFormat.contains("txt") || outputFormat.contains("all")) { - // As far as I can tell, this file is written twice, the other times without the "cadyts" part. kai, feb'13 - // yyyyyy As far as I can tell, the version here is wrong as soon as the time bin is different from 3600.--?? kai, feb'13 - // See near beginning of method. kai, feb'13 - ccaOccupancy.write(controlerIO.getIterationFilename(iter, "cadytsSimCountCompareOccupancy.txt")); - } - - stopWatch.endOperation("compare with pt counts"); - } - - @Override - public AnalyticalCalibrator getCalibrator() { - return calibrator; - } - - @Override - public PlansTranslator getPlansTranslator() { - return ptStep; - } - -} diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtCountsComparisonAlgorithm.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtCountsComparisonAlgorithm.java deleted file mode 100644 index 6327a98260f..00000000000 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtCountsComparisonAlgorithm.java +++ /dev/null @@ -1,185 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * copyright : (C) 2012 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.contrib.cadyts.pt; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Identifiable; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.network.Node; -import org.matsim.core.utils.geometry.CoordUtils; -import org.matsim.counts.Count; -import org.matsim.counts.CountSimComparison; -import org.matsim.counts.CountSimComparisonImpl; -import org.matsim.counts.Counts; -import org.matsim.counts.Volume; -import org.matsim.pt.counts.SimpleWriter; - -/** - * This is a modified copy of CountsComparisonAlgorithm, in order to realize the same functionality - * for pt counts. - */ -final class CadytsPtCountsComparisonAlgorithm { - /** - * The StopAttributes of the simulation - */ - private final CadytsPtOccupancyAnalyzerI oa; - /** - * The counts object - */ - Counts counts; - // needed in CadytsErrorPlot - - /** - * The result list - */ - private final List countSimComp; - - private Node distanceFilterNode = null; - - private Double distanceFilter = null; - - private final Network network; - - double countsScaleFactor; // needed in CadytsErrorPlot - - final static Logger log = LogManager.getLogger(CadytsPtCountsComparisonAlgorithm.class); - - StringBuffer content = new StringBuffer(); - - CadytsPtCountsComparisonAlgorithm(final CadytsPtOccupancyAnalyzerI oa, final Counts counts, final Network network, final double countsScaleFactor) { - this.oa = oa; - this.counts = counts; - this.countSimComp = new ArrayList(); - this.network = network; - this.countsScaleFactor = countsScaleFactor; - } - - /** - * Creates the List with the counts vs sim values stored in the countAttribute Attribute of this - * class. - */ - final String STR_NOVOLUMES = "No volumes for stop: "; - final String STR_STOPID = "StopId :\t"; - final String STR_HEAD = "\nhour\tsimVal\tscaledSimVal\tcountVal\n"; - final char CHR_HT = '\t'; - final char CHR_NL = '\n'; - - public void calculateComparison() { - double countValue; - for (Count count : this.counts.getCounts().values()) { - Id stopId = count.getId(); - if (!isInRange(count.getCoord())) { - continue; - } - int[] volumes = this.getVolumesForStop(stopId); - if (volumes == null) { - log.warn(this.STR_NOVOLUMES + stopId); - continue; - } else /* volumes!=null */if (volumes.length == 0) { - log.warn(this.STR_NOVOLUMES + stopId); - continue; - } - - this.content.append(this.STR_STOPID); - this.content.append(stopId.toString()); - this.content.append(this.STR_HEAD); - - for (int hour = 1; hour <= volumes.length; hour++) { - // real volumes: - Volume volume = count.getVolume(hour); - if (volume != null) { - - this.content.append(hour); - this.content.append(this.CHR_HT); - - countValue = volume.getValue(); - double simValue = volumes[hour - 1]; - - this.content.append(simValue); - this.content.append(this.CHR_HT); - - simValue *= this.countsScaleFactor; - - this.content.append(simValue); - this.content.append(this.CHR_HT); - this.content.append(countValue); - this.content.append(this.CHR_NL); - - this.countSimComp.add(new CountSimComparisonImpl(stopId, hour, countValue, simValue)); - - } else { - countValue = 0.0; - } - - } - } - } - - int[] getVolumesForStop(final Id stopId) { - return this.oa.getOccupancyVolumesForStop(stopId); - } - - /** - * - * @param stopCoord - * @return true if the Link with the given Id is not farther away than the - * distance specified by the distance filter from the center node of the filter. - */ - boolean isInRange(final Coord stopCoord) { - if ((this.distanceFilterNode == null) || (this.distanceFilter == null)) { - return true; - } - - double dist = CoordUtils.calcEuclideanDistance(stopCoord, this.distanceFilterNode.getCoord()); - return dist < this.distanceFilter.doubleValue(); - } - - /** - * - * @return the result list - */ - public List getComparison() { - return this.countSimComp; - } - - /** - * Set a distance filter, dropping everything out which is not in the distance given in meters - * around the given Node Id. - * - * @param distance - * @param nodeId - */ - public void setDistanceFilter(final Double distance, final String nodeId) { - this.distanceFilter = distance; - this.distanceFilterNode = this.network.getNodes().get(Id.create(nodeId, Node.class)); - } - - public void write(final String outputFilename) { - final SimpleWriter simpleWriter = new SimpleWriter(outputFilename); - simpleWriter.write(this.content.toString()); - simpleWriter.close(); - } -} diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtModule.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtModule.java deleted file mode 100644 index d9f459047b3..00000000000 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtModule.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.matsim.contrib.cadyts.pt; - - -import org.matsim.core.controler.AbstractModule; - -import jakarta.inject.Singleton; - -public class CadytsPtModule extends AbstractModule { - @Override - public void install() { - bind(CadytsPtContext.class).in( Singleton.class ); - addControlerListenerBinding().to(CadytsPtContext.class); - bind(CadytsPtOccupancyAnalyzerI.class).to(CadytsPtOccupancyAnalyzer.class); - } -} diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtOccupancyAnalyzer.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtOccupancyAnalyzer.java deleted file mode 100644 index c116c652e0c..00000000000 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtOccupancyAnalyzer.java +++ /dev/null @@ -1,299 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * copyright : (C) 2012 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.contrib.cadyts.pt; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import jakarta.inject.Inject; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.PersonEntersVehicleEvent; -import org.matsim.api.core.v01.events.PersonLeavesVehicleEvent; -import org.matsim.api.core.v01.events.TransitDriverStartsEvent; -import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.cadyts.general.CadytsConfigGroup; -import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; -import org.matsim.core.api.experimental.events.VehicleDepartsAtFacilityEvent; -import org.matsim.core.config.Config; -import org.matsim.core.config.ConfigUtils; -import org.matsim.core.utils.misc.Time; -import org.matsim.counts.Count; -import org.matsim.counts.Counts; -import org.matsim.counts.Volume; -import org.matsim.pt.counts.SimpleWriter; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.vehicles.Vehicle; - -/** - * Collects occupancy data of transit-line stations - *

- * This is probably similar to code elsewhere. However, it makes some sense to keep this here since the correct workings of cadyts - * (obviously) depends on the fact that the counts are actually what it thinks, and so it makes sense to decouple this from the upstream - * counting method and leave it here. kai, sep'13 - */ -final class CadytsPtOccupancyAnalyzer implements CadytsPtOccupancyAnalyzerI { - // can be/remain public as long as constructor is package-private. kai, feb'20 - - private final int timeBinSize, maxSlotIndex; - private final double maxTime; - private Map, int[]> occupancies; // Map< stopFacilityId,value[]> - private final Map, Id> vehStops = new HashMap<>(); // Map< vehId,stopFacilityId> - private final Map, Integer> vehPassengers = new HashMap<>(); // Map - private StringBuffer occupancyRecord = new StringBuffer("time\tvehId\tStopId\tno.ofPassengersInVeh\n"); - private final Set analyzedTransitDrivers = new HashSet<>(); - private final Set analyzedTransitVehicles = new HashSet<>(); - private final Set> calibratedLines; - - @Inject - CadytsPtOccupancyAnalyzer( Config config ) { - CadytsConfigGroup ccc = ConfigUtils.addOrGetModule(config, CadytsConfigGroup.class ) ; - - this.calibratedLines = toTransitLineIdSet( ccc.getCalibratedLines() ) ; - this.timeBinSize = ccc.getTimeBinSize() ; - - this.maxTime = Time.MIDNIGHT-1; //24 * 3600 - 1; - // (yy not completely clear if it might be better to use 24*this.timeBimSize, but it is overall not so great - // to have this hardcoded. kai/manuel, jul'12) - - this.maxSlotIndex = ((int) this.maxTime) / this.timeBinSize + 1; - this.occupancies = new HashMap<>(); - } - - @Override - public void reset(final int iteration) { - this.occupancies.clear(); - this.vehStops.clear(); - this.vehPassengers.clear(); - this.occupancyRecord = new StringBuffer("time\tvehId\tStopId\tno.ofPassengersInVeh\n"); - this.analyzedTransitDrivers.clear(); - this.analyzedTransitVehicles.clear(); - } - - @Override - public void handleEvent(final TransitDriverStartsEvent event) { - if (this.calibratedLines.contains(event.getTransitLineId())) { - this.analyzedTransitDrivers.add(event.getDriverId()); - this.analyzedTransitVehicles.add(event.getVehicleId()); - } - } - - @Override - public void handleEvent(final PersonEntersVehicleEvent event) { - if (this.analyzedTransitDrivers.contains(event.getPersonId()) || !this.analyzedTransitVehicles.contains(event.getVehicleId())) { - return; // ignore transit drivers or persons entering non-(analyzed-)transit vehicles - } - - // ------------------veh_passenger- (for occupancy)----------------- - Id vehId = event.getVehicleId(); - Id stopId = this.vehStops.get(vehId); - double time = event.getTime(); - Integer nPassengers = this.vehPassengers.get(vehId); - this.vehPassengers.put(vehId, (nPassengers != null) ? (nPassengers + 1) : 1); - this.occupancyRecord.append("time :\t").append(time).append(" veh :\t").append(vehId).append(" has Passenger\t").append(this.vehPassengers.get(vehId)).append(" \tat stop :\t").append(stopId).append(" ENTERING PERSON :\t").append(event.getPersonId()).append("\n"); - } - - @Override - public void handleEvent(final PersonLeavesVehicleEvent event) { - if (this.analyzedTransitDrivers.contains(event.getPersonId()) || !this.analyzedTransitVehicles.contains(event.getVehicleId())) { - return; // ignore transit drivers or persons entering non-(analyzed-)transit vehicles - } - - // ----------------veh_passenger-(for occupancy)-------------------------- - Id vehId = event.getVehicleId(); - double time = event.getTime(); - Integer nPassengers = this.vehPassengers.get(vehId); - if (nPassengers == null) { - throw new RuntimeException("null passenger-No. in vehicle ?"); - } - this.vehPassengers.put(vehId, nPassengers - 1); - if (this.vehPassengers.get(vehId) == 0) { - this.vehPassengers.remove(vehId); - } - Integer passengers = this.vehPassengers.get(vehId); - this.occupancyRecord.append("time :\t").append(time).append(" veh :\t").append(vehId).append(" has Passenger\t").append((passengers != null) ? passengers : 0).append("\n"); - } - - @Override - public void handleEvent(final VehicleDepartsAtFacilityEvent event) { - Id vehId = event.getVehicleId(); - Id facId = event.getFacilityId(); - - // -----------------------occupancy-------------------------------- - this.vehStops.remove(vehId); - int[] occupancyAtStop = this.occupancies.get(facId); - if (occupancyAtStop == null) { // no previous departure from this stop, therefore no occupancy - // record yet. Create this: - occupancyAtStop = new int[this.maxSlotIndex + 1]; - this.occupancies.put(facId, occupancyAtStop); - } - - Integer noPassengersInVeh = this.vehPassengers.get(vehId); - - if (noPassengersInVeh != null) { - occupancyAtStop[this.getTimeSlotIndex(event.getTime())] += noPassengersInVeh; - this.occupancyRecord.append(event.getTime()); - this.occupancyRecord.append("\t"); - this.occupancyRecord.append(vehId); - this.occupancyRecord.append("\t"); - this.occupancyRecord.append(facId); - this.occupancyRecord.append("\t"); - this.occupancyRecord.append(noPassengersInVeh); - this.occupancyRecord.append("\n"); - } - } - - @Override - public void handleEvent(final VehicleArrivesAtFacilityEvent event) { - Id stopId = event.getFacilityId(); - - this.vehStops.put(event.getVehicleId(), stopId); - // (constructing a table with vehId as key, and stopId as value; constructed when veh arrives at - // stop; necessary - // since personEnters/LeavesVehicle does not carry stop id) - } - - private int getTimeSlotIndex(final double time) { - if (time > this.maxTime) { - return this.maxSlotIndex; - } - return ((int) time / this.timeBinSize); - } - - /** - * @param stopId - * @return Array containing the number of passengers in bus after the transfer at the stop - * {@code stopId} per time bin, starting with time bin 0 from 0 seconds to - * (timeBinSize-1)seconds. - */ - @Override - public int[] getOccupancyVolumesForStop(final Id stopId) { - return this.occupancies.get(stopId); - } - /* (non-Javadoc) - * @see org.matsim.contrib.cadyts.pt.CadytsPtOccupancyAnalyzerI#getOccupancyVolumeForStopAndTime(org.matsim.api.core.v01.Id, int) - */ - @Override - public int getOccupancyVolumeForStopAndTime(final Id stopId, final int time_s ) { - if ( this.occupancies.get(stopId) != null ) { - int timeBinIndex = getTimeSlotIndex( time_s ) ; - return this.occupancies.get(stopId)[timeBinIndex] ; - } else { - return 0 ; - } - } - - public Set> getOccupancyStopIds() { - return this.occupancies.keySet(); - } - - @Override - public void writeResultsForSelectedStopIds(final String filename, final Counts occupCounts, final Collection> stopIds) { - SimpleWriter writer = new SimpleWriter(filename); - - final String TAB = "\t"; - final String NL = "\n"; - - // write header - writer.write("stopId\t"); - for (int i = 0; i < 24; i++) { - writer.write("oc" + i + "-" + (i + 1) + TAB); - } - for (int i = 0; i < 24; i++) { - writer.write("scalSim" + i + "-" + (i + 1) + TAB); - } - writer.write("coordinate\tcsId\n"); - - // write content - for (Id stopId : stopIds) { - // get count data - Count count = occupCounts.getCounts().get(Id.create(stopId, TransitStopFacility.class)); - if (!occupCounts.getCounts().containsKey(Id.create(stopId, TransitStopFacility.class))) { - continue; - } - - // get sim-Values - int[] ocuppancy = this.occupancies.get(stopId); - writer.write(stopId.toString() + TAB); - for (int i = 0; i < ocuppancy.length; i++) { - Volume v = count.getVolume(i + 1); - if (v != null) { - writer.write(v.getValue() + TAB); - } else { - writer.write("n/a" + TAB); - } - } - for (int anOcuppancy : ocuppancy) { - writer.write((anOcuppancy) + TAB); - } - writer.write(count.getCoord().toString() + TAB + count.getCsLabel() + NL); - } - writer.write(this.occupancyRecord.toString()); - writer.close(); - } - - @Override - public String toString() { - final StringBuilder stringBuffer2 = new StringBuilder(); - final String STOPID = "stopId: "; - final String VALUES = "; values:"; - final char TAB = '\t'; - final char RETURN = '\n'; - - for (Id stopId : this.getOccupancyStopIds()) { // Only occupancy! - StringBuilder stringBuffer = new StringBuilder(); - stringBuffer.append(STOPID); - stringBuffer.append(stopId); - stringBuffer.append(VALUES); - - boolean hasValues = false; // only prints stops with volumes > 0 - int[] values = this.getOccupancyVolumesForStop(stopId); - - for (int value : values) { - hasValues = hasValues || (value > 0); - - stringBuffer.append(TAB); - stringBuffer.append(value); - } - stringBuffer.append(RETURN); - if (hasValues) - stringBuffer2.append(stringBuffer.toString()); - - } - return stringBuffer2.toString(); - } - - public static Set> toTransitLineIdSet(Set list) { - Set> converted = new LinkedHashSet<>(); - - for ( String id : list) { - converted.add(Id.create(id, TransitLine.class)); - } - - return converted; - } - - -} diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtOccupancyAnalyzerI.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtOccupancyAnalyzerI.java deleted file mode 100644 index 069fe358fd9..00000000000 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/CadytsPtOccupancyAnalyzerI.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.matsim.contrib.cadyts.pt; - -import java.util.Collection; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.handler.PersonEntersVehicleEventHandler; -import org.matsim.api.core.v01.events.handler.PersonLeavesVehicleEventHandler; -import org.matsim.api.core.v01.events.handler.TransitDriverStartsEventHandler; -import org.matsim.api.core.v01.network.Link; -import org.matsim.core.api.experimental.events.handler.VehicleArrivesAtFacilityEventHandler; -import org.matsim.core.api.experimental.events.handler.VehicleDepartsAtFacilityEventHandler; -import org.matsim.counts.Counts; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -public interface CadytsPtOccupancyAnalyzerI extends TransitDriverStartsEventHandler, PersonEntersVehicleEventHandler, -PersonLeavesVehicleEventHandler, VehicleArrivesAtFacilityEventHandler, VehicleDepartsAtFacilityEventHandler { - - int getOccupancyVolumeForStopAndTime(Id stopId, int time_s); - - void writeResultsForSelectedStopIds(String filename, Counts occupCounts, Collection> stopIds); - - int[] getOccupancyVolumesForStop(Id stopId); - -} diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/PtPlanToPlanStepBasedOnEvents.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/PtPlanToPlanStepBasedOnEvents.java deleted file mode 100644 index f9ab329ad5a..00000000000 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/PtPlanToPlanStepBasedOnEvents.java +++ /dev/null @@ -1,238 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * copyright : (C) 2012 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.contrib.cadyts.pt; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -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; -import org.matsim.api.core.v01.events.PersonLeavesVehicleEvent; -import org.matsim.api.core.v01.events.TransitDriverStartsEvent; -import org.matsim.api.core.v01.events.handler.PersonEntersVehicleEventHandler; -import org.matsim.api.core.v01.events.handler.PersonLeavesVehicleEventHandler; -import org.matsim.api.core.v01.events.handler.TransitDriverStartsEventHandler; -import org.matsim.api.core.v01.population.Person; -import org.matsim.api.core.v01.population.Plan; -import org.matsim.contrib.cadyts.general.PlansTranslator; -import org.matsim.core.api.experimental.events.VehicleDepartsAtFacilityEvent; -import org.matsim.core.api.experimental.events.handler.VehicleDepartsAtFacilityEventHandler; -import org.matsim.core.scenario.MutableScenario; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -import cadyts.demand.PlanBuilder; - -/*package*/ class PtPlanToPlanStepBasedOnEvents implements TransitDriverStartsEventHandler, PersonEntersVehicleEventHandler, - PersonLeavesVehicleEventHandler, VehicleDepartsAtFacilityEventHandler, PlansTranslator { - private static final Logger log = LogManager.getLogger(PtPlanToPlanStepBasedOnEvents.class); - - private final Scenario sc; - private final TransitSchedule schedule; - - private final Map> personsFromVehId = new HashMap<>(); - - private int iteration = -1; - - // this is _only_ there for output: - Set plansEverSeen = new HashSet<>(); - - private static final String STR_PLANSTEPFACTORY = "planStepFactory"; - private static final String STR_ITERATION = "iteration"; - // (better to do it this way since when plans are removed, this additional info is removed as well) - - private final Set transitDrivers = new HashSet<>(); - private final Set transitVehicles = new HashSet<>(); - private final Set> calibratedLines; - - PtPlanToPlanStepBasedOnEvents(final Scenario sc, final Set> calibratedLines) { - this.sc = sc; - this.schedule = ((MutableScenario) sc).getTransitSchedule(); - this.calibratedLines = calibratedLines; - } - - private long plansFound = 0; - private long plansNotFound = 0; - - @Override - public final cadyts.demand.Plan getCadytsPlan(final Plan plan) { - @SuppressWarnings("unchecked") // getting stuff from custom attributes has to be untyped. - PlanBuilder planStepFactory = (PlanBuilder) plan.getCustomAttributes().get(STR_PLANSTEPFACTORY); - if (planStepFactory == null) { - this.plansNotFound++; - return null; - } - this.plansFound++; - final cadyts.demand.Plan planSteps = planStepFactory.getResult(); - return planSteps; - } - - @Override - public void reset(final int it) { - this.iteration = it; - - log.warn("found " + this.plansFound + " out of " + (this.plansFound + this.plansNotFound) + " (" - + (100. * this.plansFound / (this.plansFound + this.plansNotFound)) + "%)"); - log.warn("(above values may both be at zero for a couple of iterations if multiple plans per agent all have no score)"); - - long nPlans = 0 ; - long nMemorizedPlans = 0 ; - - for ( Person person : this.sc.getPopulation().getPersons().values() ) { - for ( Plan plan : person.getPlans() ) { - nPlans ++ ; - @SuppressWarnings("unchecked") // getting stuff from custom attributes has to be untyped. - PlanBuilder planStepFactory = (PlanBuilder) plan.getCustomAttributes().get(STR_PLANSTEPFACTORY); - if ( planStepFactory!=null ) { - nMemorizedPlans ++ ; - } - } - } - - log.warn( "nPlans=" + nPlans + ", nMemorizedPlans=" + nMemorizedPlans ); - - this.personsFromVehId.clear(); - this.transitDrivers.clear(); - this.transitVehicles.clear(); - } - - @Override - public void handleEvent(final TransitDriverStartsEvent event) { - if (this.calibratedLines.contains(event.getTransitLineId())) { - this.transitDrivers.add(event.getDriverId()); - this.transitVehicles.add(event.getVehicleId()); - } - } - - @Override - public void handleEvent(final PersonEntersVehicleEvent event) { - if (this.transitDrivers.contains(event.getPersonId()) || !this.transitVehicles.contains(event.getVehicleId())) { - return; // ignore transit drivers or persons entering non-(analyzed-)transit vehicles - } - addPersonToVehicleContainer(event.getPersonId(), event.getVehicleId()); - } - - @Override - public void handleEvent(final PersonLeavesVehicleEvent event) { - if (this.transitDrivers.contains(event.getPersonId()) || !this.transitVehicles.contains(event.getVehicleId())) { - return; // ignore transit drivers or persons entering non-(analyzed-)transit vehicles - } - removePersonFromVehicleContainer(event.getPersonId(), event.getVehicleId()); - } - - @Override - public void handleEvent(final VehicleDepartsAtFacilityEvent event) { - double time = event.getTime(); - Id vehId = event.getVehicleId(); - Id facId = event.getFacilityId(); - if (this.personsFromVehId.get(vehId) == null) { - // (means nobody has entered the vehicle yet) - return; - } - TransitStopFacility fac = this.schedule.getFacilities().get(facId); - - for (Id personId : this.personsFromVehId.get(vehId)) { - // get the "Person" behind the id: - Person person = this.sc.getPopulation().getPersons().get(personId); - - // get the selected plan: - Plan selectedPlan = person.getSelectedPlan(); - - // get the planStepFactory for the plan (or create one): - PlanBuilder tmpPlanStepFactory = getPlanStepFactoryForPlan(selectedPlan); - - if (tmpPlanStepFactory != null) { - // add the "turn" to the planStepfactory - tmpPlanStepFactory.addTurn(fac, (int) time); - } - } - } - - // ################################################################################### - // only private functions below here (low level functionality) - - private void addPersonToVehicleContainer(final Id personId, final Id vehId) { - // get the personsContainer that belongs to the vehicle: - Collection personsInVehicle = this.personsFromVehId.get(vehId); - - if (personsInVehicle == null) { - // means does not exist yet - personsInVehicle = new ArrayList<>(); - this.personsFromVehId.put(vehId, personsInVehicle); - } - - personsInVehicle.add(personId); - } - - private void removePersonFromVehicleContainer(final Id personId, final Id vehId) { - // get the personsContainer that belongs to the vehicle: - Collection personsInVehicle = this.personsFromVehId.get(vehId); - - if (personsInVehicle == null) { - throw new RuntimeException("should not be possible: person should enter before leaving, and then construct the container"); - } - - // remove the person from the personsContainer: - personsInVehicle.remove(personId); // linear time operation; a HashMap might be better. - } - - private PlanBuilder getPlanStepFactoryForPlan(final Plan selectedPlan) { - PlanBuilder planStepFactory = null; - - planStepFactory = (PlanBuilder) selectedPlan.getCustomAttributes().get(STR_PLANSTEPFACTORY); - Integer factoryIteration = (Integer) selectedPlan.getCustomAttributes().get(STR_ITERATION); - if (planStepFactory == null || factoryIteration == null || factoryIteration != this.iteration) { - // attach the iteration number to the plan: - selectedPlan.getCustomAttributes().put(STR_ITERATION, this.iteration); - - // construct a new PlanBulder and attach it to the plan: - planStepFactory = new PlanBuilder<>(); - selectedPlan.getCustomAttributes().put(STR_PLANSTEPFACTORY, planStepFactory); - - // memorize the plan as being seen: - this.plansEverSeen.add(selectedPlan); - } - - return planStepFactory; - } - - static void printCadytsPlan(final cadyts.demand.Plan cadytsPlan) { - // prints Cadyts plan - String sepCadStr = "==printing Cadyts Plan=="; - System.err.println(sepCadStr); - if (cadytsPlan != null) { - for (int ii = 0; ii < cadytsPlan.size(); ii++) { - cadyts.demand.PlanStep cadytsPlanStep = cadytsPlan.getStep(ii); - System.err.println("stopId" + cadytsPlanStep.getLink().getId() + " time: " + cadytsPlanStep.getEntryTime_s()); - } - } else { - System.err.println(" cadyts plan is null "); - } - } - -} diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/TransitStopFacilityLookUp.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/TransitStopFacilityLookUp.java deleted file mode 100644 index 651b2a99c66..00000000000 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/TransitStopFacilityLookUp.java +++ /dev/null @@ -1,48 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* * - * * - * *********************************************************************** * - * * - * copyright : (C) 2008 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ -package org.matsim.contrib.cadyts.pt; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.cadyts.general.LookUpItemFromId; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -/** - * @author nagel - * - */ -class TransitStopFacilityLookUp implements LookUpItemFromId { - - private TransitSchedule schedule; - - public TransitStopFacilityLookUp( Scenario sc ) { - this.schedule = sc.getTransitSchedule() ; - } - - public TransitStopFacilityLookUp( TransitSchedule schedule ) { - this.schedule = schedule ; - } - - @Override - public TransitStopFacility getItem(Id id) { - return this.schedule.getFacilities().get(id); - } - -} diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/package-info.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/package-info.java deleted file mode 100644 index 0b45babafa5..00000000000 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/pt/package-info.java +++ /dev/null @@ -1,74 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* * - * * - * *********************************************************************** * - * * - * copyright : (C) 2008 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 * - * * - * *********************************************************************** */ -/** - * Integrates automatic calibration upon public transport line occupancies using Cadyts into MATSim. - * - *

Entry point / How to use

- *
    - *
  • Use org.matsim.contrib.cadyts.pt.CadytsPtPlanStrategy as a replanning strategy.
  • - *
  • Add the following configuration parameters (approximately; this has changed since inception; - * check auto-generated config comments; use second config dump for that): - *
    - * <module name="cadytsPt">
    - *   <param name="startTime" value="05:00:00" />
    - *
    - *   <param name="endTime" value="21:00:00" />
    - *
    - *   <!-- Comma-separated list of transit lines to be calibrated. ->
    - *   <param name="calibratedLines" value="M44" />
    - *
    - *   <param name="writeAnalysisFile" value="false" />
    - *
    - *   <!-- see cadyts documentation for the meaning of the following values. -->
    - *   <param name="regressionInertia" value="0.95" />
    - *   <param name="minFlowStddevVehH" value="8.0" />
    - *   <param name="freezeIteration" value="2147483647" />
    - *   <param name="preparatoryIterations" value="1" />
    - *   <param name="varianceScale" value="1.0" />
    - *   <param name="useBruteForce" value="true" />
    - *
    - * </module>
    - * These parameters are defined in {@link org.matsim.contrib.cadyts.general.CadytsConfigGroup} - * - *
  • - *
  • There also needs to be a ptCounts entry, something like: - *
    - *
    - * 	<module name="ptCounts">
    - *		<param name="inputOccupancyCountsFile" value="path-to-counts-file" />
    - *	</module>
    - * And (obviously) a working ptCounts file. - *
  • - *
  • It is a unfortunate that the counts file takes measurements in hourly values, while cadyts takes arbitrary time spans. - * (The cadyts convention seems more powerful, thus we did not want to reduce it to the "Counts" convention.) - * As long as the cadytsPt timeBinSize is set to 3600, things should be straightforward, and there is also (I think) no - * problem if there are measurements for times outside the cadytsPt startTime/endTime interval. yyyy Unfortunately, - * I cannot remember how the counts file is interpreted once the cadytsPt timeBinSize is set to something different: Does the - * Counts file than think in terms of time bins rather than in terms of hours? In fact, I think not; rather, it is probably as - * follows: Counts still refer to hours. If, say, you use timeBinSize of 7200 and start/endTime as 05:00/09:00, then the code - * will aggregate counts from the 6th and 7th hour into one time bin, etc. If things do not correspond, the code will probably - * complain. See CadytsBuilder.buildCalibrator, since there are some consistency checks. (kai, oct'12) - *
  • Typically, {@link org.matsim.contrib.cadyts.pt.CadytsPtPlanStrategy} should be the only - * plan strategy being used. So it is advised to first run the simulation until every - * agent has a few (different) plans, and then do some iterations using only the - * calibration strategy.
  • - *
- * - */ -package org.matsim.contrib.cadyts.pt; diff --git a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/run/RunCadyts4CarExample.java b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/run/RunCadyts4CarExample.java index 4ad3a583ad5..1e1e8d5e95e 100644 --- a/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/run/RunCadyts4CarExample.java +++ b/contribs/cadytsIntegration/src/main/java/org/matsim/contrib/cadyts/run/RunCadyts4CarExample.java @@ -74,7 +74,7 @@ public ScoringFunction createNewScoringFunction(Person person) { scoringFunctionAccumulator.addScoringFunction(new CharyparNagelAgentStuckScoring(params)); final CadytsScoring scoringFunction = new CadytsScoring<>(person.getSelectedPlan(), config, cadytsContext); - scoringFunction.setWeightOfCadytsCorrection(30. * config.planCalcScore().getBrainExpBeta()) ; + scoringFunction.setWeightOfCadytsCorrection(30. * config.scoring().getBrainExpBeta()) ; scoringFunctionAccumulator.addScoringFunction(scoringFunction ); return scoringFunctionAccumulator; diff --git a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/car/CadytsCarIT.java b/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/car/CadytsCarIT.java index b07564f0a8f..6b72ab1b664 100644 --- a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/car/CadytsCarIT.java +++ b/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/car/CadytsCarIT.java @@ -38,9 +38,9 @@ import org.matsim.contrib.cadyts.utils.CalibrationStatReader; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup.MobsimType; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ControllerConfigGroup.MobsimType; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.ControlerDefaultsModule; import org.matsim.core.controler.ControlerI; @@ -89,12 +89,12 @@ public final void testInitialization() { String outputDir = this.utils.getOutputDirectory(); Config config = createTestConfig(inputDir, outputDir); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); StrategySettings strategySettings = new StrategySettings(Id.create(1, StrategySettings.class)); strategySettings.setStrategyName(CADYTS_STRATEGY_NAME) ; strategySettings.setWeight(1.0) ; - config.strategy().addStrategySettings(strategySettings); + config.replanning().addStrategySettings(strategySettings); CadytsConfigGroup cadytsCar = ConfigUtils.addOrGetModule(config, CadytsConfigGroup.GROUP_NAME, CadytsConfigGroup.class); // cadytsCar.addParam("startTime", "04:00:00"); cadytsCar.setStartTime( 4*3600 ); @@ -164,11 +164,11 @@ public final void testCalibrationAsScoring() throws IOException { final Config config = createTestConfig(inputDir, outputDir); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); - config.planCalcScore().setBrainExpBeta(beta); + config.scoring().setBrainExpBeta(beta); - config.strategy().addStrategySettings( new StrategySettings().setStrategyName( DefaultSelector.ChangeExpBeta ).setWeight( 1.0 ) ); + config.replanning().addStrategySettings( new StrategySettings().setStrategyName( DefaultSelector.ChangeExpBeta ).setWeight( 1.0 ) ); // === @@ -320,22 +320,22 @@ private static Config createTestConfig(String inputDir, String outputDir) { config.global().setRandomSeed(4711) ; config.network().setInputFile(inputDir + "network.xml") ; config.plans().setInputFile(inputDir + "plans5.xml") ; - config.controler().setFirstIteration(1) ; - config.controler().setLastIteration(10) ; - config.controler().setOutputDirectory(outputDir) ; - config.controler().setWriteEventsInterval(1) ; - config.controler().setMobsim(MobsimType.qsim.toString()) ; + config.controller().setFirstIteration(1) ; + config.controller().setLastIteration(10) ; + config.controller().setOutputDirectory(outputDir) ; + config.controller().setWriteEventsInterval(1) ; + config.controller().setMobsim(MobsimType.qsim.toString()) ; config.qsim().setFlowCapFactor(1.) ; config.qsim().setStorageCapFactor(1.) ; config.qsim().setStuckTime(10.) ; config.qsim().setRemoveStuckVehicles(false) ; { ActivityParams params = new ActivityParams("h") ; - config.planCalcScore().addActivityParams(params ) ; + config.scoring().addActivityParams(params ) ; params.setTypicalDuration(12*60*60.) ; }{ ActivityParams params = new ActivityParams("w") ; - config.planCalcScore().addActivityParams(params ) ; + config.scoring().addActivityParams(params ) ; params.setTypicalDuration(8*60*60.) ; } config.counts().setInputFile(inputDir + "counts5.xml"); diff --git a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/car/CadytsCarWithPtScenarioIT.java b/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/car/CadytsCarWithPtScenarioIT.java index 538a47ae917..58f3b81fb2f 100644 --- a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/car/CadytsCarWithPtScenarioIT.java +++ b/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/car/CadytsCarWithPtScenarioIT.java @@ -25,8 +25,8 @@ public class CadytsCarWithPtScenarioIT { @Test @Ignore public void testCadytsWithPtVehicles() { final Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("siouxfalls-2014"), "config_default.xml")); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setLastIteration(0); final Scenario scenario = ScenarioUtils.loadScenario(config); final Counts calibrationCounts = new Counts<>(); final Id testLink = Id.createLinkId("6_1"); diff --git a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/pt/CadytsPtIT.java b/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/pt/CadytsPtIT.java deleted file mode 100644 index 9ea725add52..00000000000 --- a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/pt/CadytsPtIT.java +++ /dev/null @@ -1,690 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * CadytsIntegrationTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2011 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.contrib.cadyts.pt; - -import cadyts.measurements.SingleLinkMeasurement; -import cadyts.utilities.io.tabularFileParser.TabularFileParser; -import cadyts.utilities.misc.DynamicData; -import com.google.inject.Provider; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Scenario; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.cadyts.general.CadytsConfigGroup; -import org.matsim.contrib.cadyts.general.CadytsCostOffsetsXMLFileIO; -import org.matsim.contrib.cadyts.general.CadytsPlanChanger; -import org.matsim.contrib.cadyts.general.CadytsScoring; -import org.matsim.contrib.cadyts.utils.CalibrationStatReader; -import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.config.Config; -import org.matsim.core.config.ConfigGroup; -import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup.MobsimType; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlansConfigGroup.HandlingOfPlansWithoutRoutingMode; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; -import org.matsim.core.controler.AbstractModule; -import org.matsim.core.controler.Controler; -import org.matsim.core.mobsim.framework.Mobsim; -import org.matsim.core.mobsim.framework.MobsimFactory; -import org.matsim.core.replanning.PlanStrategy; -import org.matsim.core.replanning.PlanStrategyImpl; -import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.core.scoring.ScoringFunction; -import org.matsim.core.scoring.ScoringFunctionFactory; -import org.matsim.core.scoring.SumScoringFunction; -import org.matsim.core.scoring.functions.CharyparNagelActivityScoring; -import org.matsim.core.scoring.functions.CharyparNagelAgentStuckScoring; -import org.matsim.core.scoring.functions.CharyparNagelLegScoring; -import org.matsim.core.scoring.functions.ScoringParameters; -import org.matsim.core.scoring.functions.ScoringParametersForPerson; -import org.matsim.counts.Count; -import org.matsim.counts.Counts; -import org.matsim.counts.MatsimCountsReader; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.testcases.MatsimTestUtils; - -import jakarta.inject.Inject; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -public class CadytsPtIT { - - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); - - @Test - public final void testInitialization() { - String inputDir = this.utils.getClassInputDirectory(); - - Config config = createTestConfig(inputDir, this.utils.getOutputDirectory()); - config.controler().setLastIteration(0); - StrategySettings stratSets = new StrategySettings(); - stratSets.setStrategyName("ccc") ; - stratSets.setWeight(1.) ; - config.strategy().addStrategySettings(stratSets) ; - - final Scenario scenario = ScenarioUtils.loadScenario(config) ; - final Controler controler = new Controler(scenario); - controler.addOverridingModule(new CadytsPtModule()); - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - addPlanStrategyBinding("ccc").toProvider(new jakarta.inject.Provider() { - @Inject CadytsPtContext context; - @Override - public PlanStrategy get() { - return new PlanStrategyImpl(new CadytsPlanChanger<>(scenario, context)); - } - }); - } - }); - - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setWriteEventsInterval(0); - controler.getConfig().controler().setDumpDataAtEnd(true); - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - bindMobsim().toProvider(new Provider() { - @Override - public Mobsim get() { - return new DummyMobsimFactory().createMobsim(controler.getScenario(), controler.getEvents()); - } - }); - } - }); - controler.run(); - - CadytsPtContext context = controler.getInjector().getInstance(CadytsPtContext.class); - - //test calibration settings - Assert.assertEquals(true, context.getCalibrator().getBruteForce()); - Assert.assertEquals(false, context.getCalibrator().getCenterRegression()); - Assert.assertEquals(Integer.MAX_VALUE, context.getCalibrator().getFreezeIteration()); - Assert.assertEquals(8.0, context.getCalibrator().getMinStddev(SingleLinkMeasurement.TYPE.FLOW_VEH_H), MatsimTestUtils.EPSILON); - Assert.assertEquals(1, context.getCalibrator().getPreparatoryIterations()); - Assert.assertEquals(0.95, context.getCalibrator().getRegressionInertia(), MatsimTestUtils.EPSILON); - Assert.assertEquals(1.0, context.getCalibrator().getVarianceScale(), MatsimTestUtils.EPSILON); - Assert.assertEquals(3600.0, context.getCalibrator().getTimeBinSize_s(), MatsimTestUtils.EPSILON); - } - - - @Test - public final void testCalibrationAsScoring() throws IOException { - final double beta=30. ; - final int lastIteration = 20 ; - - String inputDir = this.utils.getClassInputDirectory(); - String outputDir = this.utils.getOutputDirectory(); - - final Config config = createTestConfig(inputDir, outputDir); - - config.controler().setLastIteration(lastIteration) ; - - config.planCalcScore().setBrainExpBeta(beta) ; - - StrategySettings stratSets = new StrategySettings() ; - stratSets.setStrategyName("ChangeExpBeta") ; - stratSets.setWeight(1.0) ; - config.strategy().addStrategySettings(stratSets) ; - - // === - - final Controler controler = new Controler(config); - controler.getConfig().controler().setCreateGraphs(false); - controler.addOverridingModule(new CadytsPtModule()); - - controler.setScoringFunctionFactory(new ScoringFunctionFactory() { - @Inject ScoringParametersForPerson parameters; - @Inject Network network; - @Inject CadytsPtContext cContext; - @Override - public ScoringFunction createNewScoringFunction(Person person) { - final ScoringParameters params = parameters.getScoringParameters(person); - - SumScoringFunction scoringFunctionAccumulator = new SumScoringFunction(); - scoringFunctionAccumulator.addScoringFunction(new CharyparNagelLegScoring(params, network, config.transit().getTransitModes())); - scoringFunctionAccumulator.addScoringFunction(new CharyparNagelActivityScoring(params)) ; - scoringFunctionAccumulator.addScoringFunction(new CharyparNagelAgentStuckScoring(params)); - - final CadytsScoring scoringFunction = new CadytsScoring(person.getSelectedPlan() ,config, cContext); - scoringFunction.setWeightOfCadytsCorrection(beta*30.) ; - scoringFunctionAccumulator.addScoringFunction(scoringFunction ); - - return scoringFunctionAccumulator; - } - }) ; - - controler.run(); - - //scenario data test - Assert.assertNotNull("Config is null" , controler.getConfig()); - Assert.assertEquals("Different number of links in network.", controler.getScenario().getNetwork().getLinks().size() , 23 ); - Assert.assertEquals("Different number of nodes in network.", controler.getScenario().getNetwork().getNodes().size() , 15 ); - Assert.assertNotNull("Transit schedule is null.", controler.getScenario().getTransitSchedule()); - Assert.assertEquals("Num. of trLines is wrong.", 2, controler.getScenario().getTransitSchedule().getTransitLines().size() ); - Assert.assertEquals("Num of facilities in schedule is wrong.", controler.getScenario().getTransitSchedule().getFacilities().size() , 5); - Assert.assertNotNull("Population is null.", controler.getScenario().getPopulation()); - Assert.assertEquals("Num. of persons in population is wrong.", controler.getScenario().getPopulation().getPersons().size() , 4); - Assert.assertEquals("Scale factor is wrong.", controler.getScenario().getConfig().ptCounts().getCountsScaleFactor(), 1.0, MatsimTestUtils.EPSILON); - // Assert.assertEquals("Distance filter is wrong.", controler.getTestScenarioURL().getConfig().ptCounts().getDistanceFilter() , 30000.0, MatsimTestUtils.EPSILON); - // Assert.assertEquals("DistanceFilterCenterNode is wrong.", controler.getTestScenarioURL().getConfig().ptCounts().getDistanceFilterCenterNode(), "7"); - //counts - Assert.assertEquals("Occupancy count file is wrong.", controler.getScenario().getConfig().ptCounts().getOccupancyCountsFileName(), inputDir + "counts/counts_occupancy.xml"); - Counts occupCounts = new Counts(); - new MatsimCountsReader(occupCounts).readFile(controler.getScenario().getConfig().ptCounts().getOccupancyCountsFileName()); - Count count = occupCounts.getCount(Id.create("stop1", Link.class)); // casting id from stop to link, not nice - Assert.assertEquals("Occupancy counts description is wrong", occupCounts.getDescription(), "counts values for equil net"); - Assert.assertEquals("CsId is wrong.", count.getCsLabel() , "stop1"); - Assert.assertEquals("Volume of hour 4 is wrong", count.getVolume(7).getValue(), 4.0 , MatsimTestUtils.EPSILON); - Assert.assertEquals("Max count volume is wrong.", count.getMaxVolume().getValue(), 4.0 , MatsimTestUtils.EPSILON); - - // test resulting simulation volumes - { - String outCounts = outputDir + "ITERS/it." + lastIteration + "/" + lastIteration + ".simCountCompareOccupancy.txt"; - CountsReaderPt reader = new CountsReaderPt(outCounts); - double[] simValues; - double[] realValues; - - Id stopId1 = Id.create("stop1", TransitStopFacility.class); - simValues = reader.getSimulatedValues(stopId1); - realValues= reader.getRealValues(stopId1); - Assert.assertEquals("Volume of hour 6 is wrong", 4.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 is wrong", 4.0, realValues[6], MatsimTestUtils.EPSILON); - - Id stopId2 = Id.create("stop2", TransitStopFacility.class); - simValues = reader.getSimulatedValues(stopId2); - realValues= reader.getRealValues(stopId2); -// Assert.assertEquals("Volume of hour 6 is wrong", 0.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 is wrong", 2.0, simValues[6], MatsimTestUtils.EPSILON); // Altered after using ChangeExpBeta instead of "ccc" - Assert.assertEquals("Volume of hour 6 is wrong", 1.0, realValues[6] , MatsimTestUtils.EPSILON); - - Id stopId6 = Id.create("stop6", TransitStopFacility.class); - simValues = reader.getSimulatedValues(stopId6); - realValues= reader.getRealValues(stopId6); - Assert.assertEquals("Volume of hour 6 is wrong", 0.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 is wrong", 2.0, realValues[6], MatsimTestUtils.EPSILON); - - Id stopId10 = Id.create("stop10", TransitStopFacility.class); - simValues = reader.getSimulatedValues(stopId10); - realValues= reader.getRealValues(stopId10); -// Assert.assertEquals("Volume of hour 6 is wrong", 4.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 is wrong", 2.0, simValues[6], MatsimTestUtils.EPSILON); // Altered after using ChangeExpBeta instead of "ccc" - Assert.assertEquals("Volume of hour 6 is wrong", 5.0, realValues[6], MatsimTestUtils.EPSILON); - - // test calibration statistics - String testCalibStatPath = outputDir + "calibration-stats.txt"; - CalibrationStatReader calibrationStatReader = new CalibrationStatReader(); - new TabularFileParser().parse(testCalibStatPath, calibrationStatReader); - - CalibrationStatReader.StatisticsData outStatData= calibrationStatReader.getCalStatMap().get(lastIteration); -// Assert.assertEquals("different Count_ll", "-0.046875", outStatData.getCount_ll() ); - Assert.assertEquals("different Count_ll", "-0.109375", outStatData.getCount_ll() ); // Altered after using ChangeExpBeta instead of "ccc" -// Assert.assertEquals("different Count_ll_pred_err", "0.01836234363152515" , outStatData.getCount_ll_pred_err() ); - Assert.assertEquals("different Count_ll_pred_err", "0.008411478550953913" , outStatData.getCount_ll_pred_err() ); // Altered after using ChangeExpBeta instead of "ccc" - // Assert.assertEquals("different Link_lambda_avg", "-2.2604922388914356E-10", outStatData.getLink_lambda_avg() ); - // Assert.assertEquals("different Link_lambda_max", "0.0" , outStatData.getLink_lambda_max() ); - // Assert.assertEquals("different Link_lambda_min", "-7.233575164452593E-9", outStatData.getLink_lambda_min() ); - // Assert.assertEquals("different Link_lambda_stddev", "1.261054219517188E-9", outStatData.getLink_lambda_stddev()); - // Assert.assertEquals("different P2p_ll", "--" , outStatData.getP2p_ll()); - // Assert.assertEquals("different Plan_lambda_avg", "-7.233575164452594E-9", outStatData.getPlan_lambda_avg() ); - // Assert.assertEquals("different Plan_lambda_max", "-7.233575164452593E-9" , outStatData.getPlan_lambda_max() ); - // Assert.assertEquals("different Plan_lambda_min", "-7.233575164452593E-9" , outStatData.getPlan_lambda_min() ); - // Assert.assertEquals("different Plan_lambda_stddev", "0.0" , outStatData.getPlan_lambda_stddev()); -// Assert.assertEquals("different Total_ll", "-0.046875", outStatData.getTotal_ll() ); - Assert.assertEquals("different Total_ll", "-0.109375", outStatData.getTotal_ll() ); // Altered after using ChangeExpBeta instead of "ccc" - - - //test link offsets - final TransitSchedule schedule = controler.getScenario().getTransitSchedule(); - String linkOffsetFile = outputDir + "ITERS/it." + lastIteration + "/" + lastIteration + ".linkCostOffsets.xml"; - // CadytsPtLinkCostOffsetsXMLFileIO offsetReader = new CadytsPtLinkCostOffsetsXMLFileIO (schedule); - CadytsCostOffsetsXMLFileIO offsetReader - = new CadytsCostOffsetsXMLFileIO (new TransitStopFacilityLookUp(controler.getScenario()), TransitStopFacility.class); - DynamicData stopOffsets = offsetReader.read(linkOffsetFile); - - TransitStopFacility stop2 = schedule.getFacilities().get(stopId2); - TransitStopFacility stop10 = schedule.getFacilities().get(stopId10); - - //find first offset value different from null to compare. Useful to test with different time bin sizes - int binIndex=-1; - boolean isZero; - do { - binIndex++; - isZero = (Math.abs(stopOffsets.getBinValue(stop2 , binIndex) - 0.0) < MatsimTestUtils.EPSILON); - } while (isZero && binIndex<86400); - - Assert.assertEquals("Wrong bin index for first link offset", 6, binIndex); -// Assert.assertEquals("Wrong link offset of stop 10", 0.03515757824042241, stopOffsets.getBinValue(stop10 , binIndex), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong link offset of stop 10", 0.022383938774904025, stopOffsets.getBinValue(stop10 , binIndex), MatsimTestUtils.EPSILON); // Altered after using ChangeExpBeta instead of "ccc" -// Assert.assertEquals("Wrong link offset of stop 2", -0.011353248321030008, stopOffsets.getBinValue(stop2 , binIndex), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong link offset of stop 2", -0.008477236625252698, stopOffsets.getBinValue(stop2 , binIndex), MatsimTestUtils.EPSILON); // Altered after using ChangeExpBeta instead of "ccc" - } - } - - - @Test - public final void testCalibration() throws IOException { - final double beta = 30. ; - final int lastIteration = 20 ; - - String inputDir = this.utils.getClassInputDirectory(); - String outputDir = this.utils.getOutputDirectory(); - - Config config = createTestConfig(inputDir, outputDir) ; - - config.controler().setWriteEventsInterval(0) ; - config.controler().setLastIteration(lastIteration) ; - // seems to need 15 iterations as "warm-up"; at least the cadyts corrections are much smaller until then. - - config.planCalcScore().setBrainExpBeta(beta) ; - - StrategySettings stratSets = new StrategySettings(); - stratSets.setStrategyName("ccc") ; - stratSets.setWeight(1.) ; - config.strategy().addStrategySettings(stratSets) ; - - final Scenario scenario = ScenarioUtils.loadScenario(config) ; - - final Controler controler = new Controler( scenario ); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(true); - - controler.addOverridingModule(new CadytsPtModule()); - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - addPlanStrategyBinding("ccc").toProvider(new jakarta.inject.Provider() { - @Inject CadytsPtContext context; - @Override - public PlanStrategy get() { - final CadytsPlanChanger planSelector = new CadytsPlanChanger(scenario, context); - planSelector.setCadytsWeight(beta * 30.); - return new PlanStrategyImpl(planSelector); - } - }); - } - }); - - controler.run(); - - //scenario data test - Assert.assertNotNull("config is null" , controler.getConfig()); - Assert.assertEquals("Different number of links in network.", controler.getScenario().getNetwork().getLinks().size() , 23 ); - Assert.assertEquals("Different number of nodes in network.", controler.getScenario().getNetwork().getNodes().size() , 15 ); - Assert.assertNotNull("Transit schedule is null.", controler.getScenario().getTransitSchedule()); - Assert.assertEquals("Num. of trLines is wrong.", 2, controler.getScenario().getTransitSchedule().getTransitLines().size() ); - Assert.assertEquals("Num of facilities in schedule is wrong.", controler.getScenario().getTransitSchedule().getFacilities().size() , 5); - Assert.assertNotNull("Population is null.", controler.getScenario().getPopulation()); - Assert.assertEquals("Num. of persons in population is wrong.", controler.getScenario().getPopulation().getPersons().size() , 4); - Assert.assertEquals("Scale factor is wrong.", controler.getScenario().getConfig().ptCounts().getCountsScaleFactor(), 1.0, MatsimTestUtils.EPSILON); - // Assert.assertEquals("Distance filter is wrong.", controler.getTestScenarioURL().getConfig().ptCounts().getDistanceFilter() , 30000.0, MatsimTestUtils.EPSILON); - // Assert.assertEquals("DistanceFilterCenterNode is wrong.", controler.getTestScenarioURL().getConfig().ptCounts().getDistanceFilterCenterNode(), "7"); - //counts - Assert.assertEquals("Occupancy count file is wrong.", controler.getScenario().getConfig().ptCounts().getOccupancyCountsFileName(), inputDir + "counts/counts_occupancy.xml"); - Counts occupCounts = new Counts(); - new MatsimCountsReader(occupCounts).readFile(controler.getScenario().getConfig().ptCounts().getOccupancyCountsFileName()); - Count count = occupCounts.getCount(Id.create("stop1", Link.class)); // casting the id from a stop to a link, not nice.. - Assert.assertEquals("Occupancy counts description is wrong", occupCounts.getDescription(), "counts values for equil net"); - Assert.assertEquals("CsId is wrong.", count.getCsLabel() , "stop1"); - Assert.assertEquals("Volume of hour 4 is wrong", count.getVolume(7).getValue(), 4.0 , MatsimTestUtils.EPSILON); - Assert.assertEquals("Max count volume is wrong.", count.getMaxVolume().getValue(), 4.0 , MatsimTestUtils.EPSILON); - - // test resulting simulation volumes - { - String outCounts = outputDir + "ITERS/it." + lastIteration + "/" + lastIteration + ".simCountCompareOccupancy.txt"; - CountsReaderPt reader = new CountsReaderPt(outCounts); - double[] simValues; - double[] realValues; - - Id stopId1 = Id.create("stop1", TransitStopFacility.class); - simValues = reader.getSimulatedValues(stopId1); - realValues= reader.getRealValues(stopId1); - Assert.assertEquals("Volume of hour 6 is wrong", 4.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 is wrong", 4.0, realValues[6], MatsimTestUtils.EPSILON); - - Id stopId2 = Id.create("stop2", TransitStopFacility.class); - simValues = reader.getSimulatedValues(stopId2); - realValues= reader.getRealValues(stopId2); - Assert.assertEquals("Volume of hour 6 is wrong", 0.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 is wrong", 1.0, realValues[6] , MatsimTestUtils.EPSILON); - - Id stopId6 = Id.create("stop6", TransitStopFacility.class); - simValues = reader.getSimulatedValues(stopId6); - realValues= reader.getRealValues(stopId6); - Assert.assertEquals("Volume of hour 6 is wrong", 0.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 is wrong", 2.0, realValues[6], MatsimTestUtils.EPSILON); - - Id stopId10 = Id.create("stop10", TransitStopFacility.class); - simValues = reader.getSimulatedValues(stopId10); - realValues= reader.getRealValues(stopId10); - Assert.assertEquals("Volume of hour 6 is wrong", 4.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 is wrong", 5.0, realValues[6], MatsimTestUtils.EPSILON); - - // test calibration statistics - String testCalibStatPath = outputDir + "calibration-stats.txt"; - CalibrationStatReader calibrationStatReader = new CalibrationStatReader(); - new TabularFileParser().parse(testCalibStatPath, calibrationStatReader); - - CalibrationStatReader.StatisticsData outStatData= calibrationStatReader.getCalStatMap().get(lastIteration); - Assert.assertEquals("different Count_ll", "-0.046875", outStatData.getCount_ll() ); - Assert.assertEquals("different Count_ll_pred_err", "0.008670972399424905" , outStatData.getCount_ll_pred_err() ); - Assert.assertEquals("different Link_lambda_avg", "3.642292018550638E-4", outStatData.getLink_lambda_avg() ); - Assert.assertEquals("different Link_lambda_max", "0.032081715026130615" , outStatData.getLink_lambda_max() ); - Assert.assertEquals("different Link_lambda_min", "-0.008771046107406533", outStatData.getLink_lambda_min() ); - Assert.assertEquals("different Link_lambda_stddev", "0.0041495140513996154", outStatData.getLink_lambda_stddev()); - Assert.assertEquals("different P2p_ll", "--" , outStatData.getP2p_ll()); - Assert.assertEquals("different Plan_lambda_avg", "0.011655334459362041", outStatData.getPlan_lambda_avg() ); - Assert.assertEquals("different Plan_lambda_max", "0.032081715026130615" , outStatData.getPlan_lambda_max() ); - Assert.assertEquals("different Plan_lambda_min", "-0.008771046107406533" , outStatData.getPlan_lambda_min() ); - Assert.assertEquals("different Plan_lambda_stddev", "0.02183671935220152" , outStatData.getPlan_lambda_stddev()); - Assert.assertEquals("different Total_ll", "-0.046875", outStatData.getTotal_ll() ); - - //test link offsets - final TransitSchedule schedule = controler.getScenario().getTransitSchedule(); - String linkOffsetFile = outputDir + "ITERS/it." + lastIteration + "/" + lastIteration + ".linkCostOffsets.xml"; - // CadytsPtLinkCostOffsetsXMLFileIO offsetReader = new CadytsPtLinkCostOffsetsXMLFileIO (schedule); - CadytsCostOffsetsXMLFileIO offsetReader - = new CadytsCostOffsetsXMLFileIO (new TransitStopFacilityLookUp(controler.getScenario()), TransitStopFacility.class); - DynamicData stopOffsets = offsetReader.read(linkOffsetFile); - - TransitStopFacility stop2 = schedule.getFacilities().get(stopId2); - TransitStopFacility stop10 = schedule.getFacilities().get(stopId10); - - //find first offset value different from null to compare. Useful to test with different time bin sizes - int binIndex=-1; - boolean isZero; - do { - binIndex++; - isZero = (Math.abs(stopOffsets.getBinValue(stop2 , binIndex) - 0.0) < MatsimTestUtils.EPSILON); - }while (isZero && binIndex<86400); - - Assert.assertEquals("Wrong bin index for first link offset", 6, binIndex); - Assert.assertEquals("Wrong link offset of stop 10", 0.031842616249416734, stopOffsets.getBinValue(stop10 , binIndex), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong link offset of stop 2", -0.0079478186053482, stopOffsets.getBinValue(stop2 , binIndex), MatsimTestUtils.EPSILON); - } - } - - - /** - * @author mmoyo - */ - @Test - public final void testCalibrationTwo() throws IOException { - // yyyy I cannot fully certify that this test is doing something reasonable, since simCountComparisonOccupancy.txt and - // cadytsSimCountComparisonOccupancy.txt are returning different results. kai, feb'13 - // There is a comment in CadytsContext that the "cadyts" version may be wrong for time bins different from one hour. kai, dec'13 - - final double beta = 30. ; - final int lastIteration = 20 ; - - String inputDir = this.utils.getClassInputDirectory(); - String outputDir = this.utils.getOutputDirectory(); - - Config config = createTestConfig(inputDir, this.utils.getOutputDirectory()); - - config.controler().setLastIteration(lastIteration) ; - config.controler().setWritePlansInterval(1) ; - config.controler().setWriteEventsInterval(1) ; - - config.ptCounts().setPtCountsInterval(1) ; - - StrategySettings stratSets = new StrategySettings(); - stratSets.setStrategyName("ccc") ; - stratSets.setWeight(1.) ; - config.strategy().addStrategySettings(stratSets) ; - - CadytsConfigGroup cConfig = (CadytsConfigGroup) config.getModule(CadytsConfigGroup.GROUP_NAME) ; - cConfig.setTimeBinSize(7200) ; - - // --- - - final Controler controler = new Controler(config); - controler.addOverridingModule(new CadytsPtModule()); -// controler.setOverwriteFiles(true); - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - addPlanStrategyBinding("ccc").toProvider(new jakarta.inject.Provider() { - @Inject Scenario scenario; - @Inject CadytsPtContext context; - @Override - public PlanStrategy get() { - final CadytsPlanChanger planSelector = new CadytsPlanChanger(scenario, context); - planSelector.setCadytsWeight(beta * 30.); - return new PlanStrategyImpl(planSelector); - } - }); - } - }); - - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setWriteEventsInterval(0); - controler.getConfig().controler().setDumpDataAtEnd(true); - controler.run(); - - // ==================================== - - //scenario data test - Assert.assertNotNull("config is null" , controler.getConfig()); - Assert.assertEquals("Different number of links in network.", controler.getScenario().getNetwork().getLinks().size() , 23 ); - Assert.assertEquals("Different number of nodes in network.", controler.getScenario().getNetwork().getNodes().size() , 15 ); - Assert.assertNotNull("Transit schedule is null.", controler.getScenario().getTransitSchedule()); - Assert.assertEquals("Num. of trLines is wrong.", 2, controler.getScenario().getTransitSchedule().getTransitLines().size() ); - Assert.assertEquals("Num of facilities in schedule is wrong.", controler.getScenario().getTransitSchedule().getFacilities().size() , 5); - Assert.assertNotNull("Population is null.", controler.getScenario().getPopulation()); - Assert.assertEquals("Num. of persons in population is wrong.", controler.getScenario().getPopulation().getPersons().size() , 4); - Assert.assertEquals("Scale factor is wrong.", controler.getScenario().getConfig().ptCounts().getCountsScaleFactor(), 1.0, MatsimTestUtils.EPSILON); - // Assert.assertEquals("Distance filter is wrong.", controler.getTestScenarioURL().getConfig().ptCounts().getDistanceFilter() , 30000.0, MatsimTestUtils.EPSILON); - // Assert.assertEquals("DistanceFilterCenterNode is wrong.", controler.getTestScenarioURL().getConfig().ptCounts().getDistanceFilterCenterNode(), "7"); - //counts - Assert.assertEquals("Occupancy count file is wrong.", controler.getScenario().getConfig().ptCounts().getOccupancyCountsFileName(), inputDir + "counts/counts_occupancy.xml"); - Counts occupCounts = new Counts(); - new MatsimCountsReader(occupCounts).readFile(controler.getScenario().getConfig().ptCounts().getOccupancyCountsFileName()); - Count count = occupCounts.getCount(Id.create("stop1", Link.class)); - Assert.assertEquals("Occupancy counts description is wrong", occupCounts.getDescription(), "counts values for equil net"); - Assert.assertEquals("CsId is wrong.", count.getCsLabel() , "stop1"); - - Assert.assertEquals("Volume of hour 4 is wrong", count.getVolume(7).getValue(), 4.0 , MatsimTestUtils.EPSILON); - // yy I don't know why it says "hour 4" but "getVolume(7)". kai, sep'14 - - Assert.assertEquals("Max count volume is wrong.", count.getMaxVolume().getValue(), 4.0 , MatsimTestUtils.EPSILON); - - // test resulting simulation volumes - String outCounts = outputDir + "ITERS/it." + lastIteration + "/" + lastIteration + ".simCountCompareOccupancy.txt"; - CountsReaderPt reader = new CountsReaderPt(outCounts); - Id stopId1 = Id.create("stop1", TransitStopFacility.class); - { - double[] simValues = reader.getSimulatedValues(stopId1); - double[] realValues= reader.getRealValues(stopId1); - Assert.assertEquals("Volume of hour 6 (probably: 7) is wrong", 4.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 (probably: 7) is wrong", 4.0, realValues[6], MatsimTestUtils.EPSILON); - } - Id stopId2 = Id.create("stop2", TransitStopFacility.class); - { - double[] simValues = reader.getSimulatedValues(stopId2); - double[] realValues= reader.getRealValues(stopId2); - Assert.assertEquals("Volume of hour 6 (probably: 7) is wrong", 0.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 (probably: 7) is wrong", 1.0, realValues[6] , MatsimTestUtils.EPSILON); - } - Id stopId6 = Id.create("stop6", TransitStopFacility.class); - { - double[] simValues = reader.getSimulatedValues(stopId6); - double[] realValues= reader.getRealValues(stopId6); - Assert.assertEquals("Volume of hour 6 (probably: 7) is wrong", 0.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 (probably: 7) is wrong", 2.0, realValues[6], MatsimTestUtils.EPSILON); - } - Id stopId10 = Id.create("stop10", TransitStopFacility.class); - { - double[] simValues = reader.getSimulatedValues(stopId10); - double[] realValues= reader.getRealValues(stopId10); - Assert.assertEquals("Volume of hour 6 (probably: 7) is wrong", 4.0, simValues[6], MatsimTestUtils.EPSILON); - Assert.assertEquals("Volume of hour 6 (probably: 7) is wrong", 5.0, realValues[6], MatsimTestUtils.EPSILON); - } - // 2 bus lines, one using stops 1, 2, 12, the other using 1, 10, 12. Counts say: - // stop1: 4 (should always be satisfied) - // stop2: 1 (should be possible to satisfy bus see below) - // stop6: 2 (not possible to satisfy (no line going there)) - // stop10: 5 (not possible to satisfy (we have not enough plans) but see below) - // and they say this at h=7 (which may, or may not, be the entry "6" in the counts array, but then the error messages are wrong). - // - // stop2 and stop10 are pulling in different directions; would need 7 plans to satisfy but have only 4. Satisfying the higher - // volume station better is the cadyts-conforming solution. - - // test calibration statistics - String testCalibStatPath = outputDir + "calibration-stats.txt"; - CalibrationStatReader calibrationStatReader = new CalibrationStatReader(); - new TabularFileParser().parse(testCalibStatPath, calibrationStatReader); - - CalibrationStatReader.StatisticsData outStatData= calibrationStatReader.getCalStatMap().get(lastIteration); - // Assert.assertEquals("different Count_ll", "-0.01171875", outStatData.getCount_ll() ); - // Assert.assertEquals("different Count_ll_pred_err", "0.004590585907794875" , outStatData.getCount_ll_pred_err() ); - // Assert.assertEquals("different Link_lambda_avg", "-1.8081427328702926E-9", outStatData.getLink_lambda_avg() ); - // Assert.assertEquals("different Link_lambda_max", "0.0" , outStatData.getLink_lambda_max() ); - // Assert.assertEquals("different Link_lambda_min", "-1.4465142715757458E-8", outStatData.getLink_lambda_min() ); - // Assert.assertEquals("different Link_lambda_stddev", "4.501584893410135E-9" , outStatData.getLink_lambda_stddev()); - // Assert.assertEquals("different P2p_ll", "--" , outStatData.getP2p_ll()); - // Assert.assertEquals("different Plan_lambda_avg", "-2.5313998260184097E-8", outStatData.getPlan_lambda_avg() ); - // Assert.assertEquals("different Plan_lambda_max", "-2.5313998260184097E-8" , outStatData.getPlan_lambda_max() ); - // Assert.assertEquals("different Plan_lambda_min", "-2.5313998260184097E-8" , outStatData.getPlan_lambda_min() ); - // Assert.assertEquals("different Plan_lambda_stddev", "NaN" , outStatData.getPlan_lambda_stddev()); - // Assert.assertEquals("different Total_ll", "-0.01171875", outStatData.getTotal_ll() ); - // - // I think that the above quantities change when changing between FLOW_VEH_H and COUNT_VEH. The calibration result, though, - // seems the same. - - - //test link offsets - final TransitSchedule schedule = controler.getScenario().getTransitSchedule(); - CadytsCostOffsetsXMLFileIO offsetReader = - new CadytsCostOffsetsXMLFileIO (new TransitStopFacilityLookUp(controler.getScenario()), TransitStopFacility.class); - DynamicData stopOffsets = - offsetReader.read(outputDir + "ITERS/it." + lastIteration + "/" + lastIteration + ".linkCostOffsets.xml"); - - TransitStopFacility stop1 = schedule.getFacilities().get(stopId1); - TransitStopFacility stop2 = schedule.getFacilities().get(stopId2); - //TransitStopFacility stop6 = schedule.getFacilities().get(stopId6); - TransitStopFacility stop10 = schedule.getFacilities().get(stopId10); - - //find first offset value different from zero to compare. Useful to test with different time bin sizes - int binIndex=-1; - boolean isZero; - do { - binIndex++; - isZero = (Math.abs(stopOffsets.getBinValue(stop2 , binIndex) - 0.0) < MatsimTestUtils.EPSILON); - }while (isZero && binIndex<86400); - - Assert.assertEquals("Wrong Bin index for first link offset", 3, binIndex); // bin size = 3600; fix! //done manuel jul.2012 - Assert.assertEquals("Wrong link offset of stop 1", 0.0, stopOffsets.getBinValue(stop1 , binIndex), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Wrong link offset of stop 2", -0.0028383120802772956, stopOffsets.getBinValue(stop2 , binIndex), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Wrong link offset of stop 10", 0.00878939456017082, stopOffsets.getBinValue(stop10 , binIndex), MatsimTestUtils.EPSILON); - - Assert.assertTrue("Offset at stop 2 has wrong sign.", stopOffsets.getBinValue(stop2, binIndex) < 0. ) ; - Assert.assertTrue("Offset at stop 10 has wrong sign.", stopOffsets.getBinValue(stop10, binIndex) > 0. ) ; - } - - - private static Config createTestConfig(String inputDir, String outputDir) { - Config config = ConfigUtils.createConfig() ; - // --- - config.global().setRandomSeed(4711) ; - // --- - config.network().setInputFile(inputDir + "network.xml") ; - // --- - config.plans().setInputFile(inputDir + "4plans.xml") ; - config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); - // --- - config.transit().setUseTransit(true) ; - // --- - config.controler().setFirstIteration(1) ; - config.controler().setLastIteration(10) ; - config.controler().setOutputDirectory(outputDir) ; - config.controler().setWriteEventsInterval(1) ; - config.controler().setMobsim(MobsimType.qsim.toString()) ; - // --- - - config.qsim().setFlowCapFactor(0.02) ; - config.qsim().setStorageCapFactor(0.06) ; - config.qsim().setStuckTime(10.) ; - config.qsim().setRemoveStuckVehicles(false) ; // ?? - // --- - config.transit().setTransitScheduleFile(inputDir + "transitSchedule1bus.xml") ; - config.transit().setVehiclesFile(inputDir + "vehicles.xml") ; - Set modes = new HashSet() ; - modes.add("pt") ; - config.transit().setTransitModes(modes) ; - // --- - { - ActivityParams params = new ActivityParams("h") ; - config.planCalcScore().addActivityParams(params ) ; - params.setTypicalDuration(12*60*60.) ; - }{ - ActivityParams params = new ActivityParams("w") ; - config.planCalcScore().addActivityParams(params ) ; - params.setTypicalDuration(8*60*60.) ; - } - // --- -// ConfigGroup cadytsPtConfig = config.createModule(CadytsConfigGroup.GROUP_NAME ) ; - CadytsConfigGroup cadytsPtConfig = ConfigUtils.addOrGetModule( config, CadytsConfigGroup.class ); - -// cadytsPtConfig.addParam(CadytsConfigGroup.START_TIME, "04:00:00") ; - cadytsPtConfig.setStartTime( 4*3600 ); -// cadytsPtConfig.addParam(CadytsConfigGroup.END_TIME, "20:00:00" ) ; - cadytsPtConfig.setEndTime( 20*3600 ); - cadytsPtConfig.addParam(CadytsConfigGroup.REGRESSION_INERTIA, "0.95") ; - cadytsPtConfig.addParam(CadytsConfigGroup.USE_BRUTE_FORCE, "true") ; - cadytsPtConfig.addParam(CadytsConfigGroup.MIN_FLOW_STDDEV, "8") ; - cadytsPtConfig.addParam(CadytsConfigGroup.PREPARATORY_ITERATIONS, "1") ; - cadytsPtConfig.addParam(CadytsConfigGroup.TIME_BIN_SIZE, "3600") ; - cadytsPtConfig.addParam(CadytsConfigGroup.CALIBRATED_LINES, "M44,M43") ; - -// CadytsConfigGroup ccc = new CadytsConfigGroup() ; -// config.addModule(ccc) ; - - - // --- - config.ptCounts().setOccupancyCountsFileName(inputDir + "counts/counts_occupancy.xml") ; - config.ptCounts().setBoardCountsFileName(inputDir + "counts/counts_boarding.xml") ; - config.ptCounts().setAlightCountsFileName(inputDir + "counts/counts_alighting.xml") ; - // config.ptCounts().setDistanceFilter(30000.) ; // why? - // config.ptCounts().setDistanceFilterCenterNode("7") ; // why? - config.ptCounts().setOutputFormat("txt"); - config.ptCounts().setCountsScaleFactor(1.) ; - // --- - return config; - } - - private static class DummyMobsimFactory implements MobsimFactory { - @Override - public Mobsim createMobsim(final Scenario sc, final EventsManager eventsManager) { - return new Mobsim() { - @Override public void run() { } - } ; - } - } -} diff --git a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/pt/CountsReaderPt.java b/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/pt/CountsReaderPt.java deleted file mode 100644 index a312c472c48..00000000000 --- a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/pt/CountsReaderPt.java +++ /dev/null @@ -1,130 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * copyright : (C) 2012 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.contrib.cadyts.pt; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.util.Map; -import java.util.TreeMap; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.matsim.api.core.v01.Id; -import org.matsim.core.utils.misc.StringUtils; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -/** - * parses a output text file containing counts comparisons - * - * this class is only there in order to read the column-oriented output back in for testing. - * It should not be used elsewhere without further thinking. kai, sep'14 - * */ -final class CountsReaderPt { - - private final static Logger log = LogManager.getLogger(CountsReaderPt.class); - - final String STOP_ID_STRING_0 = "StopId :"; - final String HEAD_STRING_0 = "hour"; - final String ZERO = "0.0"; - - String countsTextFile; - Map, Map> count = new TreeMap<>(); - - CountsReaderPt(final String countsTextFile){ - this.countsTextFile = countsTextFile; - readValues(); - } - - private void readValues() { - try { - FileReader fileReader = new FileReader(this.countsTextFile); - // ->:correct this : reads first row - BufferedReader bufferedReader = new BufferedReader(fileReader); - String row = bufferedReader.readLine(); // TODO : include the first row inside the iteration - String[] values = StringUtils.explode(row, '\t'); - - Id id = Id.create(values[1], TransitStopFacility.class); - while (row != null) { - row = bufferedReader.readLine(); - if (row != null && row != "") { - values = StringUtils.explode(row, '\t'); - if (values[0].equals(this.STOP_ID_STRING_0)) { - id = Id.create(values[1], TransitStopFacility.class); - } else if (values[0].equals(this.HEAD_STRING_0)) { - // it does nothing, correct this condition - } else { - if (!this.count.containsKey(id)) { - this.count.put(id, new TreeMap()); - } - this.count.get(id).put(values[0], - new double[] { Double.parseDouble(values[1]), Double.parseDouble(values[2]), Double.parseDouble(values[3]) }); - } - } - } - bufferedReader.close(); - fileReader.close(); - } catch (Exception e) { - log.error(e); - } - } - - /** - * I am reasonably sure that the first entry (hour 1) is at array-position 0. kai, sep'14 - */ - double[]getSimulatedValues(final Id stopId) { - return this.getCountValues(stopId, 0); - } - - /** - * I am reasonably sure that the first entry (hour 1) is at array-position 0. kai, sep'14 - */ - double[]getSimulatedScaled(final Id stopId) { - return this.getCountValues(stopId, 1); - } - - /** - * I am reasonably sure that the first entry (hour 1) is at array-position 0. kai, sep'14 - */ - double[]getRealValues(final Id stopId) { - return this.getCountValues(stopId, 2); - } - - /** - * I am reasonably sure that the first entry (hour 1) is at array-position 0. kai, sep'14 - */ - double[]getCountValues(final Id stopId, final int col) { - double[] valueArray = new double[24]; - for (byte i= 0; i<24 ; i++) { - String hour = String.valueOf(i+1); - if (this.count.keySet().contains(stopId)) { - double[] value = this.count.get(stopId).get(hour); - if (value == null){ - valueArray[i] = 0.0; - } else { - valueArray[i] = value[col] ; //0 = simulated; 1= simulatedEscaled ; 2=realValues - } - } else { - valueArray = null; - } - } - return valueArray; - } - -} diff --git a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/utils/CalibrationStatReaderTest.java b/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/utils/CalibrationStatReaderTest.java index 5733a037c50..cf1c31b9126 100644 --- a/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/utils/CalibrationStatReaderTest.java +++ b/contribs/cadytsIntegration/src/test/java/org/matsim/contrib/cadyts/utils/CalibrationStatReaderTest.java @@ -20,12 +20,10 @@ package org.matsim.contrib.cadyts.utils; import java.io.IOException; -import java.net.URL; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; -import org.matsim.contrib.cadyts.pt.CadytsPtIT; import org.matsim.testcases.MatsimTestUtils; import cadyts.utilities.io.tabularFileParser.TabularFileParser; @@ -42,17 +40,17 @@ public void testReader() throws IOException { CalibrationStatReader calibrationStatReader = new CalibrationStatReader(); tabularFileParser.parse(calibStatFile, calibrationStatReader); CalibrationStatReader.StatisticsData statData6= calibrationStatReader.getCalStatMap().get(Integer.valueOf(6)); - Assert.assertEquals("differrent Count_ll", "-1.546875", statData6.getCount_ll() ); - Assert.assertEquals("differrent Count_ll_pred_err", "9.917082938182276E-8" , statData6.getCount_ll_pred_err() ); - Assert.assertEquals("differrent Link_lambda_avg", "0.0013507168476099964", statData6.getLink_lambda_avg() ); - Assert.assertEquals("differrent Link_lambda_max", "0.031434867572002166" , statData6.getLink_lambda_max() ); - Assert.assertEquals("differrent Link_lambda_min", "0.0", statData6.getLink_lambda_min() ); - Assert.assertEquals("differrent Link_lambda_stddev", "0.0058320747961925256" , statData6.getLink_lambda_stddev()); - Assert.assertEquals("differrent P2p_ll", "--" , statData6.getP2p_ll()); - Assert.assertEquals("differrent Plan_lambda_avg", "0.04322293912351989", statData6.getPlan_lambda_avg() ); - Assert.assertEquals("differrent Plan_lambda_max", "0.04715229919344063" , statData6.getPlan_lambda_max() ); - Assert.assertEquals("differrent Plan_lambda_min", "0.03929357905359915" , statData6.getPlan_lambda_min() ); - Assert.assertEquals("differrent Plan_lambda_stddev", "0.004200662608832472" , statData6.getPlan_lambda_stddev()); - Assert.assertEquals("differrent Total_ll", "-1.546875", statData6.getTotal_ll() ); + Assert.assertEquals("different Count_ll", "-1.546875", statData6.getCount_ll() ); + Assert.assertEquals("different Count_ll_pred_err", "9.917082938182276E-8" , statData6.getCount_ll_pred_err() ); + Assert.assertEquals("different Link_lambda_avg", "0.0013507168476099964", statData6.getLink_lambda_avg() ); + Assert.assertEquals("different Link_lambda_max", "0.031434867572002166" , statData6.getLink_lambda_max() ); + Assert.assertEquals("different Link_lambda_min", "0.0", statData6.getLink_lambda_min() ); + Assert.assertEquals("different Link_lambda_stddev", "0.0058320747961925256" , statData6.getLink_lambda_stddev()); + Assert.assertEquals("different P2p_ll", "--" , statData6.getP2p_ll()); + Assert.assertEquals("different Plan_lambda_avg", "0.04322293912351989", statData6.getPlan_lambda_avg() ); + Assert.assertEquals("different Plan_lambda_max", "0.04715229919344063" , statData6.getPlan_lambda_max() ); + Assert.assertEquals("different Plan_lambda_min", "0.03929357905359915" , statData6.getPlan_lambda_min() ); + Assert.assertEquals("different Plan_lambda_stddev", "0.004200662608832472" , statData6.getPlan_lambda_stddev()); + Assert.assertEquals("different Total_ll", "-1.546875", statData6.getTotal_ll() ); } } diff --git a/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/control/listeners/CarsharingListener.java b/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/control/listeners/CarsharingListener.java index 3409c505f63..42c2d594c05 100644 --- a/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/control/listeners/CarsharingListener.java +++ b/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/control/listeners/CarsharingListener.java @@ -69,7 +69,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { e.printStackTrace(); } - if (event.getIteration() == controler.getConfig().controler().getLastIteration()) { + if (event.getIteration() == controler.getConfig().controller().getLastIteration()) { final BufferedWriter outLinkStats = IOUtils .getBufferedWriter(this.controler.getControlerIO().getOutputFilename("CS.txt")); try { diff --git a/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/manager/demand/VehicleChoiceAgentImpl.java b/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/manager/demand/VehicleChoiceAgentImpl.java index 9906d235e08..455f57a72f4 100644 --- a/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/manager/demand/VehicleChoiceAgentImpl.java +++ b/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/manager/demand/VehicleChoiceAgentImpl.java @@ -2,7 +2,6 @@ import java.util.List; import java.util.Map; -import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -15,7 +14,7 @@ import org.matsim.contrib.carsharing.manager.supply.CarsharingSupplyInterface; import org.matsim.contrib.carsharing.manager.supply.costs.CostsCalculatorContainer; import org.matsim.contrib.carsharing.vehicles.CSVehicle; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.costcalculators.TravelDisutilityFactory; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.LeastCostPathCalculator.Path; @@ -72,7 +71,7 @@ public CSVehicle chooseVehicleActivityTimeIncluded(List vehicleOption CSVehicle chosenVehicle = null; double maxUtility = Integer.MIN_VALUE; - double marginalUtilityOfMoney = ((PlanCalcScoreConfigGroup) scenario.getConfig().getModule("planCalcScore")) + double marginalUtilityOfMoney = ((ScoringConfigGroup) scenario.getConfig().getModule("planCalcScore")) .getMarginalUtilityOfMoney(); for (CSVehicle vehicle : vehicleOptions) { Link vehicleLocation = this.carsharingSupply.getCompany(vehicle.getCompanyId()) diff --git a/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/scoring/CarsharingLegScoringFunction.java b/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/scoring/CarsharingLegScoringFunction.java index 4c41d77c15e..f30d27c9ad3 100644 --- a/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/scoring/CarsharingLegScoringFunction.java +++ b/contribs/carsharing/src/main/java/org/matsim/contrib/carsharing/scoring/CarsharingLegScoringFunction.java @@ -11,15 +11,15 @@ import org.matsim.contrib.carsharing.manager.supply.costs.CostsCalculatorContainer; import org.matsim.contrib.carsharing.vehicles.CSVehicle; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.scoring.functions.ScoringParameters; public class CarsharingLegScoringFunction extends org.matsim.core.scoring.functions.CharyparNagelLegScoring { - - private Config config; - + + private Config config; + private CostsCalculatorContainer costsCalculatorContainer; private DemandHandler demandHandler; private Person person; @@ -27,11 +27,11 @@ public class CarsharingLegScoringFunction extends org.matsim.core.scoring.functi /* private static final Set walkingLegs = ImmutableSet.of("egress_walk_ow", "access_walk_ow", "egress_walk_tw", "access_walk_tw", "egress_walk_ff", "access_walk_ff"); - + private static final Set carsharingLegs = ImmutableSet.of("oneway_vehicle", "twoway_vehicle", "freefloating_vehicle");*/ - - public CarsharingLegScoringFunction(ScoringParameters params, + + public CarsharingLegScoringFunction(ScoringParameters params, Config config, Network network, DemandHandler demandHandler, CostsCalculatorContainer costsCalculatorContainer, CarsharingSupplyInterface carsharingSupplyContainer, Person person) @@ -41,62 +41,62 @@ public CarsharingLegScoringFunction(ScoringParameters params, this.demandHandler = demandHandler; this.carsharingSupplyContainer = carsharingSupplyContainer; this.costsCalculatorContainer = costsCalculatorContainer; - this.person = person; + this.person = person; } @Override public void handleEvent(Event event) { - super.handleEvent(event); - } - + super.handleEvent(event); + } + @Override - public void finish() { - super.finish(); - + public void finish() { + super.finish(); + AgentRentals agentRentals = this.demandHandler.getAgentRentalsMap().get(person.getId()); if (agentRentals != null) { - double marginalUtilityOfMoney = ((PlanCalcScoreConfigGroup)this.config.getModule("planCalcScore")).getMarginalUtilityOfMoney(); + double marginalUtilityOfMoney = this.config.scoring().getMarginalUtilityOfMoney(); for(RentalInfo rentalInfo : agentRentals.getArr()) { CSVehicle vehicle = this.carsharingSupplyContainer.getAllVehicles().get(rentalInfo.getVehId().toString()); if (marginalUtilityOfMoney != 0.0) - score += -1 * this.costsCalculatorContainer.getCost(vehicle.getCompanyId(), + score += -1 * this.costsCalculatorContainer.getCost(vehicle.getCompanyId(), rentalInfo.getCarsharingType(), rentalInfo) * marginalUtilityOfMoney; - } - } - } - + } + } + } + @Override protected double calcLegScore(double departureTime, double arrivalTime, Leg leg) { - - + + double tmpScore = 0.0D; /*double travelTime = arrivalTime - departureTime; String mode = leg.getMode(); if (carsharingLegs.contains(mode)) { - - if (("oneway_vehicle").equals(mode)) { + + if (("oneway_vehicle").equals(mode)) { tmpScore += Double.parseDouble(this.config.getModule("OneWayCarsharing").getParams().get("constantOneWayCarsharing")); tmpScore += travelTime * Double.parseDouble(this.config.getModule("OneWayCarsharing").getParams().get("travelingOneWayCarsharing")) / 3600.0; - } - - else if (("freefloating_vehicle").equals(mode)) { - + } + + else if (("freefloating_vehicle").equals(mode)) { + tmpScore += Double.parseDouble(this.config.getModule("FreeFloating").getParams().get("constantFreeFloating")); tmpScore += travelTime * Double.parseDouble(this.config.getModule("FreeFloating").getParams().get("travelingFreeFloating")) / 3600.0; - } - - else if (("twoway_vehicle").equals(mode)) { - + } + + else if (("twoway_vehicle").equals(mode)) { + tmpScore += Double.parseDouble(this.config.getModule("TwoWayCarsharing").getParams().get("constantTwoWayCarsharing")); tmpScore += travelTime * Double.parseDouble(this.config.getModule("TwoWayCarsharing").getParams().get("travelingTwoWayCarsharing")) / 3600.0; } } - + else if (walkingLegs.contains(mode)) { - + tmpScore += getWalkScore(leg.getRoute().getDistance(), travelTime); - - }*/ + + }*/ return tmpScore; } diff --git a/contribs/carsharing/src/test/java/org/matsim/contrib/carsharing/runExample/RunCarsharingIT.java b/contribs/carsharing/src/test/java/org/matsim/contrib/carsharing/runExample/RunCarsharingIT.java index a73015e0dd5..9431005a492 100644 --- a/contribs/carsharing/src/test/java/org/matsim/contrib/carsharing/runExample/RunCarsharingIT.java +++ b/contribs/carsharing/src/test/java/org/matsim/contrib/carsharing/runExample/RunCarsharingIT.java @@ -19,8 +19,8 @@ package org.matsim.contrib.carsharing.runExample; -import static org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; -import static org.matsim.core.config.groups.PlansCalcRouteConfigGroup.TeleportedModeParams; +import static org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; +import static org.matsim.core.config.groups.RoutingConfigGroup.TeleportedModeParams; import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; @@ -66,8 +66,8 @@ public final void test() { new CarsharingConfigGroup(), new DvrpConfigGroup()); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); config.network().setInputFile("network.xml"); @@ -79,8 +79,8 @@ public final void test() { config.facilities().setInputFile("facilities.xml"); config.facilities().setFacilitiesSource(FacilitiesConfigGroup.FacilitiesSource.fromFile); - config.plansCalcRoute().setAccessEgressType(AccessEgressType.none); // otherwise does not work. kai,feb'16 - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setAccessEgressType(AccessEgressType.none); // otherwise does not work. kai,feb'16 + config.routing().setRoutingRandomness(0.); // config.plansCalcRoute().setInsertingAccessEgressWalk(AccessEgressType.directWalk); CarsharingConfigGroup csConfig = (CarsharingConfigGroup) config.getModule(CarsharingConfigGroup.GROUP_NAME); @@ -103,21 +103,21 @@ public final void test() { params.setTeleportedModeSpeed(0.83333333333); // params.setTeleportedModeSpeed( 2.0 ); params.setBeelineDistanceFactor(1.3); - config.plansCalcRoute().addModeRoutingParams(params); + config.routing().addModeRoutingParams(params); } { - config.plansCalcRoute().removeModeRoutingParams(TransportMode.walk); + config.routing().removeModeRoutingParams(TransportMode.walk); TeleportedModeParams params = new TeleportedModeParams(TransportMode.walk); params.setTeleportedModeSpeed(0.83333333333); // params.setTeleportedModeSpeed( 2.0 ); params.setBeelineDistanceFactor(1.3); - config.plansCalcRoute().addModeRoutingParams(params); + config.routing().addModeRoutingParams(params); } // --- Scenario scenario = ScenarioUtils.loadScenario(config); - config.plansCalcRoute().setAccessEgressType(AccessEgressType.accessEgressModeToLink); + config.routing().setAccessEgressType(AccessEgressType.accessEgressModeToLink); // --- diff --git a/contribs/carsharing/src/test/java/org/matsim/contrib/carsharing/runExample/RunCarsharingRelocationIT.java b/contribs/carsharing/src/test/java/org/matsim/contrib/carsharing/runExample/RunCarsharingRelocationIT.java deleted file mode 100644 index 64f0d96606b..00000000000 --- a/contribs/carsharing/src/test/java/org/matsim/contrib/carsharing/runExample/RunCarsharingRelocationIT.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.matsim.contrib.carsharing.runExample; - -public class RunCarsharingRelocationIT { - - - - - -} diff --git a/contribs/carsharing/test/input/org/matsim/contrib/carsharing/runExample/RunCarsharingIT/config.xml b/contribs/carsharing/test/input/org/matsim/contrib/carsharing/runExample/RunCarsharingIT/config.xml index 0be55d6d96c..adb6c05c1a0 100644 --- a/contribs/carsharing/test/input/org/matsim/contrib/carsharing/runExample/RunCarsharingIT/config.xml +++ b/contribs/carsharing/test/input/org/matsim/contrib/carsharing/runExample/RunCarsharingIT/config.xml @@ -23,8 +23,6 @@ - - @@ -45,11 +43,11 @@ - - + + - + @@ -254,7 +252,7 @@ - + diff --git a/contribs/commercialTrafficApplications/scenarios/grid/jointDemand_config.xml b/contribs/commercialTrafficApplications/scenarios/grid/jointDemand_config.xml index a90fd68807a..d7c91a56d08 100644 --- a/contribs/commercialTrafficApplications/scenarios/grid/jointDemand_config.xml +++ b/contribs/commercialTrafficApplications/scenarios/grid/jointDemand_config.xml @@ -1,15 +1,6 @@ - - - - - - - - - @@ -392,24 +383,6 @@ - - - - - - - - - - - - - - - - - - @@ -544,8 +517,6 @@ - - diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ChangeCommercialJobOperator.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ChangeCommercialJobOperator.java index 29c3c8662e9..f1862ee3842 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ChangeCommercialJobOperator.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ChangeCommercialJobOperator.java @@ -23,8 +23,8 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Activity; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.Carriers; import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.population.algorithms.PlanAlgorithm; diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialJobGenerator.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialJobGenerator.java index 024ab6e45e6..77b82e6208b 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialJobGenerator.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialJobGenerator.java @@ -21,7 +21,7 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Population; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.Carriers; import org.matsim.core.controler.listener.AfterMobsimListener; import org.matsim.core.controler.listener.BeforeMobsimListener; diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficAnalysisListener.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficAnalysisListener.java index fb67736cd99..d41196496c1 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficAnalysisListener.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficAnalysisListener.java @@ -25,8 +25,8 @@ import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.Carriers; import org.matsim.core.controler.MatsimServices; import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.controler.listener.IterationEndsListener; @@ -77,7 +77,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { writeIterationCarrierStats(event); writeJobStats(services.getControlerIO().getIterationFilename(event.getIteration(), "commercialJobStats.csv")); analyzeCarrierMarketShares(event.getIteration()); - + firstIteration = false; } diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficChecker.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficChecker.java index 88e68e04d36..8c561e9217c 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficChecker.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficChecker.java @@ -27,8 +27,8 @@ 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.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.Carriers; import java.util.Collection; import java.util.Map; diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/DefaultCommercialJobGenerator.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/DefaultCommercialJobGenerator.java index 657770b272b..3327f46292c 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/DefaultCommercialJobGenerator.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/DefaultCommercialJobGenerator.java @@ -36,20 +36,10 @@ import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.Route; import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierPlanWriter; -import org.matsim.contrib.freight.carrier.CarrierService; -import org.matsim.contrib.freight.carrier.CarrierUtils; -import org.matsim.contrib.freight.carrier.CarrierVehicle; -import org.matsim.contrib.freight.carrier.CarrierVehicleTypes; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.TimeWindow; -import org.matsim.contrib.freight.carrier.Tour; -import org.matsim.contrib.freight.jsprit.VRPTransportCostsFactory; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.jsprit.VRPTransportCostsFactory; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.events.AfterMobsimEvent; import org.matsim.core.controler.events.BeforeMobsimEvent; import org.matsim.core.population.PopulationUtils; @@ -127,7 +117,7 @@ private void buildVehicleAndDriver(Carrier carrier, Person driverPerson, Carrier if (!scenario.getVehicles().getVehicleTypes().containsKey(carrierVehicle.getType().getId())) scenario.getVehicles().addVehicleType(carrierVehicle.getType()); Id vid = Id.createVehicleId(driverPerson.getId()); - VehicleUtils.insertVehicleIdsIntoAttributes(driverPerson, Map.of(CarrierUtils.getCarrierMode(carrier), vid)); + VehicleUtils.insertVehicleIdsIntoAttributes(driverPerson, Map.of(CarriersUtils.getCarrierMode(carrier), vid)); scenario.getVehicles() .addVehicle(scenario.getVehicles().getFactory().createVehicle(vid, carrierVehicle.getType())); freightVehicles.add(vid); @@ -211,7 +201,7 @@ private void manageJspritDepartureTimes(Plan plan) { */ private Plan createPlainPlanFromTour(Carrier carrier, ScheduledTour scheduledTour) { - String carrierMode = CarrierUtils.getCarrierMode(carrier); + String carrierMode = CarriersUtils.getCarrierMode(carrier); // Create empty plan Plan plan = PopulationUtils.createPlan(); @@ -223,7 +213,7 @@ private Plan createPlainPlanFromTour(Carrier carrier, ScheduledTour scheduledTou plan.addActivity(startActivity); for (Tour.TourElement tourElement : scheduledTour.getTour().getTourElements()) { - if (tourElement instanceof org.matsim.contrib.freight.carrier.Tour.Leg) { + if (tourElement instanceof Tour.Leg) { // Take information from scheduled leg and create a defaultLeg Tour.Leg tourLeg = (Tour.Leg) tourElement; @@ -301,7 +291,7 @@ public void notifyBeforeMobsim(BeforeMobsimEvent event) { createAndAddFreightAgents(this.carriers, this.scenario.getPopulation()); event.getServices().getInjector().getInstance(ScoreCommercialJobs.class).prepareTourArrivalsForDay(); - String dir = event.getServices().getConfig().controler().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/"; + String dir = event.getServices().getConfig().controller().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/"; log.info("writing carrier file of iteration " + event.getIteration() + " to " + dir); CarrierPlanWriter planWriter = new CarrierPlanWriter(carriers); planWriter.write(dir + "carriers_it" + event.getIteration() + ".xml"); @@ -415,7 +405,7 @@ private void toggleChangeCommercialJobOperatorStrategy(int currentIteration) { log.info("Toggle " + ChangeCommercialJobOperator.SELECTOR_NAME); } - Collection allStrategies = this.scenario.getConfig().strategy().getStrategySettings(); + Collection allStrategies = this.scenario.getConfig().replanning().getStrategySettings(); for (StrategySettings strategy : allStrategies) { if (strategy.getStrategyName().equals(ChangeCommercialJobOperator.SELECTOR_NAME)) { diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/JointDemandModule.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/JointDemandModule.java index 5860e8a5cd9..a4f182cf17a 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/JointDemandModule.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/JointDemandModule.java @@ -27,10 +27,10 @@ import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; import org.matsim.contrib.drt.run.MultiModeDrtModule; import org.matsim.contrib.dvrp.run.DvrpModule; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCostsFactory; -import org.matsim.contrib.freight.jsprit.VRPTransportCostsFactory; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCostsFactory; +import org.matsim.freight.carriers.jsprit.VRPTransportCostsFactory; import org.matsim.core.config.Config; import org.matsim.core.controler.AbstractModule; import org.matsim.core.replanning.PlanStrategy; @@ -92,7 +92,7 @@ private CarrierProvider() { } public Carriers get() { - return FreightUtils.getCarriers(this.scenario); + return CarriersUtils.getCarriers(this.scenario); } } diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/JointDemandUtils.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/JointDemandUtils.java index 5089e8b9e87..e433a3651e6 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/JointDemandUtils.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/JointDemandUtils.java @@ -22,9 +22,9 @@ import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierVehicle; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierVehicle; +import org.matsim.freight.carriers.Carriers; import javax.annotation.Nullable; import java.util.*; diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/RunJointDemandCarToggleJspritExample.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/RunJointDemandCarToggleJspritExample.java index 9a0df38130b..905102b912c 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/RunJointDemandCarToggleJspritExample.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/RunJointDemandCarToggleJspritExample.java @@ -22,12 +22,12 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.CarriersUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule; @@ -70,17 +70,17 @@ public void run(URL configUrl){ jointDemandConfigGroup.setFirstLegTraveltimeBufferFactor(1.5); jointDemandConfigGroup.setChangeCommercialJobOperatorInterval(2); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setTravelTimeSliceWidth(3600); - freightConfigGroup.setCarriersFile("jointDemand_carriers_car.xml"); - freightConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setTravelTimeSliceWidth(3600); + freightCarriersConfigGroup.setCarriersFile("jointDemand_carriers_car.xml"); + freightCarriersConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); prepareConfig(config); Scenario scenario = loadScenario(config); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); //assumes that input file paths are set in FreightConfigGroup + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); //assumes that input file paths are set in FreightCarriersConfigGroup //alternatively, one can read in the input Carriers and CarrierVehicleTypes manually and use - //FreightUtils.getCarriers(scenario) and FreightUtils.getCarrierVehicleTypes(scenario) + //CarrierControlerUtils.getCarriers(scenario) and CarrierControlerUtils.getCarrierVehicleTypes(scenario) Controler controler = new Controler(scenario); controler.addOverridingModule(new JointDemandModule() ); @@ -88,28 +88,28 @@ public void run(URL configUrl){ } private static void prepareConfig(Config config) { - StrategyConfigGroup.StrategySettings changeExpBeta = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings changeExpBeta = new ReplanningConfigGroup.StrategySettings(); changeExpBeta.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta); changeExpBeta.setWeight(0.5); - config.strategy().addStrategySettings(changeExpBeta); + config.replanning().addStrategySettings(changeExpBeta); - StrategyConfigGroup.StrategySettings changeJobOperator = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings changeJobOperator = new ReplanningConfigGroup.StrategySettings(); changeJobOperator.setStrategyName(ChangeCommercialJobOperator.SELECTOR_NAME); changeJobOperator.setWeight(0.5); - config.strategy().addStrategySettings(changeJobOperator); + config.replanning().addStrategySettings(changeJobOperator); - config.strategy().setFractionOfIterationsToDisableInnovation(.8); - PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + config.replanning().setFractionOfIterationsToDisableInnovation(.8); + ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setTypicalDuration(14 * 3600); - config.planCalcScore().addActivityParams(home); - PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + config.scoring().addActivityParams(home); + ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setTypicalDuration(14 * 3600); work.setOpeningTime(8 * 3600); work.setClosingTime(8 * 3600); - config.planCalcScore().addActivityParams(work); - config.controler().setWriteEventsInterval(5); - config.controler().setOutputDirectory("output/commercialTrafficApplications/jointDemand/RunJointDemandCarToggleJspritExample"); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(5); + config.scoring().addActivityParams(work); + config.controller().setWriteEventsInterval(5); + config.controller().setOutputDirectory("output/commercialTrafficApplications/jointDemand/RunJointDemandCarToggleJspritExample"); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(5); } } diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ScoreCommercialJobs.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ScoreCommercialJobs.java index 7cdab223e4b..c3a6a068701 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ScoreCommercialJobs.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ScoreCommercialJobs.java @@ -30,10 +30,10 @@ import org.matsim.api.core.v01.events.handler.ActivityStartEventHandler; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.*; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierService; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.carrier.CarrierConstants; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierService; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.CarrierConstants; import org.matsim.core.api.experimental.events.EventsManager; import java.util.*; diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TourLengthAnalyzer.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TourLengthAnalyzer.java index 5ea36ca6528..c1434c351b9 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TourLengthAnalyzer.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TourLengthAnalyzer.java @@ -33,7 +33,7 @@ import org.matsim.api.core.v01.events.handler.PersonLeavesVehicleEventHandler; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.CarrierConstants; +import org.matsim.freight.carriers.CarrierConstants; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.vehicles.Vehicle; diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TourPlanning.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TourPlanning.java index 1a3fd7e9713..2c1e9d82e2e 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TourPlanning.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TourPlanning.java @@ -31,14 +31,15 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierPlan; -import org.matsim.contrib.freight.carrier.CarrierUtils; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.jsprit.MatsimJspritFactory; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts; -import org.matsim.contrib.freight.jsprit.VRPTransportCosts; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierPlan; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.freight.carriers.jsprit.VRPTransportCosts; import org.matsim.core.router.util.TravelTime; +import org.matsim.freight.carriers.jsprit.NetworkRouter; import org.matsim.vehicles.VehicleType; import java.util.ArrayList; @@ -91,8 +92,8 @@ static void runTourPlanningForCarriers(Carriers carriers, Scenario scenario, VRP HashMap, Integer> sortedMap = carrierServiceCounterMap.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new)); - - + + ArrayList> tempList = new ArrayList<>(sortedMap.keySet()); ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors()); forkJoinPool.submit(() -> tempList.parallelStream().forEach(carrierId -> { @@ -152,7 +153,7 @@ static void runTourPlanningForCarriers(Carriers carriers, Scenario scenario, VRP log.info("setting maxIterations=1 as carrier has no services"); algorithm.setMaxIterations(1); } else { - algorithm.setMaxIterations(CarrierUtils.getJspritIterations(carrier)); + algorithm.setMaxIterations(CarriersUtils.getJspritIterations(carrier)); } // variationCoefficient = stdDeviation/mean. so i set the threshold rather soft @@ -167,7 +168,7 @@ static void runTourPlanningForCarriers(Carriers carriers, Scenario scenario, VRP CarrierPlan carrierPlan = MatsimJspritFactory.createPlan(carrier, bestSolution); log.info("routing plan for carrier " + carrier.getId()); - org.matsim.contrib.freight.jsprit.NetworkRouter.routePlan(carrierPlan, transportCosts); // we need to route + NetworkRouter.routePlan(carrierPlan, transportCosts); // we need to route // the plans in // order to create // reasonable diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/examples/RunJointDemandCarExample.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/examples/RunJointDemandCarExample.java index 5a3386fba32..62c6584a1de 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/examples/RunJointDemandCarExample.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/examples/RunJointDemandCarExample.java @@ -25,12 +25,12 @@ import org.matsim.contrib.commercialTrafficApplications.jointDemand.ChangeCommercialJobOperator; import org.matsim.contrib.commercialTrafficApplications.jointDemand.JointDemandConfigGroup; import org.matsim.contrib.commercialTrafficApplications.jointDemand.JointDemandModule; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.CarriersUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule; @@ -72,17 +72,17 @@ public void run(URL configUrl){ JointDemandConfigGroup jointDemandConfigGroup = ConfigUtils.addOrGetModule(config, JointDemandConfigGroup.class); jointDemandConfigGroup.setFirstLegTraveltimeBufferFactor(1.5); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setTravelTimeSliceWidth(3600); - freightConfigGroup.setCarriersFile("jointDemand_carriers_car.xml"); - freightConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setTravelTimeSliceWidth(3600); + freightCarriersConfigGroup.setCarriersFile("jointDemand_carriers_car.xml"); + freightCarriersConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); prepareConfig(config); Scenario scenario = loadScenario(config); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); //assumes that input file paths are set in FreightConfigGroup + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); //assumes that input file paths are set in FreightCarriersConfigGroup //alternatively, one can read in the input Carriers and CarrierVehicleTypes manually and use - //FreightUtils.getCarriers(scenario) and FreightUtils.getCarrierVehicleTypes(scenario) + //CarrierControlerUtils.getCarriers(scenario) and CarrierControlerUtils.getCarrierVehicleTypes(scenario) Controler controler = new Controler(scenario); controler.addOverridingModule(new JointDemandModule() ); @@ -90,28 +90,28 @@ public void run(URL configUrl){ } private static void prepareConfig(Config config) { - StrategyConfigGroup.StrategySettings changeExpBeta = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings changeExpBeta = new ReplanningConfigGroup.StrategySettings(); changeExpBeta.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta); changeExpBeta.setWeight(0.5); - config.strategy().addStrategySettings(changeExpBeta); + config.replanning().addStrategySettings(changeExpBeta); - StrategyConfigGroup.StrategySettings changeJobOperator = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings changeJobOperator = new ReplanningConfigGroup.StrategySettings(); changeJobOperator.setStrategyName(ChangeCommercialJobOperator.SELECTOR_NAME); changeJobOperator.setWeight(0.5); - config.strategy().addStrategySettings(changeJobOperator); + config.replanning().addStrategySettings(changeJobOperator); - config.strategy().setFractionOfIterationsToDisableInnovation(.8); - PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + config.replanning().setFractionOfIterationsToDisableInnovation(.8); + ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setTypicalDuration(14 * 3600); - config.planCalcScore().addActivityParams(home); - PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + config.scoring().addActivityParams(home); + ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setTypicalDuration(14 * 3600); work.setOpeningTime(8 * 3600); work.setClosingTime(8 * 3600); - config.planCalcScore().addActivityParams(work); - config.controler().setWriteEventsInterval(5); - config.controler().setOutputDirectory("output/commercialTrafficApplications/jointDemand/RunJointDemandCarExample"); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(5); + config.scoring().addActivityParams(work); + config.controller().setWriteEventsInterval(5); + config.controller().setOutputDirectory("output/commercialTrafficApplications/jointDemand/RunJointDemandCarExample"); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(5); } } diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/examples/RunJointDemandDRTExample.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/examples/RunJointDemandDRTExample.java index ee0983bd2df..68addb0a68a 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/examples/RunJointDemandDRTExample.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/examples/RunJointDemandDRTExample.java @@ -36,13 +36,13 @@ import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; import org.matsim.contrib.dvrp.run.DvrpConfigGroup; import org.matsim.contrib.dvrp.run.DvrpQSimComponents; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.CarriersUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule; @@ -80,14 +80,14 @@ public static void main(String[] args) throws IOException { public void run(URL configURL){ Config config = loadConfig(configURL); prepareConfig(config); - DrtConfigs.adjustMultiModeDrtConfig(MultiModeDrtConfigGroup.get(config), config.planCalcScore(), - config.plansCalcRoute()); + DrtConfigs.adjustMultiModeDrtConfig(MultiModeDrtConfigGroup.get(config), config.scoring(), + config.routing()); Scenario scenario = DrtControlerCreator.createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); //assumes that input file paths are set in FreightConfigGroup + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); //assumes that input file paths are set in FreightCarriersConfigGroup //alternatively, one can read in the input Carriers and CarrierVehicleTypes manually and use - //FreightUtils.getCarriers(scenario) and FreightUtils.getCarrierVehicleTypes(scenario) + //CarrierControlerUtils.getCarriers(scenario) and CarrierControlerUtils.getCarrierVehicleTypes(scenario) Controler controler = new Controler(scenario); controler.addOverridingModule(new JointDemandModule()); @@ -102,33 +102,33 @@ private static void prepareConfig(Config config) { config.qsim().setSimStarttimeInterpretation(QSimConfigGroup.StarttimeInterpretation.onlyUseStarttime); - StrategyConfigGroup.StrategySettings changeExpBeta = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings changeExpBeta = new ReplanningConfigGroup.StrategySettings(); changeExpBeta.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta); changeExpBeta.setWeight(0.5); - config.strategy().addStrategySettings(changeExpBeta); - StrategyConfigGroup.StrategySettings changeServiceOperator = new StrategyConfigGroup.StrategySettings(); + config.replanning().addStrategySettings(changeExpBeta); + ReplanningConfigGroup.StrategySettings changeServiceOperator = new ReplanningConfigGroup.StrategySettings(); changeServiceOperator.setStrategyName(ChangeCommercialJobOperator.SELECTOR_NAME); changeServiceOperator.setWeight(0.5); - config.strategy().addStrategySettings(changeServiceOperator); + config.replanning().addStrategySettings(changeServiceOperator); - config.strategy().setFractionOfIterationsToDisableInnovation(.8); - PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + config.replanning().setFractionOfIterationsToDisableInnovation(.8); + ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setTypicalDuration(14 * 3600); - config.planCalcScore().addActivityParams(home); - PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + config.scoring().addActivityParams(home); + ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setTypicalDuration(14 * 3600); work.setOpeningTime(8 * 3600); work.setClosingTime(8 * 3600); - config.planCalcScore().addActivityParams(work); - config.controler().setWriteEventsInterval(1); - config.controler().setOutputDirectory("output/commercialTrafficApplications/jointDemand/RunJointDemandUsingDRTExample"); - config.controler() + config.scoring().addActivityParams(work); + config.controller().setWriteEventsInterval(1); + config.controller().setOutputDirectory("output/commercialTrafficApplications/jointDemand/RunJointDemandUsingDRTExample"); + config.controller() .setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); config.qsim().setEndTime(26 * 3600); config.qsim().setSimEndtimeInterpretation(QSimConfigGroup.EndtimeInterpretation.onlyUseEndtime); - config.controler().setLastIteration(5); + config.controller().setLastIteration(5); } private static void loadConfigGroups(Config config) { @@ -147,8 +147,8 @@ private static void loadConfigGroups(Config config) { JointDemandConfigGroup jointDemandConfigGroup = ConfigUtils.addOrGetModule(config, JointDemandConfigGroup.class); jointDemandConfigGroup.setFirstLegTraveltimeBufferFactor(1.5); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setCarriersFile("jointDemand_carriers_drt.xml"); - freightConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setCarriersFile("jointDemand_carriers_drt.xml"); + freightCarriersConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); } } diff --git a/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ChangeCommercialJobOperatorTest.java b/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ChangeCommercialJobOperatorTest.java index a66096756ac..18de26d446d 100644 --- a/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ChangeCommercialJobOperatorTest.java +++ b/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/ChangeCommercialJobOperatorTest.java @@ -7,11 +7,8 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Plan; -import org.matsim.contrib.commercialTrafficApplications.jointDemand.ChangeCommercialJobOperator; -import org.matsim.contrib.commercialTrafficApplications.jointDemand.JointDemandUtils; -import org.matsim.contrib.commercialTrafficApplications.jointDemand.TestScenarioGeneration; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.Carriers; import org.matsim.core.router.util.TravelTime; import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; @@ -49,4 +46,4 @@ public void getPlanAlgoInstance() { } -} \ No newline at end of file +} diff --git a/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficIntegrationTest.java b/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficIntegrationTest.java index 2ea7d0a9853..27b59b0d621 100644 --- a/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficIntegrationTest.java +++ b/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/CommercialTrafficIntegrationTest.java @@ -2,8 +2,8 @@ import org.junit.Test; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.CarriersUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.Controler; @@ -15,13 +15,13 @@ public class CommercialTrafficIntegrationTest { @Test public void runCommercialTrafficIT() { Config config = ConfigUtils.loadConfig("./scenarios/grid/jointDemand_config.xml"); - config.controler().setLastIteration(5); + config.controller().setLastIteration(5); ConfigUtils.addOrGetModule(config, JointDemandConfigGroup.class); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setCarriersFile("jointDemand_carriers_car.xml"); - freightConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setCarriersFile("jointDemand_carriers_car.xml"); + freightCarriersConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); Scenario scenario = ScenarioUtils.loadScenario(config); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); Controler controler = new Controler(scenario); controler.addOverridingModule(new JointDemandModule()); controler.run(); diff --git a/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/IsTheRightCustomerScoredTest.java b/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/IsTheRightCustomerScoredTest.java index 3b250c4f855..b9f40a81c5d 100644 --- a/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/IsTheRightCustomerScoredTest.java +++ b/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/IsTheRightCustomerScoredTest.java @@ -27,9 +27,7 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PopulationFactory; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.*; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.Controler; @@ -47,18 +45,18 @@ public class IsTheRightCustomerScoredTest { public void setUp() { Config config = ConfigUtils.loadConfig("./scenarios/grid/jointDemand_config.xml"); - config.controler().setLastIteration(0); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setLastIteration(0); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); JointDemandConfigGroup jointDemandConfigGroup = ConfigUtils.addOrGetModule(config, JointDemandConfigGroup.class); jointDemandConfigGroup.setMaxJobScore(MAX_JOB_SCORE); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setCarriersFile("jointDemand_carriers_car.xml"); - freightConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setCarriersFile("jointDemand_carriers_car.xml"); + freightCarriersConfigGroup.setCarriersVehicleTypesFile("jointDemand_vehicleTypes.xml"); scenario = ScenarioUtils.loadScenario(config); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); //limit the fleet size of carrier pizza_1 so that it can handly only one order/job - FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("salamiPizza", Carrier.class)).getCarrierCapabilities().setFleetSize(CarrierCapabilities.FleetSize.FINITE); + CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("salamiPizza", Carrier.class)).getCarrierCapabilities().setFleetSize(CarrierCapabilities.FleetSize.FINITE); preparePopulation(scenario); @@ -107,7 +105,7 @@ public void testIfTheRightPersonIsScoredForReceivingAJob() { Plan nonCustomerPlan = scenario.getPopulation().getPersons().get(Id.createPersonId("nonCustomer")).getSelectedPlan(); //derive the service activity from the carrier plan and compare the service id (which should contain the customer id) with the person id of the expected customer - Carrier pizzaCarrier = FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("salamiPizza", Carrier.class)); + Carrier pizzaCarrier = CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("salamiPizza", Carrier.class)); ScheduledTour tour = (ScheduledTour) pizzaCarrier.getSelectedPlan().getScheduledTours().toArray()[0]; Id serviceActivity = tour.getTour().getTourElements().stream() .filter(tourElement -> tourElement instanceof Tour.ServiceActivity) diff --git a/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TestScenarioGeneration.java b/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TestScenarioGeneration.java index 629c1bbd6c6..1d6b845a665 100644 --- a/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TestScenarioGeneration.java +++ b/contribs/commercialTrafficApplications/src/test/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/TestScenarioGeneration.java @@ -26,9 +26,9 @@ import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.contrib.freight.carrier.*; import org.matsim.core.config.Config; import org.matsim.core.population.PopulationUtils; +import org.matsim.freight.carriers.*; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; @@ -54,18 +54,18 @@ public static Carriers generateCarriers() { Carriers carriers = new Carriers(); Carrier italianPizzaPlace = CarrierImpl.newInstance(Id.create("pizza_italian", Carrier.class)); - CarrierUtils.setCarrierMode(italianPizzaPlace, TransportMode.car); - CarrierUtils.setJspritIterations(italianPizzaPlace, 20); + CarriersUtils.setCarrierMode(italianPizzaPlace, TransportMode.car); + CarriersUtils.setJspritIterations(italianPizzaPlace, 20); italianPizzaPlace.getAttributes().putAttribute(JointDemandUtils.CARRIER_MARKET_ATTRIBUTE_NAME, "pizza"); Carrier americanPizzaPlace = CarrierImpl.newInstance(Id.create("pizza_american", Carrier.class)); - CarrierUtils.setCarrierMode(americanPizzaPlace, TransportMode.car); - CarrierUtils.setJspritIterations(americanPizzaPlace, 20); + CarriersUtils.setCarrierMode(americanPizzaPlace, TransportMode.car); + CarriersUtils.setJspritIterations(americanPizzaPlace, 20); americanPizzaPlace.getAttributes().putAttribute(JointDemandUtils.CARRIER_MARKET_ATTRIBUTE_NAME, "pizza"); Carrier shopping_1 = CarrierImpl.newInstance(Id.create("shopping_1", Carrier.class)); - CarrierUtils.setCarrierMode(shopping_1, TransportMode.car); - CarrierUtils.setJspritIterations(shopping_1, 20); + CarriersUtils.setCarrierMode(shopping_1, TransportMode.car); + CarriersUtils.setJspritIterations(shopping_1, 20); shopping_1.getAttributes().putAttribute(JointDemandUtils.CARRIER_MARKET_ATTRIBUTE_NAME, "shopping"); VehicleType type = createLightType(); diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/csv/CompactCSVWriter.java b/contribs/common/src/main/java/org/matsim/contrib/common/csv/CompactCSVWriter.java index c51911f531a..35d7ec5f660 100644 --- a/contribs/common/src/main/java/org/matsim/contrib/common/csv/CompactCSVWriter.java +++ b/contribs/common/src/main/java/org/matsim/contrib/common/csv/CompactCSVWriter.java @@ -21,10 +21,9 @@ package org.matsim.contrib.common.csv; import java.io.IOException; +import java.io.UncheckedIOException; import java.io.Writer; -import org.matsim.core.utils.io.UncheckedIOException; - import com.opencsv.CSVWriter; public class CompactCSVWriter extends CSVWriter { diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/randomizedtransitrouter/RandomizingTransitRouterFactory.java b/contribs/common/src/main/java/org/matsim/contrib/common/randomizedtransitrouter/RandomizingTransitRouterFactory.java deleted file mode 100644 index 7fba53c4198..00000000000 --- a/contribs/common/src/main/java/org/matsim/contrib/common/randomizedtransitrouter/RandomizingTransitRouterFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.matsim.contrib.common.randomizedtransitrouter;/* *********************************************************************** * - * project: org.matsim.* - * RandomizedTransitRouterFacotry - * * - * *********************************************************************** * - * * - * copyright : (C) 2013 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 * - * * - * *********************************************************************** */ - -import org.matsim.core.config.Config; -import org.matsim.pt.router.*; -import org.matsim.pt.transitSchedule.api.TransitSchedule; - -import jakarta.inject.Inject; -import jakarta.inject.Provider; - - -/** - * @author dgrether - * - */ -public class RandomizingTransitRouterFactory implements Provider { - - private TransitRouterConfig trConfig; - private TransitSchedule schedule; - private TransitRouterNetwork routerNetwork; - - @Inject - RandomizingTransitRouterFactory(Config config, TransitSchedule schedule) { - this.trConfig = new TransitRouterConfig(config); - this.schedule = schedule; - this.routerNetwork = TransitRouterNetwork.createFromSchedule(schedule, trConfig.getBeelineWalkConnectionDistance()); - } - - @Override - public TransitRouter get() { - RandomizingTransitRouterTravelTimeAndDisutility ttCalculator = new RandomizingTransitRouterTravelTimeAndDisutility(trConfig); - ttCalculator.setDataCollection(RandomizingTransitRouterTravelTimeAndDisutility.DataCollection.randomizedParameters, true) ; - ttCalculator.setDataCollection(RandomizingTransitRouterTravelTimeAndDisutility.DataCollection.additionalInformation, false) ; - return new TransitRouterImpl(trConfig, new PreparedTransitSchedule(schedule), routerNetwork, ttCalculator, ttCalculator); - } - -} diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/randomizedtransitrouter/RandomizingTransitRouterModule.java b/contribs/common/src/main/java/org/matsim/contrib/common/randomizedtransitrouter/RandomizingTransitRouterModule.java deleted file mode 100644 index 1dc0dec0300..00000000000 --- a/contribs/common/src/main/java/org/matsim/contrib/common/randomizedtransitrouter/RandomizingTransitRouterModule.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.matsim.contrib.common.randomizedtransitrouter;/* - * *********************************************************************** * - * * project: org.matsim.* - * * RandomizedTransitRouterModule.java - * * * - * * *********************************************************************** * - * * * - * * copyright : (C) 2015 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 * - * * * - * * *********************************************************************** - */ - -import org.matsim.core.controler.AbstractModule; -import org.matsim.pt.router.TransitRouter; - -public class RandomizingTransitRouterModule extends AbstractModule { - @Override - public void install() { - bind(TransitRouter.class).toProvider(RandomizingTransitRouterFactory.class); - } -} diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/randomizedtransitrouter/RandomizingTransitRouterTravelTimeAndDisutility.java b/contribs/common/src/main/java/org/matsim/contrib/common/randomizedtransitrouter/RandomizingTransitRouterTravelTimeAndDisutility.java deleted file mode 100644 index d75e386838e..00000000000 --- a/contribs/common/src/main/java/org/matsim/contrib/common/randomizedtransitrouter/RandomizingTransitRouterTravelTimeAndDisutility.java +++ /dev/null @@ -1,207 +0,0 @@ -package org.matsim.contrib.common.randomizedtransitrouter;/* *********************************************************************** * - * project: org.matsim.* - * RandomizedTransitRouterNetworkTravelTimeAndDisutility2 - * * - * *********************************************************************** * - * * - * copyright : (C) 2012 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 * - * * - * *********************************************************************** */ - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.matsim.api.core.v01.Coord; -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.gbl.MatsimRandom; -import org.matsim.pt.router.CustomDataManager; -import org.matsim.pt.router.TransitRouterConfig; -import org.matsim.pt.router.TransitRouterNetwork.TransitRouterNetworkLink; -import org.matsim.pt.router.TransitRouterNetworkTravelTimeAndDisutility; -import org.matsim.vehicles.Vehicle; - -import java.util.HashMap; -import java.util.Map; - - -/** - * When plugged into the transit router, will switch to a different, randomly generated combination of - * marginal utilities every time it is called for a new agent. - *

- * Comments:
    - *
  • In the literature, they seem to use log-normal distributions for the tastes. (Makes sense - * since it addresse the symmetry problem which I am addressing ad-hoc.) [M. K. Anderson, hEART'13] - * kai, sep'13 - *
  • People seem to use "gamma distributions for the error term" ("double stochastic assignment"). - * Not sure what that does, if we need it, etc. [M. K. Anderson, hEART'13] kai, sep'13 - *
- * @author kai - * @author dgrether - * - */ -public class RandomizingTransitRouterTravelTimeAndDisutility extends TransitRouterNetworkTravelTimeAndDisutility { - - public enum DataCollection {randomizedParameters, additionalInformation} - private Id cachedPersonId = null ; - private final TransitRouterConfig originalTransitRouterConfig ; - - private double localMarginalUtilityOfTravelTimeWalk_utl_s = Double.NaN ; - private double localMarginalUtilityOfWaitingPt_utl_s = Double.NaN ; - private double localUtilityOfLineSwitch_utl = Double.NaN ; - private double localMarginalUtilityOfTravelTimePt_utl_s = Double.NaN ; - private double localMarginalUtilityOfTravelDistancePt_utl_m = Double.NaN ; - - private Map dataCollectionConfig = new HashMap() ; - private Map dataCollectionStrings = new HashMap() ; - - public RandomizingTransitRouterTravelTimeAndDisutility(TransitRouterConfig routerConfig) { - super(routerConfig); - - prepareDataCollection(); - - // make sure that some parameters are not zero since otherwise the randomization will not work: - - // marg utl time wlk should be around -3/h or -(3/3600)/sec. Give warning if not at least 1/3600: - if ( -routerConfig.getMarginalUtilityOfTravelTimeWalk_utl_s() < 1./3600. ) { - LogManager.getLogger(this.getClass()).warn( "marg utl of walk rather close to zero; randomization may not work") ; - } - // utl of line switch should be around -300sec or -0.5u. Give warning if not at least 0.1u: - if ( -routerConfig.getUtilityOfLineSwitch_utl() < 0.1 ) { - LogManager.getLogger(this.getClass()).warn( "utl of line switch rather close to zero; randomization may not work") ; - } - - this.originalTransitRouterConfig = routerConfig ; - - this.localMarginalUtilityOfTravelDistancePt_utl_m = routerConfig.getMarginalUtilityOfTravelDistancePt_utl_m(); - this.localMarginalUtilityOfTravelTimePt_utl_s = routerConfig.getMarginalUtilityOfTravelTimePt_utl_s() ; - this.localMarginalUtilityOfTravelTimeWalk_utl_s = routerConfig.getMarginalUtilityOfTravelTimeWalk_utl_s() ; -// this.localMarginalUtilityOfWaitingPt_utl_s = routerConfig.getMarginalUtilityOfTravelTimePt_utl_s() ; - this.localMarginalUtilityOfWaitingPt_utl_s = routerConfig.getMarginalUtilityOfWaitingPt_utl_s() ; - this.localUtilityOfLineSwitch_utl = routerConfig.getUtilityOfLineSwitch_utl() ; - } - public final String getDataCollectionString( DataCollection item ) { - return dataCollectionStrings.get(item).toString() ; - } - - @Override - public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle, - final CustomDataManager dataManager) { - - regenerateUtilityParametersIfPersonHasChanged(person); - - double disutl; - if (((TransitRouterNetworkLink) link).getRoute() == null) { - // (this means that it is a transfer link (walk)) - - double transfertime = getLinkTravelTime(link, time, person, vehicle); - double waittime = this.originalTransitRouterConfig.getAdditionalTransferTime(); - - // say that the effective walk time is the transfer time minus some "buffer" - double walktime = transfertime - waittime; - - disutl = - walktime * localMarginalUtilityOfTravelTimeWalk_utl_s - - waittime * localMarginalUtilityOfWaitingPt_utl_s - - localUtilityOfLineSwitch_utl; - - } else { - - double offVehWaitTime = offVehicleWaitTime(link, time); - - double inVehTime = getLinkTravelTime(link,time, person, vehicle) - offVehWaitTime ; - - disutl = -inVehTime * this.localMarginalUtilityOfTravelTimePt_utl_s - - offVehWaitTime * this.localMarginalUtilityOfWaitingPt_utl_s - - link.getLength() * this.localMarginalUtilityOfTravelDistancePt_utl_m; - } - - if ( this.dataCollectionConfig.get(DataCollection.additionalInformation )) { - StringBuffer strb = this.dataCollectionStrings.get(DataCollection.additionalInformation ) ; - strb.append("also collecting additional information") ; - } - - return disutl; - } - - @Override - public double getWalkTravelDisutility(Person person, Coord coord, Coord toCoord) { - regenerateUtilityParametersIfPersonHasChanged(person); - return - getWalkTravelTime(person, coord, toCoord) * localMarginalUtilityOfTravelTimeWalk_utl_s ; - } - - public final void setDataCollection( DataCollection item, Boolean bbb ) { - LogManager.getLogger(this.getClass()).info( " settin data collection of " + item.toString() + " to " + bbb.toString() ) ; - dataCollectionConfig.put( item, bbb ) ; - } - - private void prepareDataCollection() { - for ( DataCollection dataCollection : DataCollection.values() ) { - switch ( dataCollection ) { - case randomizedParameters: - dataCollectionConfig.put( dataCollection, false ) ; - dataCollectionStrings.put( dataCollection, new StringBuffer() ) ; - break; - case additionalInformation: - dataCollectionConfig.put( dataCollection, false ) ; - dataCollectionStrings.put( dataCollection, new StringBuffer() ) ; - break; - } - } - } - - private void regenerateUtilityParametersIfPersonHasChanged(final Person person) { - if ( !person.getId().equals(this.cachedPersonId)) { - // yyyyyy probably not thread safe (?!?!) - - // person has changed, so ... - - // ... memorize new person id: - this.cachedPersonId = person.getId() ; - - // ... generate new random parameters: - { - double tmp = this.originalTransitRouterConfig.getMarginalUtilityOfTravelTimeWalk_utl_s() ; - tmp *= 5. * MatsimRandom.getRandom().nextDouble() ; - localMarginalUtilityOfTravelTimeWalk_utl_s = tmp ; - // yy if this becomes too small, they may walk the whole way (is it really clear why this can happen?) - } - { - double tmp = this.originalTransitRouterConfig.getUtilityOfLineSwitch_utl() ; - tmp *= 5. * MatsimRandom.getRandom().nextDouble() ; - localUtilityOfLineSwitch_utl = tmp ; - } - { - double tmp = this.originalTransitRouterConfig.getMarginalUtilityOfWaitingPt_utl_s(); - tmp *= 5. * MatsimRandom.getRandom().nextDouble(); - localMarginalUtilityOfWaitingPt_utl_s = tmp; - } - { - // (Conceptually, the following is not necessary, but empirically, it seems to help. kai, jan'13) - double tmp = this.originalTransitRouterConfig.getMarginalUtilityOfTravelTimePt_utl_s() ; - tmp *= 5. * MatsimRandom.getRandom().nextDouble(); - localMarginalUtilityOfTravelTimePt_utl_s = tmp; - } - - if ( this.dataCollectionConfig.get(DataCollection.randomizedParameters) ) { -// StringBuffer strb = this.dataCollectionStrings.get(DataCollection.randomizedParameters) ; -// strb.append - System.out.println("personId: " + person.getId() + - "; margUtlOfTimeWlk_h: " + this.localMarginalUtilityOfTravelTimeWalk_utl_s*3600. + - "; utlOfLineSwitch: " + this.localUtilityOfLineSwitch_utl + - "; margUtlOfWait_h: " + this.localMarginalUtilityOfWaitingPt_utl_s*3600. + - "; margUtlOfTimePt_h: " + this.localMarginalUtilityOfTravelTimePt_utl_s*3600. ) ; - } - } - } - -} diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/timeprofile/ProfileWriter.java b/contribs/common/src/main/java/org/matsim/contrib/common/timeprofile/ProfileWriter.java index 5f5a9194b7b..768ec3ea404 100644 --- a/contribs/common/src/main/java/org/matsim/contrib/common/timeprofile/ProfileWriter.java +++ b/contribs/common/src/main/java/org/matsim/contrib/common/timeprofile/ProfileWriter.java @@ -87,7 +87,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { } } - if (this.matsimServices.getConfig().controler().isCreateGraphs()) { + if (this.matsimServices.getConfig().controller().isCreateGraphs()) { DefaultTableXYDataset xyDataset = createXYDataset(times, profiles); generateImage(xyDataset, TimeProfileCharts.ChartType.Line); generateImage(xyDataset, TimeProfileCharts.ChartType.StackedArea); @@ -115,7 +115,7 @@ private DefaultTableXYDataset createXYDataset(double[] times, Map,Double> cnts = new HashMap<>() ; - - @Override public void reset(int iteration) { - cnts.clear(); - } - - @Override public void handleEvent(PersonEntersVehicleEvent event) { - cnts.merge( event.getVehicleId() , 1. , Double::sum ); - } - - void printCounts() { - for ( Entry, Double> entry : cnts.entrySet() ) { - log.info( "Vehicle id: " + entry.getKey() + "; number of boards: " + entry.getValue() ) ; - } - } - - Map< Id, Double> getCounts() { - return this.cnts ; - } - } - - @Rule public MatsimTestUtils utils = new MatsimTestUtils() ; - - @Test -// @Ignore - public final void test() { - String outputDir = utils.getOutputDirectory() ; - - Config config = utils.createConfigWithPackageInputResourcePathAsContext(); - - config.network().setInputFile("network.xml"); - config.plans().setInputFile("population.xml"); - - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); - config.transit().setTransitScheduleFile("transitschedule.xml"); - config.transit().setVehiclesFile("transitVehicles.xml"); - config.transit().setUseTransit(true); - - config.controler().setOutputDirectory( outputDir ); - config.controler().setLastIteration(20); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); - - config.global().setNumberOfThreads(1); - - config.planCalcScore().addActivityParams( new ActivityParams("home").setTypicalDuration( 6*3600. ) ); - config.planCalcScore().addActivityParams( new ActivityParams("education_100").setTypicalDuration( 6*3600. ) ); - -// config.strategy().addStrategySettings( new StrategySettings( ConfigUtils.createAvailableStrategyId(config)).setStrategyName(DefaultStrategy.ReRoute ).setWeight(0.1 ) ); -// config.strategy().addStrategySettings( new StrategySettings( ConfigUtils.createAvailableStrategyId(config)).setStrategyName(DefaultSelector.ChangeExpBeta ).setWeight(0.9 ) ); - config.strategy().addStrategySettings( new StrategySettings().setStrategyName(DefaultStrategy.ReRoute ).setWeight(0.1 ) ); - config.strategy().addStrategySettings( new StrategySettings().setStrategyName(DefaultSelector.ChangeExpBeta ).setWeight(0.9 ) ); - // yy changing the above (= no longer using createAvailableStrategyId) changes the results. :-( :-( :-( - - config.qsim().setEndTime(18.*3600.); - - config.timeAllocationMutator().setMutationRange(7200); - config.timeAllocationMutator().setAffectingDuration(false); - config.plans().setRemovingUnneccessaryPlanAttributes(true); - config.qsim().setTrafficDynamics( TrafficDynamics.withHoles ); - config.qsim().setUsingFastCapacityUpdate(true); - -// config.facilities().setFacilitiesSource( FacilitiesConfigGroup.FacilitiesSource.none ); - // yyyy changing this setting changes result. Possible reasons: - // * The implicit activity coordinates may be elsewhere. - // * The "fudged" walk distances may be different. - // * It uses getNearestLinkEXACTLY, and thus activities may be attached to other links. - - config.vspExperimental().setWritingOutputEvents(true); - config.vspExperimental().setVspDefaultsCheckingLevel( VspDefaultsCheckingLevel.warn ); - - // --- - - Scenario scenario = ScenarioUtils.loadScenario( config ) ; - - // --- - - Controler controler = new Controler( scenario ) ; - - controler.addOverridingModule( new RandomizingTransitRouterModule() ); - - final MyObserver observer = new MyObserver(); - controler.getEvents().addHandler(observer); - - controler.run(); - - // --- - - observer.printCounts(); - - // yyyy the following is just a regression test, making sure that results remain stable. In general, the randomized transit router - // could be improved, for example along the lines of the randomized regular router, which uses a (hopefully unbiased) lognormal - // distribution rather than a biased uniform distribution as is used here. kai, jul'15 - - Assert.assertEquals(36., observer.getCounts().get( Id.create("1009", Vehicle.class) ), 0.1 ); - Assert.assertEquals( 8. /*6.*/ , observer.getCounts().get( Id.create("1012", Vehicle.class) ) , 0.1 ); - Assert.assertEquals(22. /*21.*/, observer.getCounts().get( Id.create("2009", Vehicle.class) ) , 0.1 ); - Assert.assertEquals(36., observer.getCounts().get( Id.create("3009", Vehicle.class) ) , 0.1 ); - - - } - -} diff --git a/contribs/common/src/test/java/org/matsim/integration/always/BetaTravelTest66IT.java b/contribs/common/src/test/java/org/matsim/integration/always/BetaTravelTest66IT.java index 7db3eb15ed1..935e4c61fb8 100644 --- a/contribs/common/src/test/java/org/matsim/integration/always/BetaTravelTest66IT.java +++ b/contribs/common/src/test/java/org/matsim/integration/always/BetaTravelTest66IT.java @@ -133,7 +133,7 @@ public class BetaTravelTest66IT { @Test public void testBetaTravel_66() { Config config = utils.loadConfig("../../examples/scenarios/equil/config.xml"); ConfigUtils.loadConfig(config, utils.getInputDirectory() + "config.xml"); - config.controler().setWritePlansInterval(0); + config.controller().setWritePlansInterval(0); // --- Scenario scenario = ScenarioUtils.loadScenario(config); /* @@ -151,9 +151,9 @@ public void install() { } }); controler.addControlerListener(new TestControlerListener()); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setWriteEventsInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setWriteEventsInterval(0); controler.run(); } @@ -275,7 +275,7 @@ public StrategyManager get() { StrategyManager manager = new StrategyManager(); manager.setMaxPlansPerAgent(5); - PlanStrategyImpl strategy1 = new PlanStrategyImpl(new ExpBetaPlanSelector<>(config.planCalcScore())); + PlanStrategyImpl strategy1 = new PlanStrategyImpl(new ExpBetaPlanSelector<>(config.scoring())); manager.addStrategy( strategy1, null, 0.80 ); PlanStrategyImpl strategy2 = new PlanStrategyImpl(new RandomPlanSelector<>()); @@ -317,12 +317,12 @@ private static class TestControlerListener implements StartupListener, Iteration @Override public void notifyStartup(final StartupEvent event) { // do some test to ensure the scenario is correct - double beta_travel = event.getServices().getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling(); + double beta_travel = event.getServices().getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling(); if ((beta_travel != -6.0) && (beta_travel != -66.0)) { throw new IllegalArgumentException("Unexpected value for beta_travel. Expected -6.0 or -66.0, actual value is " + beta_travel); } - int lastIter = event.getServices().getConfig().controler().getLastIteration(); + int lastIter = event.getServices().getConfig().controller().getLastIteration(); if (lastIter < 100) { throw new IllegalArgumentException("Controler.lastIteration must be at least 100. Current value is " + lastIter); } @@ -360,7 +360,7 @@ public void notifyIterationEnds(final IterationEndsEvent event) { event.getServices().getEvents().removeHandler(this.ttAnalyzer); } if (iteration == 100) { - double beta_travel = event.getServices().getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling(); + double beta_travel = event.getServices().getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling(); /* *************************************************************** * AUTOMATIC VERIFICATION OF THE TESTS: * diff --git a/contribs/common/src/test/java/org/matsim/integration/always/BetaTravelTest6IT.java b/contribs/common/src/test/java/org/matsim/integration/always/BetaTravelTest6IT.java index 6c9792fb458..9db009cbcf8 100644 --- a/contribs/common/src/test/java/org/matsim/integration/always/BetaTravelTest6IT.java +++ b/contribs/common/src/test/java/org/matsim/integration/always/BetaTravelTest6IT.java @@ -133,7 +133,7 @@ public class BetaTravelTest6IT { @Test public void testBetaTravel_6() { Config config = utils.loadConfig("../../examples/scenarios/equil/config.xml"); // default config ConfigUtils.loadConfig(config, utils.getInputDirectory() + "config.xml"); // specific setting for this test - config.controler().setWritePlansInterval(0); + config.controller().setWritePlansInterval(0); config.plans().setActivityDurationInterpretation( ActivityDurationInterpretation.tryEndTimeThenDuration ); /* * The input plans file is not sorted. After switching from TreeMap to LinkedHashMap @@ -150,9 +150,9 @@ public void install() { } }); controler.addControlerListener(new TestControlerListener()); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setWriteEventsInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setWriteEventsInterval(0); controler.run(); } @@ -273,7 +273,7 @@ public StrategyManager get() { StrategyManager manager = new StrategyManager(); manager.setMaxPlansPerAgent(5); - PlanStrategyImpl strategy1 = new PlanStrategyImpl(new ExpBetaPlanSelector(config.planCalcScore())); + PlanStrategyImpl strategy1 = new PlanStrategyImpl(new ExpBetaPlanSelector(config.scoring())); manager.addStrategy( strategy1, null, 0.80 ); PlanStrategyImpl strategy2 = new PlanStrategyImpl(new RandomPlanSelector()); @@ -314,12 +314,12 @@ public TestControlerListener() { @Override public void notifyStartup(final StartupEvent event) { // do some test to ensure the scenario is correct - double beta_travel = event.getServices().getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling(); + double beta_travel = event.getServices().getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling(); if ((beta_travel != -6.0) && (beta_travel != -66.0)) { throw new IllegalArgumentException("Unexpected value for beta_travel. Expected -6.0 or -66.0, actual value is " + beta_travel); } - int lastIter = event.getServices().getConfig().controler().getLastIteration(); + int lastIter = event.getServices().getConfig().controller().getLastIteration(); if (lastIter < 100) { throw new IllegalArgumentException("Controler.lastIteration must be at least 100. Current value is " + lastIter); } @@ -357,7 +357,7 @@ public void notifyIterationEnds(final IterationEndsEvent event) { event.getServices().getEvents().removeHandler(this.ttAnalyzer); } if (iteration == 100) { - double beta_travel = event.getServices().getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling(); + double beta_travel = event.getServices().getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling(); /* *************************************************************** * AUTOMATIC VERIFICATION OF THE TESTS: * diff --git a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionControlerListener.java b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionControlerListener.java index 07b279f0be9..080d92d0c51 100644 --- a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionControlerListener.java +++ b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionControlerListener.java @@ -40,7 +40,7 @@ import org.matsim.contrib.decongestion.handler.DelayAnalysis; import org.matsim.contrib.decongestion.handler.IntervalBasedTolling; import org.matsim.contrib.decongestion.tollSetting.DecongestionTollSetting; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.events.AfterMobsimEvent; import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.controler.events.IterationStartsEvent; @@ -103,7 +103,7 @@ public void notifyStartup(StartupEvent event) { log.info("decongestion settings: " + congestionInfo.getDecongestionConfigGroup().toString()); - this.outputDirectory = this.congestionInfo.getScenario().getConfig().controler().getOutputDirectory(); + this.outputDirectory = this.congestionInfo.getScenario().getConfig().controller().getOutputDirectory(); if (!outputDirectory.endsWith("/")) { log.info("Adjusting output directory."); outputDirectory = outputDirectory + "/"; @@ -117,13 +117,13 @@ public void notifyAfterMobsim(AfterMobsimEvent event) { computeDelays(event); } - if (event.getIteration() == this.congestionInfo.getScenario().getConfig().controler().getFirstIteration()) { + if (event.getIteration() == this.congestionInfo.getScenario().getConfig().controller().getFirstIteration()) { // skip first iteration } else if (event.getIteration() % this.congestionInfo.getDecongestionConfigGroup().getUpdatePriceInterval() == 0.) { - int totalNumberOfIterations = this.congestionInfo.getScenario().getConfig().controler().getLastIteration() - this.congestionInfo.getScenario().getConfig().controler().getFirstIteration(); - int iterationCounter = event.getIteration() - this.congestionInfo.getScenario().getConfig().controler().getFirstIteration(); + int totalNumberOfIterations = this.congestionInfo.getScenario().getConfig().controller().getLastIteration() - this.congestionInfo.getScenario().getConfig().controller().getFirstIteration(); + int iterationCounter = event.getIteration() - this.congestionInfo.getScenario().getConfig().controller().getFirstIteration(); if (iterationCounter < this.congestionInfo.getDecongestionConfigGroup().getFractionOfIterationsToEndPriceAdjustment() * totalNumberOfIterations && iterationCounter > this.congestionInfo.getDecongestionConfigGroup().getFractionOfIterationsToStartPriceAdjustment() * totalNumberOfIterations) { @@ -136,8 +136,8 @@ public void notifyAfterMobsim(AfterMobsimEvent event) { } if (event.getIteration() % this.congestionInfo.getDecongestionConfigGroup().getWriteOutputIteration() == 0.) { - CongestionInfoWriter.writeDelays(congestionInfo, event.getIteration(), this.outputDirectory + "ITERS/it." + event.getIteration() + "/", this.congestionInfo.getScenario().getConfig().controler().getRunId()); - CongestionInfoWriter.writeTolls(congestionInfo, event.getIteration(), this.outputDirectory + "ITERS/it." + event.getIteration() + "/", this.congestionInfo.getScenario().getConfig().controler().getRunId()); + CongestionInfoWriter.writeDelays(congestionInfo, event.getIteration(), this.outputDirectory + "ITERS/it." + event.getIteration() + "/", this.congestionInfo.getScenario().getConfig().controller().getRunId()); + CongestionInfoWriter.writeTolls(congestionInfo, event.getIteration(), this.outputDirectory + "ITERS/it." + event.getIteration() + "/", this.congestionInfo.getScenario().getConfig().controller().getRunId()); } } @@ -197,7 +197,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { if ( person.getSelectedPlan().getScore()==null ) { throw new RuntimeException( "score is null; don't know how to continue.") ; } - monetizedUserBenefits += person.getSelectedPlan().getScore() / this.congestionInfo.getScenario().getConfig().planCalcScore().getMarginalUtilityOfMoney(); + monetizedUserBenefits += person.getSelectedPlan().getScore() / this.congestionInfo.getScenario().getConfig().scoring().getMarginalUtilityOfMoney(); } this.iteration2userBenefits.put(event.getIteration(), monetizedUserBenefits); @@ -207,35 +207,35 @@ public void notifyIterationEnds(IterationEndsEvent event) { this.iteration2totalTravelTime, this.iteration2userBenefits, outputDirectory, - this.congestionInfo.getScenario().getConfig().controler().getRunId() + this.congestionInfo.getScenario().getConfig().controller().getRunId() ); XYLineChart chart1 = new XYLineChart("Total travel time and total delay", "Iteration", "Hours"); double[] iterations1 = new double[event.getIteration() + 1]; double[] values1a = new double[event.getIteration() + 1]; double[] values1b = new double[event.getIteration() + 1]; - for (int i = this.congestionInfo.getScenario().getConfig().controler().getFirstIteration(); i <= event.getIteration(); i++) { + for (int i = this.congestionInfo.getScenario().getConfig().controller().getFirstIteration(); i <= event.getIteration(); i++) { iterations1[i] = i; values1a[i] = this.iteration2totalDelay.get(i) / 3600.; values1b[i] = this.iteration2totalTravelTime.get(i) / 3600.; } chart1.addSeries("Total delay", iterations1, values1a); chart1.addSeries("Total travel time", iterations1, values1b); - chart1.saveAsPng(outputDirectory + this.congestionInfo.getScenario().getConfig().controler().getRunId() + ".decongestion_travelTime_delay.png", 800, 600); + chart1.saveAsPng(outputDirectory + this.congestionInfo.getScenario().getConfig().controller().getRunId() + ".decongestion_travelTime_delay.png", 800, 600); XYLineChart chart2 = new XYLineChart("user benefits and toll revenues", "Iteration", "Monetary units"); double[] iterations2 = new double[event.getIteration() + 1]; double[] values2b = new double[event.getIteration() + 1]; double[] values2c = new double[event.getIteration() + 1]; - for (int i = this.congestionInfo.getScenario().getConfig().controler().getFirstIteration(); i <= event.getIteration(); i++) { + for (int i = this.congestionInfo.getScenario().getConfig().controller().getFirstIteration(); i <= event.getIteration(); i++) { iterations2[i] = i; values2b[i] = this.iteration2userBenefits.get(i); values2c[i] = this.iteration2totalTollPayments.get(i); } chart2.addSeries("User benefits", iterations2, values2b); chart2.addSeries("Toll payments (decongestion tolls only)", iterations2, values2c); - chart2.saveAsPng(outputDirectory + this.congestionInfo.getScenario().getConfig().controler().getRunId() + ".decongestion_userBenefits_tolls.png", 800, 600); + chart2.saveAsPng(outputDirectory + this.congestionInfo.getScenario().getConfig().controller().getRunId() + ".decongestion_userBenefits_tolls.png", 800, 600); } } @@ -243,9 +243,9 @@ public void notifyIterationEnds(IterationEndsEvent event) { public void notifyIterationStarts(IterationStartsEvent event) { if (congestionInfo.getDecongestionConfigGroup().getUpdatePriceInterval() > 1) { - if (event.getIteration() == this.congestionInfo.getScenario().getConfig().controler().getFirstIteration()) { + if (event.getIteration() == this.congestionInfo.getScenario().getConfig().controller().getFirstIteration()) { - this.nextDisableInnovativeStrategiesIteration = (int) (congestionInfo.getScenario().getConfig().strategy().getFractionOfIterationsToDisableInnovation() * congestionInfo.getDecongestionConfigGroup().getUpdatePriceInterval()); + this.nextDisableInnovativeStrategiesIteration = (int) (congestionInfo.getScenario().getConfig().replanning().getFractionOfIterationsToDisableInnovation() * congestionInfo.getDecongestionConfigGroup().getUpdatePriceInterval()); log.info("next disable innovative strategies iteration: " + this.nextDisableInnovativeStrategiesIteration); if (this.nextDisableInnovativeStrategiesIteration != 0) { @@ -274,7 +274,7 @@ public void notifyIterationStarts(IterationStartsEvent event) { } else if (event.getIteration() == this.nextEnableInnovativeStrategiesIteration) { // set weight back to original value - if (event.getIteration() >= congestionInfo.getScenario().getConfig().strategy().getFractionOfIterationsToDisableInnovation() * (congestionInfo.getScenario().getConfig().controler().getLastIteration() - congestionInfo.getScenario().getConfig().controler().getFirstIteration())) { + if (event.getIteration() >= congestionInfo.getScenario().getConfig().replanning().getFractionOfIterationsToDisableInnovation() * (congestionInfo.getScenario().getConfig().controller().getLastIteration() - congestionInfo.getScenario().getConfig().controller().getFirstIteration())) { log.info("Strategies are switched off by global settings. Do not set back the strategy parameters to original values..."); @@ -288,7 +288,7 @@ public void notifyIterationStarts(IterationStartsEvent event) { if (isInnovativeStrategy(strategy)) { double originalValue = -1.0; - for (StrategySettings setting : event.getServices().getConfig().strategy().getStrategySettings()) { + for (StrategySettings setting : event.getServices().getConfig().replanning().getStrategySettings()) { log.info("setting: " + setting.getStrategyName()); log.info("strategyName: " + strategyName); diff --git a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExample.java b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExample.java index a7ae5e473de..72aca4c0fa7 100644 --- a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExample.java +++ b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExample.java @@ -19,7 +19,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.decongestion; @@ -41,7 +41,7 @@ /** * Starts an interval-based decongestion pricing simulation run. - * + * * @author ikaddoura * */ @@ -50,22 +50,22 @@ public class DecongestionRunExample { private static final Logger log = LogManager.getLogger(DecongestionRunExample.class); private static String configFile; - + public static void main(String[] args) throws IOException { - + if (args.length > 0) { log.info("Starting simulation run with the following arguments:"); - configFile = args[0]; + configFile = args[0]; log.info("config file: "+ configFile); } else { configFile = "path/to/config.xml"; } - + DecongestionRunExample main = new DecongestionRunExample(); main.run(); - + } private void run() { @@ -77,9 +77,9 @@ private void run() { decongestionSettings.setUpdatePriceInterval(1); decongestionSettings.setMsa(false); decongestionSettings.setTollBlendFactor(1.0); - + // decongestionSettings.setDecongestionApproach(DecongestionApproach.P_MC); - + decongestionSettings.setDecongestionApproach(DecongestionApproach.PID); decongestionSettings.setKd(0.005); decongestionSettings.setKi(0.005); @@ -87,38 +87,38 @@ private void run() { decongestionSettings.setIntegralApproach(IntegralApproach.UnusedHeadway); decongestionSettings.setIntegralApproachUnusedHeadwayFactor(10.0); decongestionSettings.setIntegralApproachAverageAlpha(0.0); - + // decongestionSettings.setDecongestionApproach(DecongestionApproach.BangBang); // 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.addOverridingModule(new DecongestionModule(scenario)); - + // toll-adjusted routing - + controler.addOverridingModule(new AbstractModule(){ @Override public void install() { final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); } - }); - + }); + // ############################################################# - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists); 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/DecongestionRunExampleFromConfig.java index 3dd8a48c2a1..339c6fff079 100644 --- a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExampleFromConfig.java +++ b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExampleFromConfig.java @@ -19,7 +19,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.decongestion; @@ -39,7 +39,7 @@ /** * Starts an interval-based decongestion pricing simulation run. - * + * * @author ikaddoura * */ @@ -48,37 +48,37 @@ public class DecongestionRunExampleFromConfig { private static final Logger log = LogManager.getLogger(DecongestionRunExampleFromConfig.class); private static String configFile; - - public static void main(String[] args) throws IOException { + + public static void main(String[] args) throws IOException { if (args.length > 0) { log.info("Starting simulation run with the following arguments:"); - configFile = args[0]; + configFile = args[0]; log.info("config file: "+ configFile); } else { configFile = "path/to/config.xml"; } - + DecongestionRunExampleFromConfig main = new DecongestionRunExampleFromConfig(); main.run(); } private void run() throws IOException { - + Config config = ConfigUtils.loadConfig(configFile, new DecongestionConfigGroup()); - + final Scenario scenario = ScenarioUtils.loadScenario(config); Controler controler = new Controler(scenario); - + // ############################################################# - + // congestion toll computation - + controler.addOverridingModule(new DecongestionModule(scenario)); - + // toll-adjusted routing - + final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); controler.addOverridingModule(new AbstractModule(){ @@ -86,11 +86,11 @@ private void run() throws IOException { public void install() { this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); } - }); - + }); + // ############################################################# - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists); controler.run(); } } 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 5635fdbae0a..f4036b3e1a0 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 @@ -35,7 +35,7 @@ import org.matsim.contrib.decongestion.data.LinkInfo; /** - * A cost calculator which respects time, distance and decongestion tolls. + * A cost calculator which respects time, distance and decongestion tolls. * * @author ikaddoura */ @@ -50,15 +50,15 @@ public final class TollTimeDistanceTravelDisutility implements TravelDisutility TollTimeDistanceTravelDisutility( final TravelTime timeCalculator, Config config, DecongestionInfo info ) { this.info = info; - this.marginalUtilityOfMoney = config.planCalcScore().getMarginalUtilityOfMoney(); + this.marginalUtilityOfMoney = config.scoring().getMarginalUtilityOfMoney(); final RandomizingTimeDistanceTravelDisutilityFactory builder = new RandomizingTimeDistanceTravelDisutilityFactory( TransportMode.car, config ); this.delegate = builder.createTravelDisutility(timeCalculator); this.timeBinSize = info.getScenario().getConfig().travelTimeCalculator().getTraveltimeBinSize(); - this.sigma = config.plansCalcRoute().getRoutingRandomness(); - + this.sigma = config.routing().getRoutingRandomness(); + log.info("Using the toll-adjusted travel disutility (improved version) in the decongestion package."); } @@ -67,7 +67,7 @@ public double getLinkTravelDisutility(final Link link, final double time, final int timeBin = (int) (time / timeBinSize); double timeDistanceTravelDisutilityFromDelegate = this.delegate.getLinkTravelDisutility(link, time, person, vehicle); - + double logNormalRnd = 1. ; if ( sigma != 0. ) { logNormalRnd = (double) person.getCustomAttributes().get("logNormalRnd") ; @@ -75,17 +75,17 @@ public double getLinkTravelDisutility(final Link link, final double time, final // adjust the travel disutility for the toll double toll = 0.; - + LinkInfo linkInfo = info.getlinkInfos().get(link.getId()); if (linkInfo != null) { - - Double linkInfoTimeBinToll = linkInfo.getTime2toll().get(timeBin); + + Double linkInfoTimeBinToll = linkInfo.getTime2toll().get(timeBin); if (linkInfoTimeBinToll != null) { toll = linkInfoTimeBinToll; } } - - double tollAdjustedLinkTravelDisutility = timeDistanceTravelDisutilityFromDelegate + logNormalRnd * marginalUtilityOfMoney * toll; + + double tollAdjustedLinkTravelDisutility = timeDistanceTravelDisutilityFromDelegate + logNormalRnd * marginalUtilityOfMoney * toll; return tollAdjustedLinkTravelDisutility; } diff --git a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/tollSetting/DecongestionTollingP_MCP.java b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/tollSetting/DecongestionTollingP_MCP.java index 146bf63f012..00450067e9c 100644 --- a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/tollSetting/DecongestionTollingP_MCP.java +++ b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/tollSetting/DecongestionTollingP_MCP.java @@ -36,64 +36,64 @@ import org.matsim.contrib.decongestion.data.LinkInfo; /** - * + * * P-based toll adjustment, where e(t) = average delay and K_p = VTTS * number of delayed agents - * + * * @author ikaddoura */ public class DecongestionTollingP_MCP implements DecongestionTollSetting, LinkLeaveEventHandler { private static final Logger log = LogManager.getLogger(DecongestionTollingP_MCP.class); - + @Inject private DecongestionInfo congestionInfo; - - private Map, LinkInfo> linkId2infoPreviousTollComputation = new HashMap<>(); + + private Map, LinkInfo> linkId2infoPreviousTollComputation = new HashMap<>(); private int tollUpdateCounter = 0; private final Map, Map> linkId2time2leavingAgents = new HashMap<>(); @Override public void updateTolls() { - - final double vtts = ( this.congestionInfo.getScenario().getConfig().planCalcScore().getPerforming_utils_hr() - - this.congestionInfo.getScenario().getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() ) - / this.congestionInfo.getScenario().getConfig().planCalcScore().getMarginalUtilityOfMoney(); - + final double vtts = ( this.congestionInfo.getScenario().getConfig().scoring().getPerforming_utils_hr() + - this.congestionInfo.getScenario().getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() ) + / this.congestionInfo.getScenario().getConfig().scoring().getMarginalUtilityOfMoney(); + + final double toleratedAvgDelay = this.congestionInfo.getDecongestionConfigGroup().getToleratedAverageDelaySec(); final boolean msa = this.congestionInfo.getDecongestionConfigGroup().isMsa(); final double blendFactorFromConfig = this.congestionInfo.getDecongestionConfigGroup().getTollBlendFactor(); - + for (Id linkId : this.congestionInfo.getlinkInfos().keySet()) { - + LinkInfo linkInfo = this.congestionInfo.getlinkInfos().get(linkId); for (Integer intervalNr : linkInfo.getTime2avgDelay().keySet()) { - + // average delay - - double averageDelay = linkInfo.getTime2avgDelay().get(intervalNr); + + double averageDelay = linkInfo.getTime2avgDelay().get(intervalNr); if (averageDelay <= toleratedAvgDelay) { averageDelay = 0.0; } - + // toll - + double demand = 1.0; if (this.linkId2time2leavingAgents.get(linkId) != null && this.linkId2time2leavingAgents.get(linkId).get(intervalNr) != null) { demand = this.linkId2time2leavingAgents.get(linkId).get(intervalNr); } - + double toll = vtts * demand * averageDelay / 3600.; // prevent negative tolls - + if (toll < 0) { log.warn("Negative tolls... Are you sure everything works fine?"); toll = 0; } - + // smoothen the tolls - + Double previousToll = linkInfo.getTime2toll().get(intervalNr); double blendFactor; @@ -106,35 +106,35 @@ public void updateTolls() { } else { blendFactor = blendFactorFromConfig; } - + double smoothedToll; if (previousToll != null && previousToll >= 0.) { smoothedToll = toll * blendFactor + previousToll * (1 - blendFactor); } else { smoothedToll = toll; } - + // store the updated toll - + linkInfo.getTime2toll().put(intervalNr, smoothedToll); - } + } } - + log.info("Updating tolls completed."); this.tollUpdateCounter++; - + // store the current link information for the next toll computation - + linkId2infoPreviousTollComputation = new HashMap<>(); for ( Map.Entry< Id,LinkInfo> entry : this.congestionInfo.getlinkInfos().entrySet() ) { LinkInfo linkInfo = entry.getValue() ; - + Map time2previousDelay = new HashMap<>(); for (Integer intervalNr : linkInfo.getTime2avgDelay().keySet()) { time2previousDelay.put(intervalNr, linkInfo.getTime2avgDelay().get(intervalNr)); } - + LinkInfo linkInfoPreviousTollComputation = new LinkInfo(linkInfo.getLink()); linkInfoPreviousTollComputation.setTime2avgDelay(time2previousDelay); linkId2infoPreviousTollComputation.put(linkInfo.getLink().getId(), linkInfoPreviousTollComputation); @@ -151,27 +151,27 @@ public void handleEvent(LinkLeaveEvent event) { int timeBinNr = getIntervalNr(event.getTime()); Id linkId = event.getLinkId(); - + if (linkId2time2leavingAgents.get(linkId) != null) { - + if (linkId2time2leavingAgents.get(linkId).get(timeBinNr) != null) { int leavingAgents = linkId2time2leavingAgents.get(linkId).get(timeBinNr) + 1; linkId2time2leavingAgents.get(linkId).put(timeBinNr, leavingAgents); - + } else { linkId2time2leavingAgents.get(linkId).put(timeBinNr, 1); } - + } else { Map time2leavingAgents = new HashMap<>(); time2leavingAgents.put(timeBinNr, 1); linkId2time2leavingAgents.put(linkId, time2leavingAgents); - + } } - + private int getIntervalNr(double time) { - double timeBinSize = congestionInfo.getScenario().getConfig().travelTimeCalculator().getTraveltimeBinSize(); + double timeBinSize = congestionInfo.getScenario().getConfig().travelTimeCalculator().getTraveltimeBinSize(); return (int) (time / timeBinSize); } 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 ac6697e3694..58477477f23 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 @@ -1,560 +1,561 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * copyright : (C) 2013 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -/** - * - */ -package org.matsim.contrib.decongestion; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.matsim.analysis.ScoreStatsControlerListener.ScoreItem; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.decongestion.DecongestionConfigGroup.DecongestionApproach; -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; -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; -import org.matsim.testcases.MatsimTestUtils; - -/** - * - * - * @author ikaddoura - * - */ -public class DecongestionPricingTestIT { - - @Rule - public MatsimTestUtils testUtils = new MatsimTestUtils(); - - /** - * Kp = 0.0123 - * - */ - @Test - public final void test0a() { - - System.out.println(testUtils.getPackageInputDirectory()); - - final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; - - Config config = ConfigUtils.loadConfig(configFile); - - String outputDirectory = testUtils.getOutputDirectory() + "/"; - config.controler().setOutputDirectory(outputDirectory); - - final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); - decongestionSettings.setWriteOutputIteration(1); - decongestionSettings.setKp(0.0123); - decongestionSettings.setKd(0.0); - decongestionSettings.setKi(0.0); - decongestionSettings.setMsa(false); - 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); - - DecongestionInfo info = new DecongestionInfo(); - - // congestion toll computation - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - - this.bind(DecongestionInfo.class).toInstance(info); - - this.bind(DecongestionTollSetting.class).to(DecongestionTollingPID.class); - this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class); - - this.bind(IntervalBasedTollingAll.class).asEagerSingleton(); - this.bind(DelayAnalysis.class).asEagerSingleton(); - this.bind(PersonVehicleTracker.class).asEagerSingleton(); - - this.addEventHandlerBinding().to(IntervalBasedTollingAll.class); - this.addEventHandlerBinding().to(DelayAnalysis.class); - this.addEventHandlerBinding().to(PersonVehicleTracker.class); - - this.addControlerListenerBinding().to(DecongestionControlerListener.class); - - } - }); - - // toll-adjusted routing - - final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - - controler.addOverridingModule(new AbstractModule(){ - @Override - public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); - } - }); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - 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); - - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); - - final int index = config.controler().getLastIteration() - config.controler().getFirstIteration(); - double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); - Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -33.940316666666666, avgScore, MatsimTestUtils.EPSILON); - - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); - - Assert.assertEquals("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", 50.5, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().get(84), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong toll.", 50.5 * 0.0123, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(84), MatsimTestUtils.EPSILON); - - } - - /** - * Kp = 0.0123, other syntax - * - */ - @Test - public final void test0amodified() { - - System.out.println(testUtils.getPackageInputDirectory()); - - final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; - - Config config = ConfigUtils.loadConfig(configFile); - - String outputDirectory = testUtils.getOutputDirectory() + "/"; - config.controler().setOutputDirectory(outputDirectory); - - final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); - decongestionSettings.setWriteOutputIteration(1); - decongestionSettings.setKp(0.0123); - decongestionSettings.setKd(0.0); - decongestionSettings.setKi(0.0); - decongestionSettings.setMsa(false); - 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)); - - // toll-adjusted routing - - final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - - controler.addOverridingModule(new AbstractModule(){ - @Override - public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); - } - }); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - 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); - - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); - - final int index = config.controler().getLastIteration() - config.controler().getFirstIteration(); - double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); - Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -33.940316666666666, avgScore, MatsimTestUtils.EPSILON); - } - - /** - * Kp = 2 - * - */ - @Test - public final void test0b() { - - System.out.println(testUtils.getPackageInputDirectory()); - - final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; - - Config config = ConfigUtils.loadConfig(configFile); - - String outputDirectory = testUtils.getOutputDirectory() + "/"; - config.controler().setOutputDirectory(outputDirectory); - - final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); - decongestionSettings.setWriteOutputIteration(1); - decongestionSettings.setKp(2.0); - decongestionSettings.setKd(0.0); - decongestionSettings.setKi(0.0); - decongestionSettings.setMsa(false); - 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); - - DecongestionInfo info = new DecongestionInfo(); - - // congestion toll computation - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - - this.bind(DecongestionInfo.class).toInstance(info); - - this.bind(DecongestionTollSetting.class).to(DecongestionTollingPID.class); - this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class); - - this.bind(IntervalBasedTollingAll.class).asEagerSingleton(); - this.bind(DelayAnalysis.class).asEagerSingleton(); - this.bind(PersonVehicleTracker.class).asEagerSingleton(); - - this.addEventHandlerBinding().to(IntervalBasedTollingAll.class); - this.addEventHandlerBinding().to(DelayAnalysis.class); - this.addEventHandlerBinding().to(PersonVehicleTracker.class); - - this.addControlerListenerBinding().to(DecongestionControlerListener.class); - - } - }); - - // toll-adjusted routing - - final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - - controler.addOverridingModule(new AbstractModule(){ - @Override - public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); - } - }); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - 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); - - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); - - final int index = config.controler().getLastIteration() - config.controler().getFirstIteration(); - double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); - Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -134.31916666666666, avgScore, MatsimTestUtils.EPSILON); - - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); - - Assert.assertEquals("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", 50.5, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().get(84), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong toll.", 50.5 * 2, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(84), MatsimTestUtils.EPSILON); - } - - /** - * Kp = 2 - * - */ - @Test - public final void test0bmodified() { - - System.out.println(testUtils.getPackageInputDirectory()); - - final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; - - Config config = ConfigUtils.loadConfig(configFile); - - String outputDirectory = testUtils.getOutputDirectory() + "/"; - config.controler().setOutputDirectory(outputDirectory); - - final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); - decongestionSettings.setWriteOutputIteration(1); - decongestionSettings.setKp(2.0); - decongestionSettings.setKd(0.0); - decongestionSettings.setKi(0.0); - decongestionSettings.setMsa(false); - 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)); - - // toll-adjusted routing - - final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - - controler.addOverridingModule(new AbstractModule(){ - @Override - public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); - } - }); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - 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); - - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); - - final int index = config.controler().getLastIteration() - config.controler().getFirstIteration(); - double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); - Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -134.31916666666666, avgScore, MatsimTestUtils.EPSILON); - } - - /** - * Kp = 0 / no tolling - * - */ - @Test - public final void test0c() { - - System.out.println(testUtils.getPackageInputDirectory()); - - final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; - - Config config = ConfigUtils.loadConfig(configFile); - - String outputDirectory = testUtils.getOutputDirectory() + "/"; - config.controler().setOutputDirectory(outputDirectory); - - final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); - decongestionSettings.setWriteOutputIteration(1); - decongestionSettings.setKp(0.0); - decongestionSettings.setKd(0.0); - decongestionSettings.setKi(0.0); - decongestionSettings.setMsa(false); - 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); - - DecongestionInfo info = new DecongestionInfo(); - - // congestion toll computation - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - - this.bind(DecongestionInfo.class).toInstance(info); - - this.bind(DelayAnalysis.class).asEagerSingleton(); - this.addEventHandlerBinding().to(DelayAnalysis.class); - - this.addControlerListenerBinding().to(DecongestionControlerListener.class); - - } - }); - - // toll-adjusted routing - - final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - - controler.addOverridingModule(new AbstractModule(){ - @Override - public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); - } - }); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - 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); - - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); - - final int index = config.controler().getLastIteration() - config.controler().getFirstIteration(); - double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); - Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -33.31916666666666, avgScore, MatsimTestUtils.EPSILON); - - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); - - Assert.assertEquals("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", 50.5, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().get(84), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong toll.", null, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(84)); - - } - - /** - * Tests the PID controller - * - */ - @Test - public final void test1() { - - System.out.println(testUtils.getPackageInputDirectory()); - - final String configFile = testUtils.getPackageInputDirectory() + "/config.xml"; - Config config = ConfigUtils.loadConfig(configFile); - - String outputDirectory = testUtils.getOutputDirectory() + "/"; - config.controler().setOutputDirectory(outputDirectory); - - final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); - decongestionSettings.setWriteOutputIteration(1); - decongestionSettings.setFractionOfIterationsToEndPriceAdjustment(1.0); - decongestionSettings.setFractionOfIterationsToStartPriceAdjustment(0.0); - decongestionSettings.setDecongestionApproach(DecongestionApproach.PID); - config.addModule(decongestionSettings); - - final Scenario scenario = ScenarioUtils.loadScenario(config); - Controler controler = new Controler(scenario); - - DecongestionInfo info = new DecongestionInfo(); - - // decongestion pricing - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - - this.bind(DecongestionInfo.class).toInstance(info); - - this.bind(DecongestionTollSetting.class).to(DecongestionTollingPID.class); - this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class); - - this.bind(IntervalBasedTollingAll.class).asEagerSingleton(); - this.bind(DelayAnalysis.class).asEagerSingleton(); - this.bind(PersonVehicleTracker.class).asEagerSingleton(); - - this.addEventHandlerBinding().to(IntervalBasedTollingAll.class); - this.addEventHandlerBinding().to(DelayAnalysis.class); - this.addEventHandlerBinding().to(PersonVehicleTracker.class); - - this.addControlerListenerBinding().to(DecongestionControlerListener.class); - } - }); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - controler.run(); - - final int index = config.controler().getLastIteration() - config.controler().getFirstIteration(); - double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index) ; - Assert.assertEquals("Wrong average executed score. The run output seems to have changed.", -11749.431349675931, avgScore, MatsimTestUtils.EPSILON); - - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); - Assert.assertEquals("Wrong toll in time bin 61.", 12.600000000000009, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(61), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong toll in time bin 73.", 16.665000000000006, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(73), MatsimTestUtils.EPSILON); - } - - /** - * Tests the BangBang controller - * - */ - @Test - public final void test2() { - - System.out.println(testUtils.getPackageInputDirectory()); - - final String configFile = testUtils.getPackageInputDirectory() + "/config.xml"; - Config config = ConfigUtils.loadConfig(configFile); - - String outputDirectory = testUtils.getOutputDirectory() + "/"; - config.controler().setOutputDirectory(outputDirectory); - - final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); - decongestionSettings.setWriteOutputIteration(1); - decongestionSettings.setFractionOfIterationsToEndPriceAdjustment(1.0); - decongestionSettings.setFractionOfIterationsToStartPriceAdjustment(0.0); - config.addModule(decongestionSettings); - - DecongestionInfo info = new DecongestionInfo(); - - final Scenario scenario = ScenarioUtils.loadScenario(config); - Controler controler = new Controler(scenario); - - // decongestion pricing - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - - this.bind(DecongestionInfo.class).toInstance(info); - - this.bind(DecongestionTollSetting.class).to(DecongestionTollingBangBang.class); - this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class); - - this.bind(IntervalBasedTollingAll.class).asEagerSingleton(); - this.bind(DelayAnalysis.class).asEagerSingleton(); - this.bind(PersonVehicleTracker.class).asEagerSingleton(); - - this.addEventHandlerBinding().to(IntervalBasedTollingAll.class); - this.addEventHandlerBinding().to(DelayAnalysis.class); - this.addEventHandlerBinding().to(PersonVehicleTracker.class); - - this.addControlerListenerBinding().to(DecongestionControlerListener.class); - - } - }); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - controler.run(); - - final int index = config.controler().getLastIteration() - config.controler().getFirstIteration(); - double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get( index ) ; - Assert.assertEquals("Wrong average executed score. The run output seems to have changed.", -54.97929444444, avgScore, MatsimTestUtils.EPSILON); - - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); - Assert.assertEquals("Wrong toll in time bin 61.", 13., info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(61), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong toll in time bin 73.", 13., info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(73), MatsimTestUtils.EPSILON); - } - -} +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2013 by the members listed in the COPYING, * + * LICENSE and WARRANTY file. * + * email : info at matsim dot org * + * * + * *********************************************************************** * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * See also COPYING, LICENSE and WARRANTY file * + * * + * *********************************************************************** */ + +/** + * + */ +package org.matsim.contrib.decongestion; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.matsim.analysis.ScoreStatsControlerListener.ScoreItem; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.Scenario; +import org.matsim.contrib.decongestion.DecongestionConfigGroup.DecongestionApproach; +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; +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; +import org.matsim.testcases.MatsimTestUtils; + +/** + * + * + * @author ikaddoura + * + */ +public class DecongestionPricingTestIT { + + @Rule + public MatsimTestUtils testUtils = new MatsimTestUtils(); + + /** + * Kp = 0.0123 + * + */ + @Test + public final void test0a() { + + System.out.println(testUtils.getPackageInputDirectory()); + + final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; + + Config config = ConfigUtils.loadConfig(configFile); + + String outputDirectory = testUtils.getOutputDirectory() + "/"; + config.controller().setOutputDirectory(outputDirectory); + + final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); + decongestionSettings.setWriteOutputIteration(1); + decongestionSettings.setKp(0.0123); + decongestionSettings.setKd(0.0); + decongestionSettings.setKi(0.0); + decongestionSettings.setMsa(false); + 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); + + DecongestionInfo info = new DecongestionInfo(); + + // congestion toll computation + controler.addOverridingModule(new AbstractModule() { + @Override + public void install() { + + this.bind(DecongestionInfo.class).toInstance(info); + + this.bind(DecongestionTollSetting.class).to(DecongestionTollingPID.class); + this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class); + + this.bind(IntervalBasedTollingAll.class).asEagerSingleton(); + this.bind(DelayAnalysis.class).asEagerSingleton(); + this.bind(PersonVehicleTracker.class).asEagerSingleton(); + + this.addEventHandlerBinding().to(IntervalBasedTollingAll.class); + this.addEventHandlerBinding().to(DelayAnalysis.class); + this.addEventHandlerBinding().to(PersonVehicleTracker.class); + + this.addControlerListenerBinding().to(DecongestionControlerListener.class); + + } + }); + + // toll-adjusted routing + + final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); + + controler.addOverridingModule(new AbstractModule(){ + @Override + public void install() { + this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + } + }); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + 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); + + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); + + final int index = config.controller().getLastIteration() - config.controller().getFirstIteration(); + double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); + Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -33.940316666666666, avgScore, MatsimTestUtils.EPSILON); + + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); + + Assert.assertEquals("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", 50.5, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().get(84), MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong toll.", 50.5 * 0.0123, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(84), MatsimTestUtils.EPSILON); + + } + + /** + * Kp = 0.0123, other syntax + * + */ + @Test + public final void test0amodified() { + + System.out.println(testUtils.getPackageInputDirectory()); + + final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; + + Config config = ConfigUtils.loadConfig(configFile); + + String outputDirectory = testUtils.getOutputDirectory() + "/"; + config.controller().setOutputDirectory(outputDirectory); + + final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); + decongestionSettings.setWriteOutputIteration(1); + decongestionSettings.setKp(0.0123); + decongestionSettings.setKd(0.0); + decongestionSettings.setKi(0.0); + decongestionSettings.setMsa(false); + 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)); + + // toll-adjusted routing + + final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); + + controler.addOverridingModule(new AbstractModule(){ + @Override + public void install() { + this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + } + }); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + 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); + + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); + + final int index = config.controller().getLastIteration() - config.controller().getFirstIteration(); + double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); + Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -33.940316666666666, avgScore, MatsimTestUtils.EPSILON); + } + + /** + * Kp = 2 + * + */ + @Test + public final void test0b() { + + System.out.println(testUtils.getPackageInputDirectory()); + + final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; + + Config config = ConfigUtils.loadConfig(configFile); + + String outputDirectory = testUtils.getOutputDirectory() + "/"; + config.controller().setOutputDirectory(outputDirectory); + + final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); + decongestionSettings.setWriteOutputIteration(1); + decongestionSettings.setKp(2.0); + decongestionSettings.setKd(0.0); + decongestionSettings.setKi(0.0); + decongestionSettings.setMsa(false); + 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); + + DecongestionInfo info = new DecongestionInfo(); + + // congestion toll computation + controler.addOverridingModule(new AbstractModule() { + @Override + public void install() { + + this.bind(DecongestionInfo.class).toInstance(info); + + this.bind(DecongestionTollSetting.class).to(DecongestionTollingPID.class); + this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class); + + this.bind(IntervalBasedTollingAll.class).asEagerSingleton(); + this.bind(DelayAnalysis.class).asEagerSingleton(); + this.bind(PersonVehicleTracker.class).asEagerSingleton(); + + this.addEventHandlerBinding().to(IntervalBasedTollingAll.class); + this.addEventHandlerBinding().to(DelayAnalysis.class); + this.addEventHandlerBinding().to(PersonVehicleTracker.class); + + this.addControlerListenerBinding().to(DecongestionControlerListener.class); + + } + }); + + // toll-adjusted routing + + final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); + + controler.addOverridingModule(new AbstractModule(){ + @Override + public void install() { + this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + } + }); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + 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); + + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); + + final int index = config.controller().getLastIteration() - config.controller().getFirstIteration(); + double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); + Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -134.31916666666666, avgScore, MatsimTestUtils.EPSILON); + + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); + + Assert.assertEquals("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", 50.5, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().get(84), MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong toll.", 50.5 * 2, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(84), MatsimTestUtils.EPSILON); + } + + /** + * Kp = 2 + * + */ + @Test + public final void test0bmodified() { + + System.out.println(testUtils.getPackageInputDirectory()); + + final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; + + Config config = ConfigUtils.loadConfig(configFile); + + String outputDirectory = testUtils.getOutputDirectory() + "/"; + config.controller().setOutputDirectory(outputDirectory); + + final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); + decongestionSettings.setWriteOutputIteration(1); + decongestionSettings.setKp(2.0); + decongestionSettings.setKd(0.0); + decongestionSettings.setKi(0.0); + decongestionSettings.setMsa(false); + 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)); + + // toll-adjusted routing + + final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); + + controler.addOverridingModule(new AbstractModule(){ + @Override + public void install() { + this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + } + }); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + 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); + + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); + + final int index = config.controller().getLastIteration() - config.controller().getFirstIteration(); + double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); + Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -134.31916666666666, avgScore, MatsimTestUtils.EPSILON); + } + + /** + * Kp = 0 / no tolling + * + */ + @Test + public final void test0c() { + + System.out.println(testUtils.getPackageInputDirectory()); + + final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; + + Config config = ConfigUtils.loadConfig(configFile); + + String outputDirectory = testUtils.getOutputDirectory() + "/"; + config.controller().setOutputDirectory(outputDirectory); + + final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); + decongestionSettings.setWriteOutputIteration(1); + decongestionSettings.setKp(0.0); + decongestionSettings.setKd(0.0); + decongestionSettings.setKi(0.0); + decongestionSettings.setMsa(false); + 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); + + DecongestionInfo info = new DecongestionInfo(); + + // congestion toll computation + controler.addOverridingModule(new AbstractModule() { + @Override + public void install() { + + this.bind(DecongestionInfo.class).toInstance(info); + + this.bind(DelayAnalysis.class).asEagerSingleton(); + this.addEventHandlerBinding().to(DelayAnalysis.class); + + this.addControlerListenerBinding().to(DecongestionControlerListener.class); + + } + }); + + // toll-adjusted routing + + final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); + + controler.addOverridingModule(new AbstractModule(){ + @Override + public void install() { + this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + } + }); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + 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); + + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt0, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 150.5, tt1, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong travel time. The run output seems to have changed.", 100.0, tt2, MatsimTestUtils.EPSILON); + + final int index = config.controller().getLastIteration() - config.controller().getFirstIteration(); + double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); + Assert.assertEquals("Wrong average executed score. The tolls seem to have changed.", -33.31916666666666, avgScore, MatsimTestUtils.EPSILON); + + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); + + Assert.assertEquals("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", 50.5, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().get(84), MatsimTestUtils.EPSILON); + Assert.assertNull("Wrong toll.", info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(84)); + + } + + /** + * Tests the PID controller + * + */ + @Test + public final void test1() { + + System.out.println(testUtils.getPackageInputDirectory()); + + final String configFile = testUtils.getPackageInputDirectory() + "/config.xml"; + Config config = ConfigUtils.loadConfig(configFile); + + String outputDirectory = testUtils.getOutputDirectory() + "/"; + config.controller().setOutputDirectory(outputDirectory); + + final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); + decongestionSettings.setWriteOutputIteration(1); + decongestionSettings.setFractionOfIterationsToEndPriceAdjustment(1.0); + decongestionSettings.setFractionOfIterationsToStartPriceAdjustment(0.0); + decongestionSettings.setDecongestionApproach(DecongestionApproach.PID); + config.addModule(decongestionSettings); + + final Scenario scenario = ScenarioUtils.loadScenario(config); + Controler controler = new Controler(scenario); + + DecongestionInfo info = new DecongestionInfo(); + + // decongestion pricing + controler.addOverridingModule(new AbstractModule() { + @Override + public void install() { + + this.bind(DecongestionInfo.class).toInstance(info); + + this.bind(DecongestionTollSetting.class).to(DecongestionTollingPID.class); + this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class); + + this.bind(IntervalBasedTollingAll.class).asEagerSingleton(); + this.bind(DelayAnalysis.class).asEagerSingleton(); + this.bind(PersonVehicleTracker.class).asEagerSingleton(); + + this.addEventHandlerBinding().to(IntervalBasedTollingAll.class); + this.addEventHandlerBinding().to(DelayAnalysis.class); + this.addEventHandlerBinding().to(PersonVehicleTracker.class); + + this.addControlerListenerBinding().to(DecongestionControlerListener.class); + } + }); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + controler.run(); + + final int index = config.controller().getLastIteration() - config.controller().getFirstIteration(); + double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index) ; + Assert.assertEquals("Wrong average executed score. The run output seems to have changed.", -12036.177448472225, avgScore, MatsimTestUtils.EPSILON); + + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); + Assert.assertEquals("Wrong toll in time bin 61.", 9.197000000000003, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(61), MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong toll in time bin 73.", 12.963999999999984, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(73), MatsimTestUtils.EPSILON); + } + + /** + * Tests the BangBang controller + * + */ + @Test + public final void test2() { + + System.out.println(testUtils.getPackageInputDirectory()); + + final String configFile = testUtils.getPackageInputDirectory() + "/config.xml"; + Config config = ConfigUtils.loadConfig(configFile); + + String outputDirectory = testUtils.getOutputDirectory() + "/"; + config.controller().setOutputDirectory(outputDirectory); + + final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); + decongestionSettings.setWriteOutputIteration(1); + decongestionSettings.setFractionOfIterationsToEndPriceAdjustment(1.0); + decongestionSettings.setFractionOfIterationsToStartPriceAdjustment(0.0); + config.addModule(decongestionSettings); + + DecongestionInfo info = new DecongestionInfo(); + + final Scenario scenario = ScenarioUtils.loadScenario(config); + Controler controler = new Controler(scenario); + + // decongestion pricing + controler.addOverridingModule(new AbstractModule() { + @Override + public void install() { + + this.bind(DecongestionInfo.class).toInstance(info); + + this.bind(DecongestionTollSetting.class).to(DecongestionTollingBangBang.class); + this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class); + + this.bind(IntervalBasedTollingAll.class).asEagerSingleton(); + this.bind(DelayAnalysis.class).asEagerSingleton(); + this.bind(PersonVehicleTracker.class).asEagerSingleton(); + + this.addEventHandlerBinding().to(IntervalBasedTollingAll.class); + this.addEventHandlerBinding().to(DelayAnalysis.class); + this.addEventHandlerBinding().to(PersonVehicleTracker.class); + + this.addControlerListenerBinding().to(DecongestionControlerListener.class); + + } + }); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + controler.run(); + + + final int index = config.controller().getLastIteration() - config.controller().getFirstIteration(); + double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get( index ) ; + Assert.assertEquals("Wrong average executed score. The run output seems to have changed.", -55.215645833333184, avgScore, MatsimTestUtils.EPSILON); + + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); + Assert.assertEquals("Wrong toll in time bin 61.", 13., info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(61), MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong toll in time bin 73.", 13., info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(73), MatsimTestUtils.EPSILON); + } + +} diff --git a/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/DiscreteModeChoiceConfigurator.java b/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/DiscreteModeChoiceConfigurator.java index 44838aa3186..4cf1f8704cb 100644 --- a/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/DiscreteModeChoiceConfigurator.java +++ b/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/DiscreteModeChoiceConfigurator.java @@ -10,8 +10,8 @@ import org.matsim.contribs.discrete_mode_choice.modules.config.DiscreteModeChoiceConfigGroup; import org.matsim.contribs.discrete_mode_choice.replanning.NonSelectedPlanSelector; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.StrategyConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.config.groups.SubtourModeChoiceConfigGroup; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule.DefaultSelector; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule.DefaultStrategy; @@ -19,7 +19,7 @@ /** * Utility class that makes it possible to set up various was of using the * Discrete Mode Choice extension with MATSim. - * + * * @author sebhoerl */ public final class DiscreteModeChoiceConfigurator { @@ -28,7 +28,7 @@ private DiscreteModeChoiceConfigurator() { } static public void configureAsSubtourModeChoiceReplacement(Config config) { - for (StrategySettings strategy : config.strategy().getStrategySettings()) { + for (StrategySettings strategy : config.replanning().getStrategySettings()) { if (strategy.getStrategyName().equals(DefaultStrategy.SubtourModeChoice)) { strategy.setStrategyName(DiscreteModeChoiceModule.STRATEGY_NAME); } @@ -89,24 +89,24 @@ static public void configureAsModeChoiceInTheLoop(Config config) { } static public void configureAsModeChoiceInTheLoop(Config config, double replanningRate) { - StrategyConfigGroup strategyConfigGroup = config.strategy(); - strategyConfigGroup.clearStrategySettings(); + ReplanningConfigGroup replanningConfigGroup = config.replanning(); + replanningConfigGroup.clearStrategySettings(); - strategyConfigGroup.setMaxAgentPlanMemorySize(1); - strategyConfigGroup.setFractionOfIterationsToDisableInnovation(Double.POSITIVE_INFINITY); - strategyConfigGroup.setPlanSelectorForRemoval(NonSelectedPlanSelector.NAME); + replanningConfigGroup.setMaxAgentPlanMemorySize(1); + replanningConfigGroup.setFractionOfIterationsToDisableInnovation(Double.POSITIVE_INFINITY); + replanningConfigGroup.setPlanSelectorForRemoval(NonSelectedPlanSelector.NAME); StrategySettings dmcStrategy = new StrategySettings(); dmcStrategy.setStrategyName(DiscreteModeChoiceModule.STRATEGY_NAME); dmcStrategy.setWeight(replanningRate); - strategyConfigGroup.addStrategySettings(dmcStrategy); + replanningConfigGroup.addStrategySettings(dmcStrategy); StrategySettings selectorStrategy = new StrategySettings(); selectorStrategy.setStrategyName(DefaultSelector.KeepLastSelected); selectorStrategy.setWeight(1.0 - replanningRate); - strategyConfigGroup.addStrategySettings(selectorStrategy); + replanningConfigGroup.addStrategySettings(selectorStrategy); - checkModeChoiceInTheLoop(strategyConfigGroup); + checkModeChoiceInTheLoop(replanningConfigGroup); DiscreteModeChoiceConfigGroup dmcConfig = (DiscreteModeChoiceConfigGroup) config.getModules() .get(DiscreteModeChoiceConfigGroup.GROUP_NAME); @@ -119,15 +119,15 @@ static public void configureAsModeChoiceInTheLoop(Config config, double replanni dmcConfig.setEnforceSinglePlan(true); } - public static void checkModeChoiceInTheLoop(StrategyConfigGroup strategyConfigGroup) { - if (strategyConfigGroup.getMaxAgentPlanMemorySize() != 1) { + public static void checkModeChoiceInTheLoop(ReplanningConfigGroup replanningConfigGroup) { + if (replanningConfigGroup.getMaxAgentPlanMemorySize() != 1) { throw new IllegalStateException( "Option strategy.maxAgentPlanMemorySize should be 1 if mode-choice-in-the-loop is enforced."); } Set activeStrategies = new HashSet<>(); - for (StrategySettings strategySettings : strategyConfigGroup.getStrategySettings()) { + for (StrategySettings strategySettings : replanningConfigGroup.getStrategySettings()) { if (strategySettings.getDisableAfter() != 0) { activeStrategies.add(strategySettings.getStrategyName()); } @@ -146,14 +146,14 @@ public static void checkModeChoiceInTheLoop(StrategyConfigGroup strategyConfigGr activeStrategies.remove(DefaultSelector.KeepLastSelected); activeStrategies.remove(DiscreteModeChoiceModule.STRATEGY_NAME); activeStrategies.remove(DefaultStrategy.ReRoute); - + if (activeStrategies.size() > 0) { throw new IllegalStateException( "All these strategies should be disabled (disableAfter == 0) if mode-choice-in-the-loop is enforced: " + activeStrategies); } - if (!strategyConfigGroup.getPlanSelectorForRemoval().equals(NonSelectedPlanSelector.NAME)) { + if (!replanningConfigGroup.getPlanSelectorForRemoval().equals(NonSelectedPlanSelector.NAME)) { throw new IllegalStateException( "Removal selector should be NonSelectedPlanSelector if mode-choice-in-the-loop is enforced."); } diff --git a/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/DiscreteModeChoiceModule.java b/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/DiscreteModeChoiceModule.java index 58db9c55b85..abf34cb42f6 100644 --- a/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/DiscreteModeChoiceModule.java +++ b/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/DiscreteModeChoiceModule.java @@ -11,7 +11,7 @@ /** * Main module of the Discrete Mode Choice extension. Should be added as an * overriding module before the MATSim controller is started. - * + * * @author sebhoerl */ public class DiscreteModeChoiceModule extends AbstractModule { @@ -24,7 +24,7 @@ public class DiscreteModeChoiceModule extends AbstractModule { public void install() { addPlanStrategyBinding(STRATEGY_NAME).toProvider(DiscreteModeChoiceStrategyProvider.class); - if (getConfig().strategy().getPlanSelectorForRemoval().equals(NonSelectedPlanSelector.NAME)) { + if (getConfig().replanning().getPlanSelectorForRemoval().equals(NonSelectedPlanSelector.NAME)) { bindPlanSelectorForRemoval().to(NonSelectedPlanSelector.class); } diff --git a/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/utils/ModeChoiceInTheLoopChecker.java b/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/utils/ModeChoiceInTheLoopChecker.java index 0d7df42a168..04617415d08 100644 --- a/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/utils/ModeChoiceInTheLoopChecker.java +++ b/contribs/discrete_mode_choice/src/main/java/org/matsim/contribs/discrete_mode_choice/modules/utils/ModeChoiceInTheLoopChecker.java @@ -4,7 +4,7 @@ import org.matsim.api.core.v01.population.Plan; import org.matsim.contribs.discrete_mode_choice.modules.DiscreteModeChoiceConfigurator; import org.matsim.contribs.discrete_mode_choice.replanning.NonSelectedPlanSelector; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.events.StartupEvent; import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.replanning.selectors.PlanSelector; @@ -14,16 +14,16 @@ /** * Internal listener that is used to do some runtime checks when * mode-choice-in-the-loop should be enforced. - * + * * @author sebhoerl * */ public class ModeChoiceInTheLoopChecker implements StartupListener { - private final StrategyConfigGroup strategyConfig; + private final ReplanningConfigGroup strategyConfig; private final PlanSelector removalSelector; @Inject - public ModeChoiceInTheLoopChecker(StrategyConfigGroup strategyConfig, PlanSelector removalSelector) { + public ModeChoiceInTheLoopChecker(ReplanningConfigGroup strategyConfig, PlanSelector removalSelector) { this.strategyConfig = strategyConfig; this.removalSelector = removalSelector; } diff --git a/contribs/discrete_mode_choice/src/test/java/org/matsim/contrib/discrete_mode_choice/examples/TestSiouxFalls.java b/contribs/discrete_mode_choice/src/test/java/org/matsim/contrib/discrete_mode_choice/examples/TestSiouxFalls.java index 9d931e70283..7b71a32670e 100644 --- a/contribs/discrete_mode_choice/src/test/java/org/matsim/contrib/discrete_mode_choice/examples/TestSiouxFalls.java +++ b/contribs/discrete_mode_choice/src/test/java/org/matsim/contrib/discrete_mode_choice/examples/TestSiouxFalls.java @@ -28,16 +28,15 @@ public void testSiouxFallsWithSubtourModeChoiceReplacement() { URL scenarioURL = ExamplesUtils.getTestScenarioURL("siouxfalls-2014"); Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(scenarioURL, "config_default.xml")); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); DiscreteModeChoiceConfigurator.configureAsSubtourModeChoiceReplacement(config); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(1); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(1); // save some bandwidth/time: - config.controler().setCreateGraphs( false ); - config.controler().setWritePlansInterval( 0 ); - config.controler().setWriteEventsInterval( 0 ); - config.controler().setDumpDataAtEnd( false ); + config.controller().setCreateGraphs( false ); + config.controller().setWritePlansInterval( 0 ); + config.controller().setWriteEventsInterval( 0 ); + config.controller().setDumpDataAtEnd( false ); config.qsim().setFlowCapFactor(10000.0); config.qsim().setStorageCapFactor(10000.0); @@ -57,14 +56,14 @@ public void install() { controller.run(); - assertEquals(42395, (int) listener.counts.get("pt")); - assertEquals(132284, (int) listener.counts.get("car")); - assertEquals(78809, (int) listener.counts.get("walk")); -// assertEquals(42520, (int) listener.counts.get("pt")); -// assertEquals(132100, (int) listener.counts.get("car")); -// assertEquals(79106, (int) listener.counts.get("walk")); - // ...setConstrainedModes(...) (inside configureAsSubtourModeChoiceReplacement(...)) used to ignore its arguments because of a typo. - // This is now corrected, but results are no longer backwards compatible. kai, jan'23 + + System.out.println((int) listener.counts.get("pt")); + System.out.println((int) listener.counts.get("car")); + System.out.println(listener.counts.get("walk")); + + assertEquals(44195, listener.counts.get("pt"), 2); + assertEquals(132316, listener.counts.get("car"), 2); + assertEquals(82139, listener.counts.get("walk"), 2); } diff --git a/contribs/drt-extensions/pom.xml b/contribs/drt-extensions/pom.xml index b56ab569782..2217f9ebdc7 100644 --- a/contribs/drt-extensions/pom.xml +++ b/contribs/drt-extensions/pom.xml @@ -24,6 +24,12 @@ 16.0-SNAPSHOT
+ + org.matsim.contrib + informed-mode-choice + 16.0-SNAPSHOT + + org.matsim.contrib simwrapper @@ -33,6 +39,7 @@ org.assertj assertj-core + test diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/companions/DrtCompanionControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/companions/DrtCompanionControlerCreator.java index 9d14d6a5b37..058588cf40e 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/companions/DrtCompanionControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/companions/DrtCompanionControlerCreator.java @@ -21,14 +21,12 @@ package org.matsim.contrib.drt.extension.companions; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.drt.extension.companions.MultiModeDrtCompanionModule; 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.drt.run.MultiModeDrtModule; import org.matsim.contrib.dvrp.run.DvrpModule; import org.matsim.contrib.dvrp.run.DvrpQSimComponents; -import org.matsim.contrib.otfvis.OTFVisLiveModule; import org.matsim.core.config.Config; import org.matsim.core.controler.Controler; import org.matsim.core.scenario.ScenarioUtils; @@ -42,7 +40,7 @@ public final class DrtCompanionControlerCreator { public static Controler createControler(Config config) { MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.planCalcScore(), config.plansCalcRoute()); + DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); Scenario scenario = DrtControlerCreator.createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboardProvider.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboardProvider.java index 9760f3ec617..93e186e2474 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboardProvider.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboardProvider.java @@ -25,7 +25,7 @@ public List getDashboards(Config config, SimWrapper simWrapper) { for (DrtConfigGroup drtConfig : multiModeDrtConfigGroup.getModalElements()) { - result.add(new DrtDashboard(drtConfig, config.getContext(), config.global().getCoordinateSystem(), config.controler().getLastIteration())); + result.add(new DrtDashboard(drtConfig, config.getContext(), config.global().getCoordinateSystem(), config.controller().getLastIteration())); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java index 638180019a7..8471438ebe4 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java @@ -42,7 +42,7 @@ public class EDrtControlerCreator { public static Controler createControler(Config config, boolean otfvis) { MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.planCalcScore(), config.plansCalcRoute()); + DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); Scenario scenario = DrtControlerCreator.createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtModeOptimizerQSimModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtModeOptimizerQSimModule.java index ba65f62d550..2194784123d 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtModeOptimizerQSimModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtModeOptimizerQSimModule.java @@ -64,7 +64,7 @@ import org.matsim.contrib.dvrp.schedule.ScheduleTimingUpdater; import org.matsim.contrib.dvrp.vrpagent.VrpAgentLogic; import org.matsim.contrib.ev.infrastructure.ChargingInfrastructure; -import org.matsim.contrib.ev.infrastructure.ChargingInfrastructures; +import org.matsim.contrib.ev.infrastructure.ChargingInfrastructureUtils; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.mobsim.framework.MobsimTimer; import org.matsim.core.modal.ModalProviders; @@ -103,8 +103,8 @@ protected void configureQSim() { })).asEagerSingleton(); bindModal(ChargingInfrastructure.class).toProvider(modalProvider( - getter -> ChargingInfrastructures.createModalNetworkChargers(getter.get(ChargingInfrastructure.class), - getter.getModal(Network.class), getMode()))).asEagerSingleton(); + getter -> ChargingInfrastructureUtils.createModalNetworkChargers(getter.get(ChargingInfrastructure.class ), + getter.getModal(Network.class), getMode() ))).asEagerSingleton(); // XXX if overridden to something else, make sure that the depots are equipped with chargers // otherwise vehicles will not re-charge diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/scheduler/EmptyVehicleChargingScheduler.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/scheduler/EmptyVehicleChargingScheduler.java index f50d437a1a0..eea29745e80 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/scheduler/EmptyVehicleChargingScheduler.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/scheduler/EmptyVehicleChargingScheduler.java @@ -21,20 +21,23 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; +import org.matsim.contrib.drt.extension.edrt.schedule.EDrtTaskFactoryImpl; import org.matsim.contrib.drt.schedule.DrtStayTask; import org.matsim.contrib.drt.schedule.DrtTaskFactory; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.schedule.Schedule; -import org.matsim.contrib.drt.extension.edrt.schedule.EDrtTaskFactoryImpl; import org.matsim.contrib.ev.charging.ChargingStrategy; import org.matsim.contrib.ev.charging.ChargingWithAssignmentLogic; -import org.matsim.contrib.evrp.EvDvrpVehicle; import org.matsim.contrib.ev.fleet.ElectricVehicle; import org.matsim.contrib.ev.infrastructure.Charger; import org.matsim.contrib.ev.infrastructure.ChargingInfrastructure; +import org.matsim.contrib.evrp.EvDvrpVehicle; import org.matsim.core.mobsim.framework.MobsimTimer; +import java.util.Comparator; +import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.stream.Collectors; /** @@ -43,23 +46,27 @@ public class EmptyVehicleChargingScheduler { private final MobsimTimer timer; private final EDrtTaskFactoryImpl taskFactory; - private final Map, Charger> linkToChargerMap; + private final Map, List> linkToChargersMap; public EmptyVehicleChargingScheduler(MobsimTimer timer, DrtTaskFactory taskFactory, ChargingInfrastructure chargingInfrastructure) { this.timer = timer; this.taskFactory = (EDrtTaskFactoryImpl)taskFactory; - linkToChargerMap = chargingInfrastructure.getChargers() + linkToChargersMap = chargingInfrastructure.getChargers() .values() .stream() - .collect(Collectors.toMap(c -> c.getLink().getId(), c -> c)); + .collect(Collectors.groupingBy(c -> c.getLink().getId())); } public void chargeVehicle(DvrpVehicle vehicle) { DrtStayTask currentTask = (DrtStayTask)vehicle.getSchedule().getCurrentTask(); Link currentLink = currentTask.getLink(); - Charger charger = linkToChargerMap.get(currentLink.getId()); - if (charger != null) { + List chargers = linkToChargersMap.get(currentLink.getId()); + if (chargers != null) { + Optional freeCharger = chargers.stream().filter(c -> c.getLogic().getPluggedVehicles().isEmpty()).findFirst(); + + // Empty charger or at least smallest queue charger + Charger charger = freeCharger.orElseGet(() -> chargers.stream().min(Comparator.comparingInt(e -> e.getLogic().getQueuedVehicles().size())).orElseThrow()); ElectricVehicle ev = ((EvDvrpVehicle)vehicle).getElectricVehicle(); if (!charger.getLogic().getChargingStrategy().isChargingCompleted(ev)) { chargeVehicleImpl(vehicle, charger); @@ -67,6 +74,8 @@ public void chargeVehicle(DvrpVehicle vehicle) { } } + + private void chargeVehicleImpl(DvrpVehicle vehicle, Charger charger) { Schedule schedule = vehicle.getSchedule(); DrtStayTask stayTask = (DrtStayTask)schedule.getCurrentTask(); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/BasicDrtEstimator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/BasicDrtEstimator.java new file mode 100644 index 00000000000..3d7555020e1 --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/BasicDrtEstimator.java @@ -0,0 +1,172 @@ +package org.matsim.contrib.drt.extension.estimator; + +import org.apache.commons.math3.stat.descriptive.SummaryStatistics; +import org.apache.commons.math3.stat.regression.RegressionResults; +import org.apache.commons.math3.stat.regression.SimpleRegression; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.matsim.api.core.v01.events.PersonMoneyEvent; +import org.matsim.contrib.drt.analysis.DrtEventSequenceCollector; +import org.matsim.contrib.drt.extension.estimator.run.DrtEstimatorConfigGroup; +import org.matsim.contrib.drt.fare.DrtFareParams; +import org.matsim.contrib.drt.routing.DrtRoute; +import org.matsim.contrib.drt.run.DrtConfigGroup; +import org.matsim.contrib.drt.speedup.DrtSpeedUp; +import org.matsim.core.controler.events.IterationEndsEvent; +import org.matsim.core.controler.listener.IterationEndsListener; +import org.matsim.core.utils.misc.OptionalTime; + +import java.util.SplittableRandom; + +/** + * Estimates drt trips based only daily averages. No spatial or temporal differentiation is taken into account for the estimate. + * This estimator is suited for small scenarios with few vehicles and trips and consequently few data points. + */ +public class BasicDrtEstimator implements DrtEstimator, IterationEndsListener { + + private static final Logger log = LogManager.getLogger(BasicDrtEstimator.class); + + private final DrtEventSequenceCollector collector; + private final DrtEstimatorConfigGroup config; + private final DrtConfigGroup drtConfig; + + private final SplittableRandom rnd = new SplittableRandom(); + /** + * Currently valid estimates. + */ + private GlobalEstimate currentEst; + private RegressionResults fare; + + public BasicDrtEstimator(DrtEventSequenceCollector collector, DrtEstimatorConfigGroup config, + DrtConfigGroup drtConfig) { + //zones = injector.getModal(DrtZonalSystem.class); + this.collector = collector; + this.config = config; + this.drtConfig = drtConfig; + } + + @Override + public void notifyIterationEnds(IterationEndsEvent event) { + + // Speed-up iteration need to be ignored for the estimates + if (drtConfig.getDrtSpeedUpParams().isPresent() && + DrtSpeedUp.isTeleportDrtUsers(drtConfig.getDrtSpeedUpParams().get(), + event.getServices().getConfig().controller(), event.getIteration())) { + return; + } + + GlobalEstimate est = new GlobalEstimate(); + + int n = 0; + + int nRejections = collector.getRejectedRequestSequences().size(); + int nSubmitted = collector.getRequestSubmissions().size(); + + for (DrtEventSequenceCollector.EventSequence seq : collector.getPerformedRequestSequences().values()) { + + if (seq.getPickedUp().isPresent() && seq.getDroppedOff().isPresent()) { + + double waitTime = seq.getPickedUp().get().getTime() - seq.getSubmitted().getTime(); + est.waitTime.addValue(waitTime); + + double unsharedTime = seq.getSubmitted().getUnsharedRideTime(); + double travelTime = seq.getDroppedOff().get().getTime() - seq.getPickedUp().get().getTime(); + + est.detour.addValue(travelTime / unsharedTime); + + double fare = seq.getDrtFares().stream().mapToDouble(PersonMoneyEvent::getAmount).sum(); + est.fare.addData(seq.getSubmitted().getUnsharedRideDistance(), fare); + n++; + } + } + + // At least some data points are required + if (n <= 3) + return; + + fare = est.fare.regress(); + + double rejectionRate = (double) nRejections / nSubmitted; + + if (currentEst == null) { + est.meanWait = est.waitTime.getMean(); + est.stdWait = est.waitTime.getStandardDeviation(); + est.meanDetour = est.detour.getMean(); + est.stdDetour = est.detour.getStandardDeviation(); + est.rejectionRate = rejectionRate; + } else { + est.meanWait = config.decayFactor * est.waitTime.getMean() + (1 - config.decayFactor) * currentEst.waitTime.getMean(); + est.stdWait = config.decayFactor * est.waitTime.getStandardDeviation() + (1 - config.decayFactor) * currentEst.waitTime.getStandardDeviation(); + est.meanDetour = config.decayFactor * est.detour.getMean() + (1 - config.decayFactor) * currentEst.detour.getMean(); + est.stdDetour = config.decayFactor * est.detour.getStandardDeviation() + (1 - config.decayFactor) * currentEst.detour.getStandardDeviation(); + est.rejectionRate = config.decayFactor * rejectionRate + (1 - config.decayFactor) * currentEst.rejectionRate; + } + + log.info("Calculated {}", est); + currentEst = est; + } + + @Override + public Estimate estimate(DrtRoute route, OptionalTime departureTime) { + + if (currentEst == null) { + // If not estimates are present, use travel time alpha as detour + // beta is not used, because estimates are supposed to be minimums and not worst cases + double travelTime = Math.min(route.getDirectRideTime() + drtConfig.maxAbsoluteDetour, + route.getDirectRideTime() * drtConfig.maxTravelTimeAlpha); + + double fare = 0; + if (drtConfig.getDrtFareParams().isPresent()) { + DrtFareParams fareParams = drtConfig.getDrtFareParams().get(); + fare = fareParams.distanceFare_m * route.getDistance() + + fareParams.timeFare_h * route.getDirectRideTime() / 3600.0 + + fareParams.baseFare; + + fare = Math.max(fare, fareParams.minFarePerTrip); + } + + // for distance, also use the max travel time alpha + return new Estimate(route.getDistance() * drtConfig.maxTravelTimeAlpha, travelTime, drtConfig.maxWaitTime, fare, 0); + } + + double fare = 0; + if (this.fare != null) + fare = this.fare.getParameterEstimate(0) + this.fare.getParameterEstimate(1) * route.getDistance(); + + if (drtConfig.getDrtFareParams().isPresent()) { + fare = Math.max(fare, drtConfig.getDrtFareParams().get().minFarePerTrip); + } + + double detour = Math.max(1, rnd.nextGaussian(currentEst.meanDetour, config.randomization * currentEst.stdDetour)); + double waitTime = Math.max(0, rnd.nextGaussian(currentEst.meanWait, config.randomization * currentEst.stdWait)); + + return new Estimate(route.getDistance() * detour, route.getDirectRideTime() * detour, waitTime, fare, currentEst.rejectionRate); + } + + /** + * Helper class to hold statistics. + */ + private static final class GlobalEstimate { + + private final SummaryStatistics waitTime = new SummaryStatistics(); + private final SummaryStatistics detour = new SummaryStatistics(); + private final SimpleRegression fare = new SimpleRegression(true); + + private double meanWait; + private double stdWait; + private double meanDetour; + private double stdDetour; + private double rejectionRate; + + @Override + public String toString() { + return "GlobalEstimate{" + + "meanWait=" + meanWait + + ", stdWait=" + stdWait + + ", meanDetour=" + meanDetour + + ", stdDetour=" + stdDetour + + ", rejectionRate=" + rejectionRate + + '}'; + } + } +} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/DrtEstimateAnalyzer.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/DrtEstimateAnalyzer.java new file mode 100644 index 00000000000..2d87f7ea7b8 --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/DrtEstimateAnalyzer.java @@ -0,0 +1,126 @@ +package org.matsim.contrib.drt.extension.estimator; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.matsim.api.core.v01.events.PersonMoneyEvent; +import org.matsim.contrib.drt.analysis.DrtEventSequenceCollector; +import org.matsim.contrib.drt.extension.estimator.run.DrtEstimatorConfigGroup; +import org.matsim.contrib.drt.routing.DrtRoute; +import org.matsim.core.controler.events.AfterMobsimEvent; +import org.matsim.core.controler.events.ShutdownEvent; +import org.matsim.core.controler.events.StartupEvent; +import org.matsim.core.controler.listener.AfterMobsimListener; +import org.matsim.core.controler.listener.ShutdownListener; +import org.matsim.core.controler.listener.StartupListener; +import org.matsim.core.utils.misc.OptionalTime; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +/** + * Analyzes and outputs drt estimates errors metrics based on daily requests. + */ +public final class DrtEstimateAnalyzer implements StartupListener, ShutdownListener, AfterMobsimListener { + + private static final Logger log = LogManager.getLogger(DrtEstimateAnalyzer.class); + + // Might be useful but not needed currently + //private final DefaultMainLegRouter.RouteCreator creator; + private final DrtEstimator estimator; + private final DrtEventSequenceCollector collector; + private final DrtEstimatorConfigGroup config; + + private CSVPrinter csv; + + public DrtEstimateAnalyzer(DrtEstimator estimator, DrtEventSequenceCollector collector, DrtEstimatorConfigGroup config) { + this.estimator = estimator; + this.collector = collector; + this.config = config; + } + + @Override + public void notifyStartup(StartupEvent event) { + + String filename = event.getServices().getControlerIO().getOutputFilename("drt_estimates_" + config.getMode() + ".csv"); + + try { + csv = new CSVPrinter(Files.newBufferedWriter(Path.of(filename), StandardCharsets.UTF_8), CSVFormat.DEFAULT); + csv.printRecord("iteration", + "wait_time_mae", "wait_time_err_q5", "wait_time_err_q50", "wait_time_err_q95", + "travel_time_mae", "travel_time_err_q5", "travel_time_err_q50", "travel_time_err_q95", + "fare_mae", "fare_err_q5", "fare_err_q50", "fare_err_q95" + ); + + } catch (IOException e) { + throw new UncheckedIOException("Could not open output file for estimates.", e); + } + } + + @Override + public void notifyShutdown(ShutdownEvent event) { + try { + csv.close(); + } catch (IOException e) { + log.warn("Could not close drt estimate file", e); + } + } + + /** + * Needs to run before any estimators updates. + */ + @Override + public void notifyAfterMobsim(AfterMobsimEvent event) { + + try { + csv.printRecord(calcMetrics(event.getIteration())); + csv.flush(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Return row of metrics for the csv file. + */ + private Iterable calcMetrics(int iteration) { + + DescriptiveStatistics waitTime = new DescriptiveStatistics(); + DescriptiveStatistics travelTime = new DescriptiveStatistics(); + DescriptiveStatistics fare = new DescriptiveStatistics(); + + for (DrtEventSequenceCollector.EventSequence seq : collector.getPerformedRequestSequences().values()) { + if (seq.getPickedUp().isPresent() && seq.getDroppedOff().isPresent()) { + + // many attributes are not filled, when using the constructor + DrtRoute route = new DrtRoute(seq.getSubmitted().getFromLinkId(), seq.getSubmitted().getToLinkId()); + route.setDirectRideTime(seq.getSubmitted().getUnsharedRideTime()); + route.setDistance(seq.getSubmitted().getUnsharedRideDistance()); + + double valWaitTime = seq.getPickedUp().get().getTime() - seq.getSubmitted().getTime(); + double valTravelTime = seq.getDroppedOff().get().getTime() - seq.getPickedUp().get().getTime(); + double valFare = seq.getDrtFares().stream().mapToDouble(PersonMoneyEvent::getAmount).sum(); + + DrtEstimator.Estimate estimate = estimator.estimate(route, OptionalTime.defined(seq.getSubmitted().getTime())); + + waitTime.addValue(Math.abs(estimate.waitingTime() - valWaitTime)); + travelTime.addValue(Math.abs(estimate.travelTime() - valTravelTime)); + fare.addValue(Math.abs(estimate.fare() - valFare)); + } + } + + return List.of( + iteration, + waitTime.getMean(), waitTime.getPercentile(5), waitTime.getPercentile(50), waitTime.getPercentile(95), + travelTime.getMean(), travelTime.getPercentile(5), travelTime.getPercentile(50), travelTime.getPercentile(95), + fare.getMean(), fare.getPercentile(5), fare.getPercentile(50), fare.getPercentile(95) + ); + } + +} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/DrtEstimator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/DrtEstimator.java new file mode 100644 index 00000000000..fef209ed211 --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/DrtEstimator.java @@ -0,0 +1,35 @@ +package org.matsim.contrib.drt.extension.estimator; + +import org.matsim.contrib.drt.routing.DrtRoute; +import org.matsim.core.controler.listener.ControlerListener; +import org.matsim.core.utils.misc.OptionalTime; + +/** + * Interface to estimate a DRT service's detour, waiting time and costs. + */ +public interface DrtEstimator extends ControlerListener { + + /** + * Provide an estimate for a drt route with specific pickup and dropoff point. + * + * @param route drt route + * @param departureTime estimated departure time + * @return An {@link Estimate} instance + */ + Estimate estimate(DrtRoute route, OptionalTime departureTime); + + + /** + * Estimate for various attributes for a drt trip. + * + * @param distance travel distance in meter + * @param travelTime travel time in seconds + * @param waitingTime waiting time in seconds + * @param fare money, which is negative if the customer needs to pay it + * @param rejectionRate probability of a trip being rejected + */ + record Estimate(double distance, double travelTime, double waitingTime, double fare, double rejectionRate) { + + } + +} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/MultiModalDrtLegEstimator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/MultiModalDrtLegEstimator.java new file mode 100644 index 00000000000..ed1771ae34f --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/MultiModalDrtLegEstimator.java @@ -0,0 +1,58 @@ +package org.matsim.contrib.drt.extension.estimator; + +import com.google.inject.Inject; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.matsim.api.core.v01.population.Leg; +import org.matsim.contrib.drt.routing.DrtRoute; +import org.matsim.contrib.dvrp.run.DvrpMode; +import org.matsim.core.scoring.functions.ModeUtilityParameters; +import org.matsim.core.utils.misc.OptionalTime; +import org.matsim.modechoice.EstimatorContext; +import org.matsim.modechoice.ModeAvailability; +import org.matsim.modechoice.estimators.LegEstimator; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + + +/** + * Aggregate class for informed-mode-choice that makes sure to invoke the correct estimator for each drt mode. + */ +public class MultiModalDrtLegEstimator implements LegEstimator { + + private static final Logger log = LogManager.getLogger(MultiModalDrtLegEstimator.class); + + protected final Map estimators = new HashMap<>(); + + @Inject + public MultiModalDrtLegEstimator(Map estimators) { + for (Map.Entry e : estimators.entrySet()) { + this.estimators.put(e.getKey().value(), e.getValue()); + } + } + + @Override + public double estimate(EstimatorContext context, String mode, Leg leg, ModeAvailability option) { + + if (!(leg.getRoute() instanceof DrtRoute route)) + throw new IllegalStateException("Drt leg routes must be of type DrtRoute."); + + OptionalTime departureTime = leg.getDepartureTime(); + + DrtEstimator estimator = Objects.requireNonNull(estimators.get(mode), String.format("No drt estimator found for mode %s. Check warnings for errors.", mode)); + + DrtEstimator.Estimate est = estimator.estimate(route, departureTime); + ModeUtilityParameters params = context.scoring.modeParams.get(mode); + + // By default, waiting time is scored as travel time + return params.constant + + params.marginalUtilityOfDistance_m * est.distance() + + params.marginalUtilityOfTraveling_s * est.travelTime() + + params.marginalUtilityOfTraveling_s * est.waitingTime() + + context.scoring.marginalUtilityOfMoney * params.monetaryDistanceCostRate * est.distance() + + context.scoring.marginalUtilityOfMoney * est.fare(); + + } +} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/run/DrtEstimatorConfigGroup.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/run/DrtEstimatorConfigGroup.java new file mode 100644 index 00000000000..107aa2eb53a --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/run/DrtEstimatorConfigGroup.java @@ -0,0 +1,61 @@ +package org.matsim.contrib.drt.extension.estimator.run; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.PositiveOrZero; +import org.matsim.api.core.v01.TransportMode; +import org.matsim.contrib.dvrp.run.Modal; +import org.matsim.contrib.util.ReflectiveConfigGroupWithConfigurableParameterSets; + +public class DrtEstimatorConfigGroup extends ReflectiveConfigGroupWithConfigurableParameterSets implements Modal { + + /** + * Type of estimator, which will be installed in {@link DrtEstimatorModule}. + */ + public enum EstimatorType { + BASIC, + + /** + * Custom estimator, that needs to provided via binding. + */ + CUSTOM + } + + public static final String GROUP_NAME = "drtEstimator"; + + public DrtEstimatorConfigGroup() { + super(GROUP_NAME); + } + + public DrtEstimatorConfigGroup(String mode) { + super(GROUP_NAME); + this.mode = mode; + } + + @Parameter + @Comment("Mode of the drt service to estimate.") + @NotBlank + public String mode = TransportMode.drt; + + @Parameter + @Comment("Estimator typed to be used. In case of 'CUSTOM', guice bindings needs to be provided.") + @NotNull + public EstimatorType estimator = EstimatorType.BASIC; + + @Parameter + @Comment("Decay of the exponential moving average.") + @Positive + public double decayFactor = 0.7; + + @Parameter + @Comment("Factor multiplied with standard deviation to randomize estimates.") + @PositiveOrZero + public double randomization = 0.1; + + @Override + public String getMode() { + return mode; + } + +} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/run/DrtEstimatorModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/run/DrtEstimatorModule.java new file mode 100644 index 00000000000..14bc2ae330d --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/run/DrtEstimatorModule.java @@ -0,0 +1,80 @@ +package org.matsim.contrib.drt.extension.estimator.run; + +import com.google.inject.Singleton; +import com.google.inject.multibindings.MapBinder; +import org.matsim.contrib.drt.analysis.DrtEventSequenceCollector; +import org.matsim.contrib.drt.extension.estimator.BasicDrtEstimator; +import org.matsim.contrib.drt.extension.estimator.DrtEstimateAnalyzer; +import org.matsim.contrib.drt.extension.estimator.DrtEstimator; +import org.matsim.contrib.drt.run.DrtConfigGroup; +import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; +import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule; +import org.matsim.contrib.dvrp.run.DvrpMode; +import org.matsim.contrib.dvrp.run.DvrpModes; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.controler.AbstractModule; + +import java.util.Optional; + +/** + * Main module that needs to be installed if any estimator is to be used. + */ +public class DrtEstimatorModule extends AbstractModule { + + @Override + public void install() { + + MultiModeDrtConfigGroup drtConfigs = MultiModeDrtConfigGroup.get(getConfig()); + MultiModeDrtEstimatorConfigGroup configs = ConfigUtils.addOrGetModule(getConfig(), MultiModeDrtEstimatorConfigGroup.class); + + for (DrtConfigGroup cfg : drtConfigs.getModalElements()) { + + Optional estCfg = configs.getModalElement(cfg.mode); + + estCfg.ifPresent(drtEstimatorConfigGroup -> install(new ModeModule(cfg, drtEstimatorConfigGroup))); + } + } + + static final class ModeModule extends AbstractDvrpModeModule { + + private final DrtConfigGroup cfg; + private final DrtEstimatorConfigGroup group; + + public ModeModule(DrtConfigGroup cfg, DrtEstimatorConfigGroup group) { + super(group.mode); + this.cfg = cfg; + this.group = group; + } + + @Override + public void install() { + + // try with default injections and overwrite + if (group.estimator == DrtEstimatorConfigGroup.EstimatorType.BASIC) { + bindModal(DrtEstimator.class).toProvider(modalProvider( + getter -> new BasicDrtEstimator(getter.getModal(DrtEventSequenceCollector.class), group, cfg) + )).in(Singleton.class); + } + + // DRT Estimators will be available as Map + MapBinder.newMapBinder(this.binder(), DvrpMode.class, DrtEstimator.class) + .addBinding(DvrpModes.mode(getMode())) + .to(modalKey(DrtEstimator.class)); + + addControlerListenerBinding().to(modalKey(DrtEstimator.class)); + + bindModal(DrtEstimatorConfigGroup.class).toInstance(group); + + // Needs to run before estimators + bindModal(DrtEstimateAnalyzer.class) + .toProvider( + modalProvider(getter -> new DrtEstimateAnalyzer(getter.getModal(DrtEstimator.class), getter.getModal(DrtEventSequenceCollector.class), group)) + ) + .in(Singleton.class); + + addControlerListenerBinding().to(modalKey(DrtEstimateAnalyzer.class)); + + } + + } +} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/run/MultiModeDrtEstimatorConfigGroup.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/run/MultiModeDrtEstimatorConfigGroup.java new file mode 100644 index 00000000000..b998bf78648 --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/estimator/run/MultiModeDrtEstimatorConfigGroup.java @@ -0,0 +1,103 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 2018 by the members listed in the COPYING, * + * LICENSE and WARRANTY file. * + * email : info at matsim dot org * + * * + * *********************************************************************** * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * See also COPYING, LICENSE and WARRANTY file * + * * + * *********************************************************************** * + */ + +package org.matsim.contrib.drt.extension.estimator.run; + +import java.util.Collection; +import java.util.Optional; +import java.util.function.Supplier; + +import org.matsim.contrib.dvrp.run.MultiModal; +import org.matsim.contrib.dvrp.run.MultiModals; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigGroup; +import org.matsim.core.config.ReflectiveConfigGroup; + +import com.google.common.base.Verify; + +/** + * @author Michal Maciejewski (michalm) + */ +public final class MultiModeDrtEstimatorConfigGroup extends ReflectiveConfigGroup implements MultiModal { + public static final String GROUP_NAME = "drtEstimators"; + + /** + * @param config + * @return MultiModeDrtConfigGroup if exists. Otherwise fails + */ + public static MultiModeDrtEstimatorConfigGroup get(Config config) { + return (MultiModeDrtEstimatorConfigGroup)config.getModule(GROUP_NAME); + } + + private final Supplier drtConfigSupplier; + + public MultiModeDrtEstimatorConfigGroup() { + this(DrtEstimatorConfigGroup::new); + } + + public MultiModeDrtEstimatorConfigGroup(Supplier drtConfigSupplier) { + super(GROUP_NAME); + this.drtConfigSupplier = drtConfigSupplier; + } + + @Override + protected void checkConsistency(Config config) { + super.checkConsistency(config); + Verify.verify(config.getModule(DrtEstimatorConfigGroup.GROUP_NAME) == null, + "In the multi-mode DRT setup, DrtEstimatorConfigGroup must not be defined at the config top level"); + MultiModals.requireAllModesUnique(this); + } + + @Override + public ConfigGroup createParameterSet(String type) { + if (type.equals(DrtEstimatorConfigGroup.GROUP_NAME)) { + return drtConfigSupplier.get(); + } else { + throw new IllegalArgumentException("Unsupported parameter set type: " + type); + } + } + + @Override + public void addParameterSet(ConfigGroup set) { + if (set instanceof DrtEstimatorConfigGroup) { + super.addParameterSet(set); + } else { + throw new IllegalArgumentException("Unsupported parameter set class: " + set); + } + } + + public void addParameterSet(DrtEstimatorConfigGroup set) { + addParameterSet((ConfigGroup) set); + } + + @Override + @SuppressWarnings("unchecked") + public Collection getModalElements() { + return (Collection)getParameterSets(DrtEstimatorConfigGroup.GROUP_NAME); + } + + /** + * Find estimator config for specific mode. + */ + public Optional getModalElement(String mode) { + return getModalElements().stream().filter(m -> m.getMode().equals(mode)).findFirst(); + } + +} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/fiss/FISS.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/fiss/FISS.java index ac265cf4a2c..58705f89cb3 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/fiss/FISS.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/fiss/FISS.java @@ -164,7 +164,7 @@ public void afterSim() { } private boolean switchOffFISS() { - return (this.fissConfigGroup.switchOffFISSLastIteration && this.matsimServices.getConfig().controler().getLastIteration() == this.matsimServices.getIterationNumber()); + return (this.fissConfigGroup.switchOffFISSLastIteration && this.matsimServices.getConfig().controller().getLastIteration() == this.matsimServices.getIterationNumber()); } @Override diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/BreakCorridorXY.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/BreakCorridorXY.java index 3a3b0762936..320b23977f9 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/BreakCorridorXY.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/BreakCorridorXY.java @@ -10,12 +10,12 @@ import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecification; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import jakarta.inject.Provider; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; +import java.io.UncheckedIOException; import java.util.HashMap; import java.util.Map; diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftAnalysisControlerListener.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftAnalysisControlerListener.java index 2db2c3d8fec..de7026de9e2 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftAnalysisControlerListener.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftAnalysisControlerListener.java @@ -52,7 +52,7 @@ public ShiftAnalysisControlerListener(Config config, DrtConfigGroup drtConfigGro @Override public void notifyIterationEnds(IterationEndsEvent event) { - boolean createGraphs = event.getServices().getConfig().controler().isCreateGraphs(); + boolean createGraphs = event.getServices().getConfig().controller().isCreateGraphs(); writeAndPlotShiftDurationComparison(shiftDurationXY.getShift2plannedVsActualDuration(), filename(event, "shiftDurationComparison", ".png"), diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftDurationXY.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftDurationXY.java index f370d7f6b4f..d2ff4dda184 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftDurationXY.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftDurationXY.java @@ -9,11 +9,11 @@ import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecification; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; +import java.io.UncheckedIOException; import java.util.HashMap; import java.util.Map; diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogram.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogram.java index d4a519129fc..ce228469e50 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogram.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogram.java @@ -6,12 +6,12 @@ import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.core.config.Config; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.Time; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; +import java.io.UncheckedIOException; import java.util.Set; /** diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogramChart.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogramChart.java index bd877f2843d..d39236c91ee 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogramChart.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogramChart.java @@ -9,11 +9,11 @@ import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; -import org.matsim.core.utils.io.UncheckedIOException; import java.awt.*; import java.io.File; import java.io.IOException; +import java.io.UncheckedIOException; /** * @author nkuehnel / MOIA diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogramListener.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogramListener.java index 18525c18a7f..15aef81a055 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogramListener.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/ShiftHistogramListener.java @@ -35,7 +35,7 @@ public void notifyIterationStarts(final IterationStartsEvent event) { public void notifyIterationEnds(final IterationEndsEvent event) { this.shiftHistogram.write(matsimServices.getControlerIO().getIterationFilename(event.getIteration(), drtConfigGroup.getMode() + "_" + "shiftHistogram.txt")); this.printStats(); - boolean createGraphs = event.getServices().getConfig().controler().isCreateGraphs(); + boolean createGraphs = event.getServices().getConfig().controller().isCreateGraphs(); if (createGraphs) { ShiftHistogramChart.writeGraphic(this.shiftHistogram, matsimServices.getControlerIO().getIterationFilename(event.getIteration(),drtConfigGroup.getMode() + "_" + "shiftHistogram.png")); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/efficiency/ShiftEfficiencyAnalysisControlerListener.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/efficiency/ShiftEfficiencyAnalysisControlerListener.java index a7b7c8248ed..f75637f76d7 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/efficiency/ShiftEfficiencyAnalysisControlerListener.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/analysis/efficiency/ShiftEfficiencyAnalysisControlerListener.java @@ -56,7 +56,7 @@ public ShiftEfficiencyAnalysisControlerListener(DrtConfigGroup drtConfigGroup, @Override public void notifyIterationEnds(IterationEndsEvent event) { - boolean createGraphs = event.getServices().getConfig().controler().isCreateGraphs(); + boolean createGraphs = event.getServices().getConfig().controller().isCreateGraphs(); writeAndPlotShiftEfficiency( shiftEfficiencyTracker.getCurrentRecord().getRevenueByShift(), diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/io/DrtShiftsWriter.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/io/DrtShiftsWriter.java index 92d3c43812d..0d5f56e5d75 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/io/DrtShiftsWriter.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/io/DrtShiftsWriter.java @@ -11,9 +11,9 @@ import org.matsim.core.gbl.Gbl; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.*; import java.util.stream.Collectors; diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/io/OperationFacilitiesWriter.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/io/OperationFacilitiesWriter.java index 22c3a1712e5..91b247738d1 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/io/OperationFacilitiesWriter.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/io/OperationFacilitiesWriter.java @@ -11,9 +11,9 @@ import org.matsim.core.gbl.Gbl; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.*; import java.util.stream.Collectors; diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/preplanned/run/PreplannedDrtControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/preplanned/run/PreplannedDrtControlerCreator.java index fbf6325b77a..bbf5fa4c5c2 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/preplanned/run/PreplannedDrtControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/preplanned/run/PreplannedDrtControlerCreator.java @@ -62,7 +62,7 @@ public final class PreplannedDrtControlerCreator { */ public static Controler createControler(Config config, boolean otfvis) { MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.planCalcScore(), config.plansCalcRoute()); + DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); Scenario scenario = createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/preplanned/run/RunPreplannedDrtExample.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/preplanned/run/RunPreplannedDrtExample.java index 04f7852c45a..e0463eb46f0 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/preplanned/run/RunPreplannedDrtExample.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/preplanned/run/RunPreplannedDrtExample.java @@ -43,7 +43,7 @@ public static void run(URL configUrl, boolean otfvis, int lastIteration, Map preplannedSchedulesByMode) { Config config = ConfigUtils.loadConfig(configUrl, new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); Controler controler = PreplannedDrtControlerCreator.createControler(config, otfvis); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/DrtTestScenario.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/DrtTestScenario.java index 4ca143f3cf3..7131c33a368 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/DrtTestScenario.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/DrtTestScenario.java @@ -17,19 +17,21 @@ import org.matsim.contrib.vsp.scenario.SnzActivities; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.simwrapper.SimWrapperModule; +import org.matsim.modechoice.InformedModeChoiceConfigGroup; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.VehicleType; import javax.annotation.Nullable; import java.net.URL; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.function.Consumer; @@ -65,8 +67,8 @@ public static Config loadConfig(MatsimTestUtils utils) { URL context = ExamplesUtils.getTestScenarioURL("kelheim"); Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(context, "config-with-drt.xml")); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); return config; } @@ -76,19 +78,21 @@ protected Config prepareConfig(Config config) { SnzActivities.addScoringParams(config); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("car interaction").setTypicalDuration(60)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("other").setTypicalDuration(600 * 3)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("car interaction").setTypicalDuration(60)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("other").setTypicalDuration(600 * 3)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("freight_start").setTypicalDuration(60 * 15)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("freight_end").setTypicalDuration(60 * 15)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("freight_start").setTypicalDuration(60 * 15)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("freight_end").setTypicalDuration(60 * 15)); + InformedModeChoiceConfigGroup imc = ConfigUtils.addOrGetModule(config, InformedModeChoiceConfigGroup.class); + imc.setModes(Set.of("drt", "av", "car", "pt", "bike", "walk")); MultiModeDrtConfigGroup multiModeDrtConfig = ConfigUtils.addOrGetModule(config, MultiModeDrtConfigGroup.class); ConfigUtils.addOrGetModule(config, DvrpConfigGroup.class); - DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.planCalcScore(), config.plansCalcRoute()); + DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); prepareConfig.accept(config); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/companions/RunDrtWithCompanionExampleIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/companions/RunDrtWithCompanionExampleIT.java index de5534ab0e7..9ac24985fe4 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/companions/RunDrtWithCompanionExampleIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/companions/RunDrtWithCompanionExampleIT.java @@ -24,9 +24,7 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.stream.Collectors; import org.assertj.core.api.Assertions; @@ -64,8 +62,8 @@ public void testRunDrtWithCompanions() { DrtWithExtensionsConfigGroup drtWithExtensionsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.getModalElements().iterator().next(); drtWithExtensionsConfigGroup.addParameterSet(new DrtCompanionParams()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Controler controler = DrtCompanionControlerCreator.createControler(config); controler.run(); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/dashboards/DashboardTests.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/dashboards/DashboardTests.java index 43e8f7dfffe..c26a623fec8 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/dashboards/DashboardTests.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/dashboards/DashboardTests.java @@ -23,9 +23,9 @@ public class DashboardTests { private void run() { Config config = DrtTestScenario.loadConfig(utils); - config.controler().setLastIteration(4); - config.controler().setWritePlansInterval(4); - config.controler().setWriteEventsInterval(4); + config.controller().setLastIteration(4); + config.controller().setWritePlansInterval(4); + config.controller().setWriteEventsInterval(4); SimWrapperConfigGroup group = ConfigUtils.addOrGetModule(config, SimWrapperConfigGroup.class); group.defaultParams().sampleSize = 0.001; diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/estimator/MultiModalDrtLegEstimatorTest.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/estimator/MultiModalDrtLegEstimatorTest.java new file mode 100644 index 00000000000..8d61ef68123 --- /dev/null +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/estimator/MultiModalDrtLegEstimatorTest.java @@ -0,0 +1,90 @@ +package org.matsim.contrib.drt.extension.estimator; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.matsim.application.MATSimApplication; +import org.matsim.contrib.drt.extension.DrtTestScenario; +import org.matsim.contrib.drt.extension.estimator.run.DrtEstimatorConfigGroup; +import org.matsim.contrib.drt.extension.estimator.run.DrtEstimatorModule; +import org.matsim.contrib.drt.extension.estimator.run.MultiModeDrtEstimatorConfigGroup; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.controler.Controler; +import org.matsim.modechoice.InformedModeChoiceModule; +import org.matsim.modechoice.ModeOptions; +import org.matsim.modechoice.estimators.DefaultLegScoreEstimator; +import org.matsim.modechoice.estimators.FixedCostsEstimator; +import org.matsim.testcases.MatsimTestUtils; + +import java.io.File; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MultiModalDrtLegEstimatorTest { + + @Rule + public MatsimTestUtils utils = new MatsimTestUtils(); + + private Controler controler; + + @Before + public void setUp() throws Exception { + + Config config = DrtTestScenario.loadConfig(utils); + + config.controller().setLastIteration(3); + + controler = MATSimApplication.prepare(new DrtTestScenario(MultiModalDrtLegEstimatorTest::prepare, MultiModalDrtLegEstimatorTest::prepare), config); + } + + private static void prepare(Controler controler) { + InformedModeChoiceModule.Builder builder = InformedModeChoiceModule.newBuilder() + .withFixedCosts(FixedCostsEstimator.DailyConstant.class, "car") + .withLegEstimator(DefaultLegScoreEstimator.class, ModeOptions.AlwaysAvailable.class, "bike", "walk", "pt") + .withLegEstimator(DefaultLegScoreEstimator.class, ModeOptions.ConsiderYesAndNo.class, "car") + .withLegEstimator(MultiModalDrtLegEstimator.class, ModeOptions.AlwaysAvailable.class, "drt", "av"); + + controler.addOverridingModule(builder.build()); + controler.addOverridingModule(new DrtEstimatorModule()); + } + + private static void prepare(Config config) { + + MultiModeDrtEstimatorConfigGroup estimators = ConfigUtils.addOrGetModule(config, MultiModeDrtEstimatorConfigGroup.class); + + estimators.addParameterSet(new DrtEstimatorConfigGroup("drt")); + estimators.addParameterSet(new DrtEstimatorConfigGroup("av")); + + // Set subtour mode selection as strategy + List strategies = config.replanning().getStrategySettings().stream() + .filter(s -> !s.getStrategyName().toLowerCase().contains("mode") + ).collect(Collectors.toList()); + + strategies.add(new ReplanningConfigGroup.StrategySettings() + .setStrategyName(InformedModeChoiceModule.SELECT_SUBTOUR_MODE_STRATEGY) + .setSubpopulation("person") + .setWeight(0.2)); + + config.replanning().clearStrategySettings(); + strategies.forEach(s -> config.replanning().addStrategySettings(s)); + + } + + @Test + public void run() { + + String out = utils.getOutputDirectory(); + + controler.run(); + + assertThat(new File(out, "kelheim-mini-drt.drt_estimates_drt.csv")) + .exists() + .isNotEmpty(); + + + } +} diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java index 8e1f14d6531..c5ea83cbce9 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java @@ -20,9 +20,9 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -91,10 +91,10 @@ public void test() { modes.add("drt"); config.travelTimeCalculator().setAnalyzedModes(modes); - PlanCalcScoreConfigGroup.ModeParams scoreParams = new PlanCalcScoreConfigGroup.ModeParams("drt"); - config.planCalcScore().addModeParams(scoreParams); - PlanCalcScoreConfigGroup.ModeParams scoreParams2 = new PlanCalcScoreConfigGroup.ModeParams("walk"); - config.planCalcScore().addModeParams(scoreParams2); + ScoringConfigGroup.ModeParams scoreParams = new ScoringConfigGroup.ModeParams("drt"); + config.scoring().addModeParams(scoreParams); + ScoringConfigGroup.ModeParams scoreParams2 = new ScoringConfigGroup.ModeParams("walk"); + config.scoring().addModeParams(scoreParams2); config.plans().setInputFile(plansFile); config.network().setInputFile(networkFile); @@ -102,33 +102,33 @@ public void test() { config.qsim().setSimStarttimeInterpretation(QSimConfigGroup.StarttimeInterpretation.onlyUseStarttime); config.qsim().setSimEndtimeInterpretation(QSimConfigGroup.EndtimeInterpretation.minOfEndtimeAndMobsimFinished); - final PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + final ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setTypicalDuration(8 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams other = new PlanCalcScoreConfigGroup.ActivityParams("other"); + final ScoringConfigGroup.ActivityParams other = new ScoringConfigGroup.ActivityParams("other"); other.setTypicalDuration(4 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams education = new PlanCalcScoreConfigGroup.ActivityParams("education"); + final ScoringConfigGroup.ActivityParams education = new ScoringConfigGroup.ActivityParams("education"); education.setTypicalDuration(6 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams shopping = new PlanCalcScoreConfigGroup.ActivityParams("shopping"); + final ScoringConfigGroup.ActivityParams shopping = new ScoringConfigGroup.ActivityParams("shopping"); shopping.setTypicalDuration(2 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + final ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setTypicalDuration(2 * 3600); - config.planCalcScore().addActivityParams(home); - config.planCalcScore().addActivityParams(other); - config.planCalcScore().addActivityParams(education); - config.planCalcScore().addActivityParams(shopping); - config.planCalcScore().addActivityParams(work); + config.scoring().addActivityParams(home); + config.scoring().addActivityParams(other); + config.scoring().addActivityParams(education); + config.scoring().addActivityParams(shopping); + config.scoring().addActivityParams(work); - final StrategyConfigGroup.StrategySettings stratSets = new StrategyConfigGroup.StrategySettings(); + final ReplanningConfigGroup.StrategySettings stratSets = new ReplanningConfigGroup.StrategySettings(); stratSets.setWeight(1); stratSets.setStrategyName("ChangeExpBeta"); - config.strategy().addStrategySettings(stratSets); + config.replanning().addStrategySettings(stratSets); - config.controler().setLastIteration(2); - config.controler().setWriteEventsInterval(1); + config.controller().setLastIteration(2); + config.controller().setWriteEventsInterval(1); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory("test/output/holzkirchen_shifts"); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory("test/output/holzkirchen_shifts"); DrtOperationsParams operationsParams = (DrtOperationsParams) drtWithShiftsConfigGroup.createParameterSet(DrtOperationsParams.SET_NAME); ShiftsParams shiftsParams = (ShiftsParams) operationsParams.createParameterSet(ShiftsParams.SET_NAME); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java index 1f57b4d54c7..4abe57ba415 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java @@ -20,9 +20,9 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -94,10 +94,10 @@ public void test() { modes.add("drt"); config.travelTimeCalculator().setAnalyzedModes(modes); - PlanCalcScoreConfigGroup.ModeParams scoreParams = new PlanCalcScoreConfigGroup.ModeParams("drt"); - config.planCalcScore().addModeParams(scoreParams); - PlanCalcScoreConfigGroup.ModeParams scoreParams2 = new PlanCalcScoreConfigGroup.ModeParams("walk"); - config.planCalcScore().addModeParams(scoreParams2); + ScoringConfigGroup.ModeParams scoreParams = new ScoringConfigGroup.ModeParams("drt"); + config.scoring().addModeParams(scoreParams); + ScoringConfigGroup.ModeParams scoreParams2 = new ScoringConfigGroup.ModeParams("walk"); + config.scoring().addModeParams(scoreParams2); config.plans().setInputFile(plansFile); config.network().setInputFile(networkFile); @@ -106,33 +106,33 @@ public void test() { config.qsim().setSimEndtimeInterpretation(QSimConfigGroup.EndtimeInterpretation.minOfEndtimeAndMobsimFinished); - final PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + final ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setTypicalDuration(8 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams other = new PlanCalcScoreConfigGroup.ActivityParams("other"); + final ScoringConfigGroup.ActivityParams other = new ScoringConfigGroup.ActivityParams("other"); other.setTypicalDuration(4 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams education = new PlanCalcScoreConfigGroup.ActivityParams("education"); + final ScoringConfigGroup.ActivityParams education = new ScoringConfigGroup.ActivityParams("education"); education.setTypicalDuration(6 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams shopping = new PlanCalcScoreConfigGroup.ActivityParams("shopping"); + final ScoringConfigGroup.ActivityParams shopping = new ScoringConfigGroup.ActivityParams("shopping"); shopping.setTypicalDuration(2 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + final ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setTypicalDuration(2 * 3600); - config.planCalcScore().addActivityParams(home); - config.planCalcScore().addActivityParams(other); - config.planCalcScore().addActivityParams(education); - config.planCalcScore().addActivityParams(shopping); - config.planCalcScore().addActivityParams(work); + config.scoring().addActivityParams(home); + config.scoring().addActivityParams(other); + config.scoring().addActivityParams(education); + config.scoring().addActivityParams(shopping); + config.scoring().addActivityParams(work); - final StrategyConfigGroup.StrategySettings stratSets = new StrategyConfigGroup.StrategySettings(); + final ReplanningConfigGroup.StrategySettings stratSets = new ReplanningConfigGroup.StrategySettings(); stratSets.setWeight(1); stratSets.setStrategyName("ChangeExpBeta"); - config.strategy().addStrategySettings(stratSets); + config.replanning().addStrategySettings(stratSets); - config.controler().setLastIteration(1); - config.controler().setWriteEventsInterval(1); + config.controller().setLastIteration(1); + config.controller().setWriteEventsInterval(1); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory("test/output/holzkirchen_eshifts"); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory("test/output/holzkirchen_eshifts"); DrtOperationsParams operationsParams = (DrtOperationsParams) drtWithShiftsConfigGroup.createParameterSet(DrtOperationsParams.SET_NAME); ShiftsParams shiftsParams = (ShiftsParams) operationsParams.createParameterSet(ShiftsParams.SET_NAME); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java index 8b0e6b3a179..91c2dd16be9 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java @@ -17,9 +17,9 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.examples.ExamplesUtils; @@ -83,10 +83,10 @@ public void test() { modes.add("drt"); config.travelTimeCalculator().setAnalyzedModes(modes); - PlanCalcScoreConfigGroup.ModeParams scoreParams = new PlanCalcScoreConfigGroup.ModeParams("drt"); - config.planCalcScore().addModeParams(scoreParams); - PlanCalcScoreConfigGroup.ModeParams scoreParams2 = new PlanCalcScoreConfigGroup.ModeParams("walk"); - config.planCalcScore().addModeParams(scoreParams2); + ScoringConfigGroup.ModeParams scoreParams = new ScoringConfigGroup.ModeParams("drt"); + config.scoring().addModeParams(scoreParams); + ScoringConfigGroup.ModeParams scoreParams2 = new ScoringConfigGroup.ModeParams("walk"); + config.scoring().addModeParams(scoreParams2); config.plans().setInputFile(plansFile); config.network().setInputFile(networkFile); @@ -95,33 +95,33 @@ public void test() { config.qsim().setSimEndtimeInterpretation(QSimConfigGroup.EndtimeInterpretation.minOfEndtimeAndMobsimFinished); - final PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + final ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setTypicalDuration(8 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams other = new PlanCalcScoreConfigGroup.ActivityParams("other"); + final ScoringConfigGroup.ActivityParams other = new ScoringConfigGroup.ActivityParams("other"); other.setTypicalDuration(4 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams education = new PlanCalcScoreConfigGroup.ActivityParams("education"); + final ScoringConfigGroup.ActivityParams education = new ScoringConfigGroup.ActivityParams("education"); education.setTypicalDuration(6 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams shopping = new PlanCalcScoreConfigGroup.ActivityParams("shopping"); + final ScoringConfigGroup.ActivityParams shopping = new ScoringConfigGroup.ActivityParams("shopping"); shopping.setTypicalDuration(2 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + final ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setTypicalDuration(2 * 3600); - config.planCalcScore().addActivityParams(home); - config.planCalcScore().addActivityParams(other); - config.planCalcScore().addActivityParams(education); - config.planCalcScore().addActivityParams(shopping); - config.planCalcScore().addActivityParams(work); + config.scoring().addActivityParams(home); + config.scoring().addActivityParams(other); + config.scoring().addActivityParams(education); + config.scoring().addActivityParams(shopping); + config.scoring().addActivityParams(work); - final StrategyConfigGroup.StrategySettings stratSets = new StrategyConfigGroup.StrategySettings(); + final ReplanningConfigGroup.StrategySettings stratSets = new ReplanningConfigGroup.StrategySettings(); stratSets.setWeight(1); stratSets.setStrategyName("ChangeExpBeta"); - config.strategy().addStrategySettings(stratSets); + config.replanning().addStrategySettings(stratSets); - config.controler().setLastIteration(1); - config.controler().setWriteEventsInterval(1); + config.controller().setLastIteration(1); + config.controller().setWriteEventsInterval(1); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory("test/output/holzkirchen_shifts_multiHub"); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory("test/output/holzkirchen_shifts_multiHub"); DrtOperationsParams operationsParams = (DrtOperationsParams) drtWithShiftsConfigGroup.createParameterSet(DrtOperationsParams.SET_NAME); ShiftsParams shiftsParams = (ShiftsParams) operationsParams.createParameterSet(ShiftsParams.SET_NAME); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java index 3205bae0a4f..e6b9caf51af 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java @@ -17,9 +17,9 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.examples.ExamplesUtils; @@ -84,10 +84,10 @@ public void test() { modes.add("drt"); config.travelTimeCalculator().setAnalyzedModes(modes); - PlanCalcScoreConfigGroup.ModeParams scoreParams = new PlanCalcScoreConfigGroup.ModeParams("drt"); - config.planCalcScore().addModeParams(scoreParams); - PlanCalcScoreConfigGroup.ModeParams scoreParams2 = new PlanCalcScoreConfigGroup.ModeParams("walk"); - config.planCalcScore().addModeParams(scoreParams2); + ScoringConfigGroup.ModeParams scoreParams = new ScoringConfigGroup.ModeParams("drt"); + config.scoring().addModeParams(scoreParams); + ScoringConfigGroup.ModeParams scoreParams2 = new ScoringConfigGroup.ModeParams("walk"); + config.scoring().addModeParams(scoreParams2); config.plans().setInputFile(plansFile); config.network().setInputFile(networkFile); @@ -95,33 +95,33 @@ public void test() { config.qsim().setSimStarttimeInterpretation(QSimConfigGroup.StarttimeInterpretation.onlyUseStarttime); config.qsim().setSimEndtimeInterpretation(QSimConfigGroup.EndtimeInterpretation.minOfEndtimeAndMobsimFinished); - final PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + final ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setTypicalDuration(8 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams other = new PlanCalcScoreConfigGroup.ActivityParams("other"); + final ScoringConfigGroup.ActivityParams other = new ScoringConfigGroup.ActivityParams("other"); other.setTypicalDuration(4 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams education = new PlanCalcScoreConfigGroup.ActivityParams("education"); + final ScoringConfigGroup.ActivityParams education = new ScoringConfigGroup.ActivityParams("education"); education.setTypicalDuration(6 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams shopping = new PlanCalcScoreConfigGroup.ActivityParams("shopping"); + final ScoringConfigGroup.ActivityParams shopping = new ScoringConfigGroup.ActivityParams("shopping"); shopping.setTypicalDuration(2 * 3600); - final PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + final ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setTypicalDuration(2 * 3600); - config.planCalcScore().addActivityParams(home); - config.planCalcScore().addActivityParams(other); - config.planCalcScore().addActivityParams(education); - config.planCalcScore().addActivityParams(shopping); - config.planCalcScore().addActivityParams(work); + config.scoring().addActivityParams(home); + config.scoring().addActivityParams(other); + config.scoring().addActivityParams(education); + config.scoring().addActivityParams(shopping); + config.scoring().addActivityParams(work); - final StrategyConfigGroup.StrategySettings stratSets = new StrategyConfigGroup.StrategySettings(); + final ReplanningConfigGroup.StrategySettings stratSets = new ReplanningConfigGroup.StrategySettings(); stratSets.setWeight(1); stratSets.setStrategyName("ChangeExpBeta"); - config.strategy().addStrategySettings(stratSets); + config.replanning().addStrategySettings(stratSets); - config.controler().setLastIteration(1); - config.controler().setWriteEventsInterval(1); + config.controller().setLastIteration(1); + config.controller().setWriteEventsInterval(1); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory("test/output/holzkirchen_shifts"); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory("test/output/holzkirchen_shifts"); DrtOperationsParams operationsParams = (DrtOperationsParams) drtWithShiftsConfigGroup.createParameterSet(DrtOperationsParams.SET_NAME); ShiftsParams shiftsParams = (ShiftsParams) operationsParams.createParameterSet(ShiftsParams.SET_NAME); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/prebooking/PrebookingExampleIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/prebooking/PrebookingExampleIT.java index 2d661909863..931b8efd61b 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/prebooking/PrebookingExampleIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/prebooking/PrebookingExampleIT.java @@ -7,17 +7,13 @@ import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.IdMap; import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.edrt.optimizer.EDrtVehicleDataEntryFactory.EDrtVehicleDataEntryFactoryProvider; import org.matsim.contrib.drt.extension.edrt.run.EDrtControlerCreator; import org.matsim.contrib.drt.extension.prebooking.logic.FixedSharePrebookingLogic; -import org.matsim.contrib.drt.passenger.events.DrtRequestSubmittedEvent; -import org.matsim.contrib.drt.passenger.events.DrtRequestSubmittedEventHandler; import org.matsim.contrib.drt.run.DrtConfigGroup; import org.matsim.contrib.drt.run.DrtControlerCreator; import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; -import org.matsim.contrib.dvrp.optimizer.Request; import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEvent; import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEventHandler; import org.matsim.contrib.dvrp.passenger.PassengerRequestScheduledEvent; @@ -61,8 +57,8 @@ public void testDrtWithPrebooking() { extensionsConfig.addParameterSet(prebookingParams); } - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Controler controller = DrtControlerCreator.createControler(config, false); controller.addOverridingModule(new PrebookingModule()); @@ -89,8 +85,8 @@ public void testElectricDrtWithPrebooking() { new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new), new DvrpConfigGroup(), new OTFVisConfigGroup(), new EvConfigGroup()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Controler controler = EDrtControlerCreator.createControler(config, false); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/prebooking/PrebookingTestEnvironment.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/prebooking/PrebookingTestEnvironment.java index 2e9d7493bd5..f136290c3c2 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/prebooking/PrebookingTestEnvironment.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/prebooking/PrebookingTestEnvironment.java @@ -51,10 +51,10 @@ import org.matsim.contrib.dvrp.vrpagent.TaskStartedEventHandler; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; import org.matsim.core.config.groups.QSimConfigGroup.EndtimeInterpretation; import org.matsim.core.config.groups.QSimConfigGroup.StarttimeInterpretation; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -206,9 +206,9 @@ private void buildController(Controler controller) { } private void buildConfig(Config config) { - config.controler().setOutputDirectory("drt_test_output"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOutputDirectory("drt_test_output"); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); config.qsim().setStartTime(0.0); config.qsim().setSimStarttimeInterpretation(StarttimeInterpretation.onlyUseStarttime); @@ -217,11 +217,11 @@ private void buildConfig(Config config) { config.qsim().setSimEndtimeInterpretation(EndtimeInterpretation.onlyUseEndtime); ModeParams drtParams = new ModeParams("drt"); - config.planCalcScore().addModeParams(drtParams); + config.scoring().addModeParams(drtParams); ActivityParams genericParams = new ActivityParams("generic"); genericParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(genericParams); + config.scoring().addActivityParams(genericParams); DvrpConfigGroup dvrpConfig = new DvrpConfigGroup(); config.addModule(dvrpConfig); @@ -243,7 +243,7 @@ private void buildConfig(Config config) { DrtInsertionSearchParams searchParams = new SelectiveInsertionSearchParams(); modeConfig.addDrtInsertionSearchParams(searchParams); - DrtConfigs.adjustMultiModeDrtConfig(drtConfig, config.planCalcScore(), config.plansCalcRoute()); + DrtConfigs.adjustMultiModeDrtConfig(drtConfig, config.scoring(), config.routing()); } private void buildPopulation(Scenario scenario) { diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/DrtAnalysisControlerListener.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/DrtAnalysisControlerListener.java index fe767004ce0..62f9a26f467 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/DrtAnalysisControlerListener.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/DrtAnalysisControlerListener.java @@ -110,7 +110,7 @@ public class DrtAnalysisControlerListener implements IterationEndsListener, Shut this.vehicleOccupancyProfileCalculator = vehicleOccupancyProfileCalculator; this.drtCfg = drtCfg; this.qSimCfg = config.qsim(); - runId = Optional.ofNullable(config.controler().getRunId()).orElse(notAvailableString); + runId = Optional.ofNullable(config.controller().getRunId()).orElse(notAvailableString); maxcap = findMaxVehicleCapacity(fleet); format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); @@ -155,7 +155,7 @@ private static DrtLeg newDrtLeg(EventSequence sequence, Function, ? ext @Override public void notifyIterationEnds(IterationEndsEvent event) { - boolean createGraphs = event.getServices().getConfig().controler().isCreateGraphs(); + boolean createGraphs = event.getServices().getConfig().controller().isCreateGraphs(); writeAndPlotWaitTimeEstimateComparison(drtEventSequenceCollector.getPerformedRequestSequences().values(), filename(event, "waitTimeComparison", ".png"), filename(event, "waitTimeComparison", ".csv"), createGraphs); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/routing/MultiModeDrtMainModeIdentifier.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/routing/MultiModeDrtMainModeIdentifier.java index 549a4761a13..6fb846726ab 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/routing/MultiModeDrtMainModeIdentifier.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/routing/MultiModeDrtMainModeIdentifier.java @@ -31,7 +31,7 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.contrib.drt.run.DrtConfigGroup; import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.MainModeIdentifier; import org.matsim.core.router.MainModeIdentifierImpl; import org.matsim.core.router.TripRouter; @@ -49,7 +49,7 @@ public MultiModeDrtMainModeIdentifier(MultiModeDrtConfigGroup drtCfg) { stageActivityTypeToDrtMode = drtCfg.getModalElements() .stream() .map(DrtConfigGroup::getMode) - .collect(Collectors.toMap(PlanCalcScoreConfigGroup::createStageActivityType, s -> s)); + .collect(Collectors.toMap(ScoringConfigGroup::createStageActivityType, s -> s)); // #deleteBeforeRelease : only used to retrofit plans created since the merge of fallback routing module (sep'-dec'19) fallbackModeToDrtMode = drtCfg.getModalElements() diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtConfigGroup.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtConfigGroup.java index 7b564e1746b..ea39c0cdc42 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtConfigGroup.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtConfigGroup.java @@ -43,8 +43,8 @@ import org.matsim.contrib.dvrp.run.Modal; import org.matsim.contrib.util.ReflectiveConfigGroupWithConfigurableParameterSets; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import com.google.common.base.Preconditions; import com.google.common.base.Verify; @@ -332,7 +332,7 @@ public Optional getDrtRequestInsertionRetryParam } /** - * Convenience method that brings syntax closer to syntax in, e.g., {@link PlansCalcRouteConfigGroup} or {@link PlanCalcScoreConfigGroup} + * Convenience method that brings syntax closer to syntax in, e.g., {@link RoutingConfigGroup} or {@link ScoringConfigGroup} */ public final void addDrtInsertionSearchParams(final DrtInsertionSearchParams pars) { addParameterSet(pars); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtConfigs.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtConfigs.java index 92d29a97d42..dccfb2d7449 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtConfigs.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtConfigs.java @@ -22,8 +22,8 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; /** * @author Michal Maciejewski (michalm) @@ -32,22 +32,22 @@ public class DrtConfigs { private static final Logger LOGGER = LogManager.getLogger(DrtControlerCreator.class); public static void adjustMultiModeDrtConfig(MultiModeDrtConfigGroup multiModeDrtCfg, - PlanCalcScoreConfigGroup planCalcScoreCfg, PlansCalcRouteConfigGroup plansCalcRouteCfg) { + ScoringConfigGroup planCalcScoreCfg, RoutingConfigGroup plansCalcRouteCfg) { for (DrtConfigGroup drtCfg : multiModeDrtCfg.getModalElements()) { DrtConfigs.adjustDrtConfig(drtCfg, planCalcScoreCfg, plansCalcRouteCfg); } } - public static void adjustDrtConfig(DrtConfigGroup drtCfg, PlanCalcScoreConfigGroup planCalcScoreCfg, - PlansCalcRouteConfigGroup plansCalcRouteCfg) { - String drtStageActivityType = PlanCalcScoreConfigGroup.createStageActivityType(drtCfg.getMode()); + public static void adjustDrtConfig(DrtConfigGroup drtCfg, ScoringConfigGroup planCalcScoreCfg, + RoutingConfigGroup plansCalcRouteCfg) { + String drtStageActivityType = ScoringConfigGroup.createStageActivityType(drtCfg.getMode()); if (planCalcScoreCfg.getActivityParams(drtStageActivityType) == null) { addDrtStageActivityParams(planCalcScoreCfg, drtStageActivityType); } } - private static void addDrtStageActivityParams(PlanCalcScoreConfigGroup planCalcScoreCfg, String stageActivityType) { - PlanCalcScoreConfigGroup.ActivityParams params = new PlanCalcScoreConfigGroup.ActivityParams(stageActivityType); + private static void addDrtStageActivityParams(ScoringConfigGroup planCalcScoreCfg, String stageActivityType) { + ScoringConfigGroup.ActivityParams params = new ScoringConfigGroup.ActivityParams(stageActivityType); params.setTypicalDuration(1); params.setScoringThisActivityAtAll(false); planCalcScoreCfg.getScoringParametersPerSubpopulation().values().forEach(k -> k.addActivityParams(params)); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java index 7c28080f46f..ab438acc805 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java @@ -61,7 +61,7 @@ public static Scenario createScenarioWithDrtRouteFactory(Config config) { */ public static Controler createControler(Config config, boolean otfvis) { MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.planCalcScore(), config.plansCalcRoute()); + DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); Scenario scenario = createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); 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 e4df7dd4981..827d2d4fd41 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 @@ -79,7 +79,7 @@ public void install() { drtCfg.getDrtSpeedUpParams().ifPresent(drtSpeedUpParams -> { bindModal(DrtSpeedUp.class).toProvider(modalProvider( - getter -> new DrtSpeedUp(getMode(), drtSpeedUpParams, getConfig().controler(), + getter -> new DrtSpeedUp(getMode(), drtSpeedUpParams, getConfig().controller(), getter.get(Network.class), getter.getModal(FleetSpecification.class), getter.getModal(DrtEventSequenceCollector.class)))).asEagerSingleton(); addControlerListenerBinding().to(modalKey(DrtSpeedUp.class)); @@ -92,7 +92,7 @@ public void install() { bindModal(DefaultStopTimeCalculator.class).toProvider(modalProvider(getter -> { return new DefaultStopTimeCalculator(drtCfg.stopDuration); })).in(Singleton.class); - + bindModal(StopTimeCalculator.class).to(modalKey(DefaultStopTimeCalculator.class)); install(new AdaptiveTravelTimeMatrixModule(drtCfg.mode)); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtModeQSimModule.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtModeQSimModule.java index ffbe7f67537..ecaaf5b4065 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtModeQSimModule.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtModeQSimModule.java @@ -55,7 +55,7 @@ public DrtModeQSimModule(DrtConfigGroup drtCfg, AbstractQSimModule optimizerQSim @Override protected void configureQSim() { boolean teleportDrtUsers = drtCfg.getDrtSpeedUpParams().isPresent() && DrtSpeedUp.isTeleportDrtUsers( - drtCfg.getDrtSpeedUpParams().get(), getConfig().controler(), getIterationNumber()); + drtCfg.getDrtSpeedUpParams().get(), getConfig().controller(), getIterationNumber()); if (teleportDrtUsers) { install(new PassengerEngineQSimModule(getMode(), PassengerEngineQSimModule.PassengerEngineType.TELEPORTING)); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/examples/RunMultiModeDrtExample.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/examples/RunMultiModeDrtExample.java index 53da0c974db..8452181b4c2 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/examples/RunMultiModeDrtExample.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/examples/RunMultiModeDrtExample.java @@ -41,7 +41,7 @@ public class RunMultiModeDrtExample { public static void run(URL configUrl, boolean otfvis, int lastIteration) { Config config = ConfigUtils.loadConfig(configUrl, new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); Controler controler = DrtControlerCreator.createControler(config, otfvis); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/examples/RunOneSharedTaxiExample.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/examples/RunOneSharedTaxiExample.java index 9ca1f9f3452..3ce549d1ac7 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/examples/RunOneSharedTaxiExample.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/examples/RunOneSharedTaxiExample.java @@ -35,8 +35,8 @@ public class RunOneSharedTaxiExample { public static void run(URL configUrl, boolean otfvis, int lastIteration) { Config config = ConfigUtils.loadConfig(configUrl, new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setLastIteration(lastIteration); - config.controler().setWriteEventsInterval(lastIteration); + config.controller().setLastIteration(lastIteration); + config.controller().setWriteEventsInterval(lastIteration); DrtControlerCreator.createControler(config, otfvis).run(); } } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/speedup/DrtSpeedUp.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/speedup/DrtSpeedUp.java index 13da140a338..978ddbc7417 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/speedup/DrtSpeedUp.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/speedup/DrtSpeedUp.java @@ -34,7 +34,7 @@ import org.matsim.contrib.drt.passenger.events.DrtRequestSubmittedEvent; import org.matsim.contrib.drt.speedup.DrtSpeedUpParams.WaitingTimeUpdateDuringSpeedUp; import org.matsim.contrib.dvrp.fleet.FleetSpecification; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.controler.events.IterationStartsEvent; import org.matsim.core.controler.listener.IterationEndsListener; @@ -49,7 +49,7 @@ public final class DrtSpeedUp implements IterationStartsListener, IterationEndsListener { private static final Logger log = LogManager.getLogger(DrtSpeedUp.class); - public static boolean isTeleportDrtUsers(DrtSpeedUpParams drtSpeedUpParams, ControlerConfigGroup controlerConfig, + public static boolean isTeleportDrtUsers(DrtSpeedUpParams drtSpeedUpParams, ControllerConfigGroup controlerConfig, int iteration) { int lastIteration = controlerConfig.getLastIteration(); if (iteration < drtSpeedUpParams.fractionOfIterationsSwitchOn * lastIteration @@ -63,7 +63,7 @@ public static boolean isTeleportDrtUsers(DrtSpeedUpParams drtSpeedUpParams, Cont private final String mode; private final DrtSpeedUpParams drtSpeedUpParams; - private final ControlerConfigGroup controlerConfig; + private final ControllerConfigGroup controlerConfig; private final Network network; private final FleetSpecification fleetSpecification; private final DrtEventSequenceCollector drtEventSequenceCollector; @@ -76,7 +76,7 @@ public static boolean isTeleportDrtUsers(DrtSpeedUpParams drtSpeedUpParams, Cont private double currentAvgWaitingTime; private double currentAvgInVehicleBeelineSpeed; - public DrtSpeedUp(String mode, DrtSpeedUpParams drtSpeedUpParams, ControlerConfigGroup controlerConfig, + public DrtSpeedUp(String mode, DrtSpeedUpParams drtSpeedUpParams, ControllerConfigGroup controlerConfig, Network network, FleetSpecification fleetSpecification, DrtEventSequenceCollector drtEventSequenceCollector) { this.mode = mode; diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/speedup/DrtTeleportedRouteCalculator.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/speedup/DrtTeleportedRouteCalculator.java index 7935a2403e8..eca53f0c0d7 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/speedup/DrtTeleportedRouteCalculator.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/speedup/DrtTeleportedRouteCalculator.java @@ -40,6 +40,12 @@ public class DrtTeleportedRouteCalculator implements TeleportedRouteCalculator { this.averageInVehicleBeelineSpeed = averageInVehicleBeelineSpeed; } + // TODO: from discussion from michal and rakow + // speedup is currently using very simple and not exchangeable estimators + // it could be possible to integrate the drt estimators used by the informed mode-choice + // this router should probably not use the beeline distance but the direct travel route + // speed-up would still be significant (oct'23) + @Override public Route calculateRoute(PassengerRequest request) { Link startLink = request.getFromLink(); diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/DrtPoolingParameterTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/DrtPoolingParameterTest.java index 236d2889a6a..c708e623de0 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/DrtPoolingParameterTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/DrtPoolingParameterTest.java @@ -4,7 +4,6 @@ import java.util.*; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; @@ -213,9 +212,9 @@ private PersonEnterDrtVehicleEventHandler setupAndRunScenario(double maxWaitTime new OTFVisConfigGroup()); config.plans().setInputFile(null); - config.controler() + config.controller() .setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); MultiModeDrtConfigGroup mm = ConfigUtils.addOrGetModule(config, MultiModeDrtConfigGroup.class); mm.getModalElements().forEach(x -> { diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/routing/MultiModeDrtMainModeIdentifierTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/routing/MultiModeDrtMainModeIdentifierTest.java index 750f73e21d2..d9af16f9896 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/routing/MultiModeDrtMainModeIdentifierTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/routing/MultiModeDrtMainModeIdentifierTest.java @@ -14,7 +14,7 @@ import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.population.PopulationUtils; import org.matsim.core.router.TripRouter; @@ -43,7 +43,7 @@ public void test() { Assert.assertEquals(drtMode, mmi.identifyMainMode(testElements)); } { - String drtStageActivityType = PlanCalcScoreConfigGroup.createStageActivityType(drtMode); + String drtStageActivityType = ScoringConfigGroup.createStageActivityType(drtMode); List testElements = new ArrayList<>(); // #deleteBeforeRelease : only used to retrofit plans created since the merge of fallback routing module (sep'-dec'19) diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/run/examples/RunDrtExampleIT.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/run/examples/RunDrtExampleIT.java index 492b8da4640..7d3efcf51c6 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/run/examples/RunDrtExampleIT.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/run/examples/RunDrtExampleIT.java @@ -78,8 +78,8 @@ public void testRunDrtExampleWithNoRejections_ExtensiveSearch() { drtCfg.rejectRequestIfMaxWaitOrTravelTimeViolated = false; } - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); RunDrtExample.run(config, false); var expectedStats = Stats.newBuilder() @@ -112,8 +112,8 @@ public void testRunDrtExampleWithNoRejections_SelectiveSearch() { drtCfg.rejectRequestIfMaxWaitOrTravelTimeViolated = false; } - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); RunDrtExample.run(config, false); var expectedStats = Stats.newBuilder() @@ -146,9 +146,9 @@ public void testRunDrtExampleWithNoRejections_RepeatedSelectiveSearch() { drtCfg.rejectRequestIfMaxWaitOrTravelTimeViolated = false; } - config.controler().setLastIteration(3); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(3); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); RunDrtExample.run(config, false); var expectedStats = Stats.newBuilder() @@ -176,8 +176,8 @@ public void testRunDrtExampleWithRequestRetry() { drtCfg.addParameterSet(drtRequestInsertionRetryParams); } - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); RunDrtExample.run(config, false); var expectedStats = Stats.newBuilder() @@ -199,8 +199,8 @@ public void testRunDrtStopbasedExample() { Config config = ConfigUtils.loadConfig(configUrl, new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); RunDrtExample.run(config, false); var expectedStats = Stats.newBuilder() @@ -213,19 +213,19 @@ public void testRunDrtStopbasedExample() { verifyDrtCustomerStatsCloseToExpectedStats(utils.getOutputDirectory(), expectedStats); } - + @Test - public void testRunDrtStopbasedExampleWithFlexibleStopDuration() { + public void testRunDrtStopbasedExampleWithFlexibleStopDuration() { Id.resetCaches(); URL configUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("mielec"), "mielec_stop_based_drt_config.xml"); Config config = ConfigUtils.loadConfig(configUrl, new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - - Controler controller = DrtControlerCreator.createControler(config, false); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + + Controler controller = DrtControlerCreator.createControler(config, false); // This snippet adds the correction against wait times smaller than the defined stopDuration controller.addOverridingModule(new AbstractDvrpModeModule("drt") { @@ -235,7 +235,7 @@ public void install() { bindModal(StopTimeCalculator.class).toInstance(stopTimeCalculator); } }); - + controller.run(); var expectedStats = Stats.newBuilder() @@ -257,8 +257,8 @@ public void testRunServiceAreabasedExampleWithSpeedUp() { Config config = ConfigUtils.loadConfig(configUrl, new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); RunDrtExample.run(config, false); var expectedStats = Stats.newBuilder() @@ -279,8 +279,8 @@ public void testRunDrtExampleWithIncrementalStopDuration() { Config config = ConfigUtils.loadConfig(configUrl, new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Controler controller = DrtControlerCreator.createControler(config, false); diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/speedup/DrtSpeedUpTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/speedup/DrtSpeedUpTest.java index c6be10bc522..0cc447f1237 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/speedup/DrtSpeedUpTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/speedup/DrtSpeedUpTest.java @@ -54,7 +54,7 @@ import org.matsim.contrib.dvrp.passenger.PassengerPickedUpEvent; import org.matsim.contrib.dvrp.passenger.PassengerRequestScheduledEvent; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.network.NetworkUtils; @@ -66,7 +66,7 @@ */ public class DrtSpeedUpTest { private final DrtSpeedUpParams drtSpeedUpParams = new DrtSpeedUpParams(); - private final ControlerConfigGroup controlerConfig = new ControlerConfigGroup(); + private final ControllerConfigGroup controlerConfig = new ControllerConfigGroup(); @Test public final void test_computeMovingAverage() { diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/util/DrtEventsReadersTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/util/DrtEventsReadersTest.java index 308e00f23a2..afc39c2e6de 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/util/DrtEventsReadersTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/util/DrtEventsReadersTest.java @@ -46,7 +46,7 @@ import org.matsim.contrib.dvrp.vrpagent.TaskStartedEvent; import org.matsim.contrib.dvrp.vrpagent.TaskStartedEventHandler; import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.algorithms.EventWriterXML; @@ -83,7 +83,7 @@ public void testReader() { eventsManager.initProcessing(); DrtEventsReaders.createEventsReader(eventsManager) .readStream(new ByteArrayInputStream(outputStream.toByteArray()), - ControlerConfigGroup.EventsFileFormat.xml); + ControllerConfigGroup.EventsFileFormat.xml); eventsManager.finishProcessing(); assertThat(handler.handledEvents).usingRecursiveFieldByFieldElementComparator() diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetaxi/RunOneTaxiExample.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetaxi/RunOneTaxiExample.java index 686ff8d9713..e151f68821c 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetaxi/RunOneTaxiExample.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetaxi/RunOneTaxiExample.java @@ -42,7 +42,7 @@ public final class RunOneTaxiExample { public static void run(URL configUrl, String taxisFile, boolean otfvis, int lastIteration) { // load config Config config = ConfigUtils.loadConfig(configUrl, new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); // load scenario Scenario scenario = ScenarioUtils.loadScenario(config); diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetaxionetruck/RunOneTaxiOneTruckExample.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetaxionetruck/RunOneTaxiOneTruckExample.java index 9c3298cde14..4c4232b15b5 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetaxionetruck/RunOneTaxiOneTruckExample.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetaxionetruck/RunOneTaxiOneTruckExample.java @@ -45,7 +45,7 @@ public class RunOneTaxiOneTruckExample { public static void run(URL configUrl, String taxisFile, String trucksFile, boolean otfvis, int lastIteration) { // load config Config config = ConfigUtils.loadConfig(configUrl, new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); // load scenario Scenario scenario = ScenarioUtils.loadScenario(config); diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetruck/RunOneTruckExample.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetruck/RunOneTruckExample.java index 5f555ce90f7..2bb198672a7 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetruck/RunOneTruckExample.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/examples/onetruck/RunOneTruckExample.java @@ -41,7 +41,7 @@ public final class RunOneTruckExample { public static void run(URL configUrl, String trucksFile, boolean otfvis, int lastIteration) { // load config Config config = ConfigUtils.loadConfig(configUrl, new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); // load scenario Scenario scenario = ScenarioUtils.loadScenario(config); diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/run/DvrpConfigGroup.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/run/DvrpConfigGroup.java index cc4b609e6cc..6d0b68cb400 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/run/DvrpConfigGroup.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/run/DvrpConfigGroup.java @@ -143,7 +143,7 @@ protected void checkConsistency(Config config) { if (config.qsim().isRemoveStuckVehicles()) { throw new RuntimeException("Stuck DynAgents cannot be removed from simulation"); } - if (!config.parallelEventHandling().getSynchronizeOnSimSteps()) { + if (!config.eventsManager().getSynchronizeOnSimSteps()) { throw new RuntimeException("Synchronization on sim steps is required"); } } diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/vrpagent/VrpAgentQueryHelper.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/vrpagent/VrpAgentQueryHelper.java index abdcc4521b3..68d6e327ed5 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/vrpagent/VrpAgentQueryHelper.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/vrpagent/VrpAgentQueryHelper.java @@ -24,6 +24,7 @@ import java.util.List; import java.util.Map; +import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; @@ -158,6 +159,36 @@ public String getType() { public void setType(String type) { throw new UnsupportedOperationException(); } + + @Override + public int getIterationCreated() { + throw new UnsupportedOperationException(); + } + + @Override + public void setIterationCreated(int iteration) { + throw new UnsupportedOperationException(); + } + + @Override + public Id getId() { + throw new UnsupportedOperationException(); + } + + @Override + public void setPlanId(Id planId) { + throw new UnsupportedOperationException(); + } + + @Override + public String getPlanMutator() { + throw new UnsupportedOperationException(); + } + + @Override + public void setPlanMutator(String planMutator) { + throw new UnsupportedOperationException(); + } @Override public void setScore(Double score) { diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/examples/random/RunRandomDynAgentExample.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/examples/random/RunRandomDynAgentExample.java index 3bb9d6b7231..0952558534d 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/examples/random/RunRandomDynAgentExample.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/examples/random/RunRandomDynAgentExample.java @@ -47,9 +47,9 @@ public static void run(URL context, String networkFile, boolean otfvis) { config.qsim().setSimStarttimeInterpretation(StarttimeInterpretation.onlyUseStarttime); config.qsim().setSnapshotStyle(SnapshotStyle.queue); config.network().setInputFile(networkFile); - config.controler().setOutputDirectory("./test/output/random_dyn_agent/"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOutputDirectory("./test/output/random_dyn_agent/"); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); config.addConfigConsistencyChecker(new DynQSimConfigConsistencyChecker()); Scenario scenario = ScenarioUtils.loadScenario(config); diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/zone/Zones.java b/contribs/dvrp/src/main/java/org/matsim/contrib/zone/Zones.java index 4a4be662672..34321d05068 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/zone/Zones.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/zone/Zones.java @@ -20,27 +20,14 @@ package org.matsim.contrib.zone; import java.io.File; +import java.io.UncheckedIOException; import java.net.MalformedURLException; import java.net.URL; -import java.util.List; import java.util.Map; -import org.geotools.geometry.jts.JTS; -import org.geotools.referencing.CRS; -import org.locationtech.jts.geom.MultiPolygon; -import org.locationtech.jts.geom.Polygon; -import org.locationtech.jts.geom.util.PolygonExtracter; import org.matsim.api.core.v01.Id; import org.matsim.contrib.zone.io.ZoneShpReader; -import org.matsim.contrib.zone.io.ZoneShpWriter; import org.matsim.contrib.zone.io.ZoneXmlReader; -import org.matsim.contrib.zone.io.ZoneXmlWriter; -import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.io.UncheckedIOException; -import org.opengis.referencing.FactoryException; -import org.opengis.referencing.crs.CoordinateReferenceSystem; -import org.opengis.referencing.operation.MathTransform; -import org.opengis.referencing.operation.TransformException; public class Zones { public static Map, Zone> readZones(String zonesXmlFile, String zonesShpFile) { diff --git a/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/examples/onetaxi/RunOneTaxiWithPrebookingExampleIT.java b/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/examples/onetaxi/RunOneTaxiWithPrebookingExampleIT.java index 02917236596..c2b6f6a5753 100644 --- a/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/examples/onetaxi/RunOneTaxiWithPrebookingExampleIT.java +++ b/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/examples/onetaxi/RunOneTaxiWithPrebookingExampleIT.java @@ -78,9 +78,9 @@ public void testRun() { URL configUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("dvrp-grid"), "generic_dvrp_one_taxi_config.xml"); Config config = ConfigUtils.loadConfig(configUrl, new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); { QSimComponentsConfigGroup qsimComponentsConfig = ConfigUtils.addOrGetModule(config, QSimComponentsConfigGroup.class); diff --git a/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/router/DiversionTest.java b/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/router/DiversionTest.java index 5f158a0480a..adf44ba57ac 100644 --- a/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/router/DiversionTest.java +++ b/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/router/DiversionTest.java @@ -126,8 +126,8 @@ public void testRepeatedSameDestinationDiversions() { { /* Create some necessary configuration for the test */ - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); config.qsim().setStartTime(0.0); config.qsim().setSimStarttimeInterpretation(StarttimeInterpretation.onlyUseStarttime); @@ -453,8 +453,8 @@ public void testRepeatedDiversionToDifferentDestinationRightBeforeLastLink() { { /* Create some necessary configuration for the test */ - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); config.qsim().setStartTime(0.0); config.qsim().setSimStarttimeInterpretation(StarttimeInterpretation.onlyUseStarttime); diff --git a/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/util/DvrpEventsReadersTest.java b/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/util/DvrpEventsReadersTest.java index fec0ba99afc..6f661026552 100644 --- a/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/util/DvrpEventsReadersTest.java +++ b/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/util/DvrpEventsReadersTest.java @@ -21,7 +21,7 @@ package org.matsim.contrib.dvrp.util; import static org.assertj.core.api.Assertions.assertThat; -import static org.matsim.core.config.groups.ControlerConfigGroup.EventsFileFormat; +import static org.matsim.core.config.groups.ControllerConfigGroup.EventsFileFormat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java index 5d9974f9c92..4652c3d7339 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java @@ -37,7 +37,7 @@ import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.api.core.v01.events.HasPersonId; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.events.MatsimEventsReader; @@ -68,7 +68,7 @@ private static void checkConsistency(Config config) { if (config.qsim().getSnapshotPeriod() > 1) { throw new RuntimeException("only snapshot periods of 1s are supported."); } - if (!config.controler().getSnapshotFormat().contains(ControlerConfigGroup.SnapshotFormat.positionevents)) { + if (!config.controller().getSnapshotFormat().contains(ControllerConfigGroup.SnapshotFormat.positionevents)) { throw new RuntimeException("config.controler.snapshotFormat must be set to 'positionevents'"); } if (isNotCorrectSnapshotStyle(config.qsim().getSnapshotStyle())) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java index 74f24e7321c..f50fc6a6d27 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java @@ -23,19 +23,19 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigWriter; import org.matsim.core.config.groups.*; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.Controler; import org.matsim.core.controler.MatsimServices; /** - * - * Creates a config file + * + * Creates a config file * with necessary emission input files for the {@link EmissionsConfigGroup EmissionsConfigGroup}. - * + * * This config file is used by the {@link RunDetailedEmissionToolOfflineExample OfflineExample} and * the {@link RunDetailedEmissionToolOnlineExample OnlineExample} - * + * * @author benjamin, julia * * @deprecated -- has not been maintained and should in consequence be phased out. kai, nov'21 @@ -45,47 +45,47 @@ public final class CreateEmissionConfig { private static final String inputPath = "./test/input/org/matsim/contrib/emissions/"; - private static final String networkFile = //inputPath + + private static final String networkFile = //inputPath + "sample_network.xml"; - private static final String plansFile = //inputPath + + private static final String plansFile = //inputPath + "sample_population.xml"; - private static final String emissionVehicleFile = //inputPath + + private static final String emissionVehicleFile = //inputPath + "sample_emissionVehicles.xml"; - + private static final String roadTypeMappingFile = //inputPath + "sample_roadTypeMapping.txt"; - + private static final String averageFleetWarmEmissionFactorsFile = //inputPath + "sample_EFA_HOT_vehcat_2005average.txt"; private static final String averageFleetColdEmissionFactorsFile = //inputPath + "sample_EFA_ColdStart_vehcat_2005average.txt"; - + private static final boolean isUsingDetailedEmissionCalculation = true; private static final String detailedWarmEmissionFactorsFile = //inputPath + "sample_EFA_HOT_SubSegm_2005detailed.txt"; private static final String detailedColdEmissionFactorsFile = //inputPath + "sample_EFA_ColdStart_SubSegm_2005detailed.txt"; - + private static final String outputPath = "./test/output/"; private static final String configFilePath = inputPath + "config_v2.xml"; - + private static final int numberOfIterations = 6; - - + + public static void main(String[] args) { - + Config config = new Config(); config.addCoreModules(); MatsimServices controler = new Controler(config); - + // controlerConfigGroup - ControlerConfigGroup ccg = controler.getConfig().controler(); + ControllerConfigGroup ccg = controler.getConfig().controller(); ccg.setOutputDirectory(outputPath); ccg.setFirstIteration(0); ccg.setLastIteration(numberOfIterations-1); - + // planCalcScoreConfigGroup - PlanCalcScoreConfigGroup pcs = controler.getConfig().planCalcScore(); + ScoringConfigGroup pcs = controler.getConfig().scoring(); ActivityParams homeP = new ActivityParams("home"); homeP.setTypicalDuration(12 * 3600); pcs.addActivityParams(homeP); @@ -94,21 +94,21 @@ public static void main(String[] args) { pcs.addActivityParams(workP); // strategy - StrategyConfigGroup scg = controler.getConfig().strategy(); + ReplanningConfigGroup scg = controler.getConfig().replanning(); StrategySettings strategySettings = new StrategySettings(); strategySettings.setStrategyName("ChangeExpBeta"); strategySettings.setWeight(1.0); scg.addStrategySettings(strategySettings); - + // network NetworkConfigGroup ncg = controler.getConfig().network(); ncg.setInputFile(networkFile); - + // plans PlansConfigGroup pcg = controler.getConfig().plans(); pcg.setInputFile(plansFile); - - // define emission tool input files + + // define emission tool input files EmissionsConfigGroup ecg = new EmissionsConfigGroup() ; controler.getConfig().addModule(ecg); @@ -137,11 +137,11 @@ public static void main(String[] args) { // ecg.setEmissionCostMultiplicationFactor(1.0); // ecg.setConsideringCO2Costs(true); // ecg.setEmissionEfficiencyFactor(1.0); - - // write config + + // write config ConfigWriter cw = new ConfigWriter(config); cw.write(configFilePath); - + } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java index fd852ba1a61..bd1af3c2a90 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java @@ -26,9 +26,7 @@ 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.Injector; -import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; import org.matsim.core.events.algorithms.EventWriterXML; @@ -39,7 +37,7 @@ /** * - * Use the config file as created by the + * Use the config file as created by the * {@link CreateEmissionConfig CreateEmissionConfig} to calculate * emissions based on the link leave events of an events file. Resulting emission events are written into an event file. * @@ -55,7 +53,7 @@ public final class RunAverageEmissionToolOfflineExample{ private Config config; - // ======================================================================================================= + // ======================================================================================================= public static void main (String[] args){ RunAverageEmissionToolOfflineExample emissionToolOfflineExampleV2 = new RunAverageEmissionToolOfflineExample(); @@ -105,7 +103,7 @@ public void install(){ EmissionModule emissionModule = injector.getInstance(EmissionModule.class); // OutputDirectoryHierarchy outputDirectoryHierarchy = injector.getInstance( OutputDirectoryHierarchy.class ); - final String outputDirectory = scenario.getConfig().controler().getOutputDirectory(); + final String outputDirectory = scenario.getConfig().controller().getOutputDirectory(); EventWriterXML emissionEventWriter = new EventWriterXML( outputDirectory + emissionEventsFilename ); emissionModule.getEmissionEventsManager().addHandler(emissionEventWriter); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java index a4818fcf794..191766556c2 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java @@ -29,7 +29,6 @@ import org.matsim.core.controler.Injector; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; -import org.matsim.core.events.ParallelEventsManager; import org.matsim.core.events.algorithms.EventWriterXML; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; @@ -38,7 +37,7 @@ /** * - * Use the config file as created by the + * Use the config file as created by the * {@link CreateEmissionConfig CreateEmissionConfig} to calculate * emissions based on the link leave events of an events file. Resulting emission events are written into an event file. * @@ -54,7 +53,7 @@ public final class RunDetailedEmissionToolOfflineExample{ // private static final String emissionEventOutputFileName = "5.emission.events.offline.xml.gz"; private Config config; - // ======================================================================================================= + // ======================================================================================================= public static void main (String[] args){ RunDetailedEmissionToolOfflineExample emissionToolOfflineExampleV2Vehv1 = new RunDetailedEmissionToolOfflineExample(); @@ -96,7 +95,7 @@ public void install(){ EmissionModule emissionModule = injector.getInstance(EmissionModule.class); - final String outputDirectory = scenario.getConfig().controler().getOutputDirectory(); + final String outputDirectory = scenario.getConfig().controller().getOutputDirectory(); EventWriterXML emissionEventWriter = new EventWriterXML( outputDirectory + RunAverageEmissionToolOfflineExample.emissionEventsFilename ) ; emissionModule.getEmissionEventsManager().addHandler(emissionEventWriter); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestPositionEmissionModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestPositionEmissionModule.java index 73ee5c208b5..c48f5254b39 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestPositionEmissionModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestPositionEmissionModule.java @@ -18,17 +18,16 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.NetworkConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.events.EventsManagerImpl; import org.matsim.core.events.handler.BasicEventHandler; -import org.matsim.core.events.handler.EventHandler; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.routes.RouteUtils; @@ -36,7 +35,6 @@ import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; -import org.matsim.facilities.filters.Filter; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.EngineInformation; import org.matsim.vehicles.Vehicle; @@ -69,11 +67,11 @@ public void simpleTest() { emissionConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); //This is the previous behaviour var config = ConfigUtils.loadConfig(configFile, emissionConfig); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); config.qsim().setSnapshotPeriod(1); config.qsim().setSnapshotStyle(QSimConfigGroup.SnapshotStyle.queue); - config.controler().setWriteSnapshotsInterval(1); - config.controler().setSnapshotFormat(Set.of(ControlerConfigGroup.SnapshotFormat.positionevents)); + config.controller().setWriteSnapshotsInterval(1); + config.controller().setSnapshotFormat(Set.of(ControllerConfigGroup.SnapshotFormat.positionevents)); var scenario = ScenarioUtils.loadScenario(config); @@ -91,33 +89,33 @@ public void compareToOtherModule_singleVehicleSingleLink() { emissionConfig.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); var config = ConfigUtils.loadConfig(configFile, emissionConfig); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); emissionConfig.setAverageColdEmissionFactorsFile("../sample_41_EFA_ColdStart_vehcat_2020average.csv"); emissionConfig.setAverageWarmEmissionFactorsFile( "../sample_41_EFA_HOT_vehcat_2020average.csv" ); emissionConfig.setHbefaTableConsistencyCheckingLevel( EmissionsConfigGroup.HbefaTableConsistencyCheckingLevel.consistent ); - final PlanCalcScoreConfigGroup.ActivityParams homeParams = new PlanCalcScoreConfigGroup.ActivityParams("home") + final ScoringConfigGroup.ActivityParams homeParams = new ScoringConfigGroup.ActivityParams("home") .setTypicalDuration(20); - config.planCalcScore().addActivityParams(homeParams); - final PlanCalcScoreConfigGroup.ActivityParams workParams = new PlanCalcScoreConfigGroup.ActivityParams("work") + config.scoring().addActivityParams(homeParams); + final ScoringConfigGroup.ActivityParams workParams = new ScoringConfigGroup.ActivityParams("work") .setTypicalDuration(20); - config.planCalcScore().addActivityParams(workParams); + config.scoring().addActivityParams(workParams); - var strategy = new StrategyConfigGroup.StrategySettings(); + var strategy = new ReplanningConfigGroup.StrategySettings(); strategy.setStrategyName("ChangeExpBeta"); strategy.setWeight(1.0); - config.strategy().addParameterSet(strategy); + config.replanning().addParameterSet(strategy); // activate snapshots config.qsim().setSnapshotPeriod(1); config.qsim().setSnapshotStyle(QSimConfigGroup.SnapshotStyle.queue); - config.controler().setWriteSnapshotsInterval(1); - config.controler().setSnapshotFormat(Set.of(ControlerConfigGroup.SnapshotFormat.positionevents)); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(0); + config.controller().setWriteSnapshotsInterval(1); + config.controller().setSnapshotFormat(Set.of(ControllerConfigGroup.SnapshotFormat.positionevents)); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(0); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.fromVehiclesData); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExampleIT.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExampleIT.java index fbe73cb8d24..5f231f96650 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExampleIT.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExampleIT.java @@ -30,7 +30,6 @@ import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; -import org.matsim.utils.eventsfilecomparison.EventsFileComparator; import org.matsim.utils.eventsfilecomparison.EventsFileComparator.Result; import java.net.URL; @@ -50,7 +49,7 @@ public final void testAverage_vehTypeV1() { URL scenarioUrl = ExamplesUtils.getTestScenarioURL( "emissions-sampleScenario/testv2_Vehv1" ); URL configUrl = IOUtils.extendUrl( scenarioUrl, "config_average.xml" ); Config config = offlineExample.prepareConfig( new String [] {configUrl.toString()} ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setHbefaVehicleDescriptionSource( HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); @@ -71,7 +70,7 @@ public final void testAverage_vehTypeV2() { URL scenarioUrl = ExamplesUtils.getTestScenarioURL( "emissions-sampleScenario/testv2_Vehv2" ); URL configUrl = IOUtils.extendUrl( scenarioUrl, "config_average.xml" ); Config config = offlineExample.prepareConfig( new String [] {configUrl.toString()} ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setHbefaVehicleDescriptionSource( HbefaVehicleDescriptionSource.asEngineInformationAttributes ); @@ -98,7 +97,7 @@ public final void testAverage_vehTypeV2b() { URL scenarioUrl = ExamplesUtils.getTestScenarioURL( "emissions-sampleScenario/testv2_Vehv2" ); URL configUrl = IOUtils.extendUrl( scenarioUrl, "config_average.xml" ); Config config = offlineExample.prepareConfig( new String [] {configUrl.toString()} ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setHbefaVehicleDescriptionSource( HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); @@ -120,7 +119,7 @@ public final void testAverage_vehTypeV2_HBEFA4() { URL scenarioUrl = ExamplesUtils.getTestScenarioURL( "emissions-sampleScenario/testv2_Vehv2" ); URL configUrl = IOUtils.extendUrl( scenarioUrl, "config_average.xml" ); Config config = offlineExample.prepareConfig( new String [] {configUrl.toString()} ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setAverageColdEmissionFactorsFile("../sample_41_EFA_ColdStart_vehcat_2020average.csv"); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java index 7c8c842941a..35735730695 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java @@ -24,7 +24,6 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup.DetailedVsAverageLookupBehavior; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup.HbefaVehicleDescriptionSource; -import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; @@ -59,7 +58,7 @@ public final void testDetailed_vehTypeV1() { EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setHbefaVehicleDescriptionSource( HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); emissionsConfig.setDetailedVsAverageLookupBehavior( DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); offlineExample.run(); } catch (Exception ee ) { @@ -83,7 +82,7 @@ public final void testDetailed_vehTypeV2() { EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setDetailedVsAverageLookupBehavior( DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); offlineExample.run(); } catch (Exception ee ) { @@ -110,7 +109,7 @@ public final void testDetailed_vehTypeV2_HBEFA4() { emissionsConfig.setDetailedColdEmissionFactorsFile("../sample_41_EFA_ColdStart_SubSegm_2020detailed.csv"); emissionsConfig.setDetailedWarmEmissionFactorsFile("../sample_41_EFA_HOT_SubSegm_2020detailed.csv"); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); offlineExample.run(); } catch (Exception ee ) { gotAnException = true ; @@ -135,7 +134,7 @@ public final void testDetailed_vehTypeV1_FallbackToAverage() { var cfUrl = IOUtils.extendUrl( scUrl, "config_detailed.xml" ); var config = offlineExample.prepareConfig( new String [] {cfUrl.toString()} ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setAverageColdEmissionFactorsFile("../sample_41_EFA_ColdStart_vehcat_2020average.csv"); @@ -156,7 +155,7 @@ public final void testDetailed_vehTypeV2_FallbackToAverage() { var cfUrl = IOUtils.extendUrl( scUrl, "config_detailed.xml" ); var config = offlineExample.prepareConfig( new String [] {cfUrl.toString()} ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setAverageColdEmissionFactorsFile("../sample_41_EFA_ColdStart_vehcat_2020average.csv"); @@ -176,7 +175,7 @@ public final void testDetailed_vehTypeV2_HBEFA4_FallbackToAverage() { var cfUrl = IOUtils.extendUrl( scUrl, "config_detailed.xml" ); var config = offlineExample.prepareConfig( new String [] {cfUrl.toString()} ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setDetailedVsAverageLookupBehavior( DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java index 0315a625693..a762a196a4a 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java @@ -55,8 +55,8 @@ public final void testDetailed_vehTypeV1() { try { RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"} ) ; - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setLastIteration( 1 ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java index 12eed58acea..a046d363371 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java @@ -55,8 +55,8 @@ public final void testDetailed_vehTypeV1_FallbackToAverage() { var configUrl = IOUtils.extendUrl( scenarioUrl, "config_detailed.xml" ); Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String [] { configUrl.toString() } ); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setLastIteration( 1 ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); emissionsConfig.setDetailedVsAverageLookupBehavior( diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java index 42caf0ed295..1a247d71217 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java @@ -49,8 +49,8 @@ public final void testDetailed_vehTypeV2() { try { RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setLastIteration( 1 ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); Scenario scenario = onlineExample.prepareScenario( config ) ; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java index 5afbeb1337e..42f65e0010b 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java @@ -51,8 +51,8 @@ public final void testDetailed_vehTypeV2_FallbackToAverage() { var configUrl = IOUtils.extendUrl( scenarioUrl, "config_detailed.xml" ); Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String [] { configUrl.toString() } ); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setLastIteration( 1 ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setDetailedVsAverageLookupBehavior( DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable ); //This is the previous behaviour -> Test only passes if falling back to average table :( 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 d450afb6d24..4a2655a5ccf 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 @@ -42,8 +42,8 @@ import org.matsim.contrib.ev.fleet.ElectricVehicle; import org.matsim.contrib.ev.infrastructure.Charger; import org.matsim.contrib.ev.infrastructure.ChargingInfrastructure; -import org.matsim.contrib.ev.infrastructure.ChargingInfrastructures; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.contrib.ev.infrastructure.ChargingInfrastructureUtils; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.events.MobsimScopeEventHandler; import org.matsim.vehicles.Vehicle; @@ -60,7 +60,7 @@ public class VehicleChargingHandler ChargingEndEventHandler, MobsimScopeEventHandler { public static final String CHARGING_IDENTIFIER = " charging"; - public static final String CHARGING_INTERACTION = PlanCalcScoreConfigGroup.createStageActivityType( + public static final String CHARGING_INTERACTION = ScoringConfigGroup.createStageActivityType( CHARGING_IDENTIFIER); private final Map, Id> lastVehicleUsed = new HashMap<>(); private final Map, Id> vehiclesAtChargers = new HashMap<>(); @@ -73,7 +73,7 @@ public class VehicleChargingHandler VehicleChargingHandler(ChargingInfrastructure chargingInfrastructure, ElectricFleet electricFleet) { this.chargingInfrastructure = chargingInfrastructure; this.electricFleet = electricFleet; - chargersAtLinks = ChargingInfrastructures.getChargersAtLinks(chargingInfrastructure); + chargersAtLinks = ChargingInfrastructureUtils.getChargersAtLinks(chargingInfrastructure ); } /** diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DischargingModule.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DischargingModule.java index c36f95635a9..96078d1eab1 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DischargingModule.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DischargingModule.java @@ -29,7 +29,7 @@ /** * @author Michal Maciejewski (michalm) */ -public class DischargingModule extends AbstractModule { +public final class DischargingModule extends AbstractModule { @Override public void install() { bind(DriveEnergyConsumption.Factory.class).toInstance(ev -> new OhdeSlaskiDriveEnergyConsumption()); 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 eae4a115384..ca8508a0e74 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 @@ -44,7 +44,7 @@ * calculating the drive-related energy consumption. However, the time spent on the first link is used by the time-based * idle discharge process (see {@link IdleDischargingHandler}). */ -public class DriveDischargingHandler +public final class DriveDischargingHandler implements LinkLeaveEventHandler, VehicleEntersTrafficEventHandler, VehicleLeavesTrafficEventHandler, MobsimScopeEventHandler { private static class EvDrive { private final Id vehicleId; diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DrivingEnergyConsumptionEvent.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DrivingEnergyConsumptionEvent.java index f00009b3e7a..3289446a72e 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DrivingEnergyConsumptionEvent.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DrivingEnergyConsumptionEvent.java @@ -27,7 +27,7 @@ /** * @author Michal Maciejewski (michalm) */ -public class DrivingEnergyConsumptionEvent extends AbstractEnergyConsumptionEvent { +public final class DrivingEnergyConsumptionEvent extends AbstractEnergyConsumptionEvent { public static final String EVENT_TYPE = "drivingEnergyConsumption"; public DrivingEnergyConsumptionEvent(double time, Id vehicleId, Id linkId, double energy, double endCharge) { diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/IdleDischargingHandler.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/IdleDischargingHandler.java index da6fab88948..20a90c08e13 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/IdleDischargingHandler.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/IdleDischargingHandler.java @@ -45,7 +45,7 @@ * VehicleProvider is responsible to decide if AUX discharging applies to a given vehicle based on information from * ActivityStartEvent. */ -public class IdleDischargingHandler +public final class IdleDischargingHandler implements MobsimAfterSimStepListener, ActivityStartEventHandler, ActivityEndEventHandler, MobsimScopeEventHandler { public interface VehicleProvider { /** diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/IdlingEnergyConsumptionEvent.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/IdlingEnergyConsumptionEvent.java index d992dc363f5..fcb625ad7b6 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/IdlingEnergyConsumptionEvent.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/IdlingEnergyConsumptionEvent.java @@ -27,7 +27,7 @@ /** * @author Michal Maciejewski (michalm) */ -public class IdlingEnergyConsumptionEvent extends AbstractEnergyConsumptionEvent { +public final class IdlingEnergyConsumptionEvent extends AbstractEnergyConsumptionEvent { public static final String EVENT_TYPE = "idlingEnergyConsumption"; public IdlingEnergyConsumptionEvent(double time, Id vehicleId, Id linkId, double energy, double endCharge) { diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/LTHDriveEnergyConsumption.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/LTHDriveEnergyConsumption.java index afc8d17d93a..ea20f84a484 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/LTHDriveEnergyConsumption.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/LTHDriveEnergyConsumption.java @@ -32,7 +32,7 @@ import com.google.common.primitives.Doubles; -public class LTHDriveEnergyConsumption implements DriveEnergyConsumption { +public final class LTHDriveEnergyConsumption implements DriveEnergyConsumption { private final PiecewiseBicubicSplineInterpolatingFunction function; diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/MissingEnergyEvent.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/MissingEnergyEvent.java index a85c043522d..ef120c09fa9 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/MissingEnergyEvent.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/MissingEnergyEvent.java @@ -26,7 +26,7 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.vehicles.Vehicle; -public class MissingEnergyEvent extends Event { +public final class MissingEnergyEvent extends Event { public static final String EVENT_TYPE = "missing_energy"; public static final String ATTRIBUTE_VEHICLE = "vehicle"; public static final String ATTRIBUTE_ENERGY = "energy"; diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/OhdeSlaskiAuxEnergyConsumption.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/OhdeSlaskiAuxEnergyConsumption.java index 39d93db41c0..b344474bf9d 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/OhdeSlaskiAuxEnergyConsumption.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/OhdeSlaskiAuxEnergyConsumption.java @@ -27,7 +27,7 @@ import com.google.common.base.Preconditions; import com.google.inject.Inject; -public class OhdeSlaskiAuxEnergyConsumption implements AuxEnergyConsumption { +public final class OhdeSlaskiAuxEnergyConsumption implements AuxEnergyConsumption { private static final double a = 1.3;// [W] private static final double b = -63.4;// [W] private static final double c = 1748.1;// [W] @@ -46,7 +46,7 @@ private static double calcPower(double temp) { private final TemperatureService temperatureService; - public OhdeSlaskiAuxEnergyConsumption(TemperatureService temperatureService) { + OhdeSlaskiAuxEnergyConsumption(TemperatureService temperatureService) { this.temperatureService = temperatureService; } @@ -59,7 +59,7 @@ public static class Factory implements AuxEnergyConsumption.Factory { private final TemperatureService temperatureService; @Inject - public Factory(TemperatureService temperatureService) { + Factory(TemperatureService temperatureService) { this.temperatureService = temperatureService; } diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/OhdeSlaskiDriveEnergyConsumption.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/OhdeSlaskiDriveEnergyConsumption.java index dafad6d76d1..44b62145719 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/OhdeSlaskiDriveEnergyConsumption.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/OhdeSlaskiDriveEnergyConsumption.java @@ -30,7 +30,7 @@ * https://www.researchgate.net/profile/Michal-Maciejewski-3/publication/312393169_Statistical_analysis_of_real-world_urban_driving_cycles_for_modelling_energy_consumption_of_electric_vehicles/links/59b7a17faca2722453a5fc7f/Statistical-analysis-of-real-world-urban-driving-cycles-for-modelling-energy-consumption-of-electric-vehicles.pdf * TODO Add (dis-)charging efficiency relative to SOC, temperature, etc... */ -public class OhdeSlaskiDriveEnergyConsumption implements DriveEnergyConsumption { +public final class OhdeSlaskiDriveEnergyConsumption implements DriveEnergyConsumption { private static final double g = 9.81; // g [m/s^2] private static final double m = 1525; // vehicle mass [kg] private static final double m_s = m + 100; // vehicle mass + extra mass [kg] diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/VehicleTypeSpecificDriveEnergyConsumptionFactory.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/VehicleTypeSpecificDriveEnergyConsumptionFactory.java index b905a6f881e..4310d786b80 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/VehicleTypeSpecificDriveEnergyConsumptionFactory.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/VehicleTypeSpecificDriveEnergyConsumptionFactory.java @@ -29,7 +29,7 @@ import org.matsim.contrib.ev.fleet.ElectricVehicle; import org.matsim.vehicles.VehicleType; -public class VehicleTypeSpecificDriveEnergyConsumptionFactory implements DriveEnergyConsumption.Factory { +public final class VehicleTypeSpecificDriveEnergyConsumptionFactory implements DriveEnergyConsumption.Factory { private final Map, DriveEnergyConsumption.Factory> consumptionMap = new HashMap<>(); diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExample.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExample.java index 698dfe32e5c..e4980391db6 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExample.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExample.java @@ -23,7 +23,6 @@ import java.io.File; import java.io.IOException; -import java.net.URL; import java.util.Arrays; import org.apache.logging.log4j.LogManager; @@ -32,14 +31,12 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.contrib.ev.EvConfigGroup; import org.matsim.contrib.ev.EvModule; -import org.matsim.contrib.ev.charging.VehicleChargingHandler; import org.matsim.contrib.ev.routing.EvNetworkRoutingProvider; 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.mobsim.qsim.AbstractQSimModule; import org.matsim.core.scenario.ScenarioUtils; public class RunEvExample { @@ -66,7 +63,7 @@ public static void main(String[] args) throws IOException { public void run( String[] args ) { Config config = ConfigUtils.loadConfig(args, new EvConfigGroup()); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); Scenario scenario = ScenarioUtils.loadScenario(config); Controler controler = new Controler(scenario); controler.addOverridingModule( new AbstractModule(){ @@ -74,8 +71,11 @@ public void run( String[] args ) { install( new EvModule() ); addRoutingModuleBinding( TransportMode.car ).toProvider(new EvNetworkRoutingProvider(TransportMode.car) ); - // a router that inserts charging activities when the battery is run empty. there may be some other way to insert - // charging activities, based on the situation. kai, dec'22 + // a router that inserts charging activities INTO THE ROUTE when the battery is run empty. This assumes that a full + // charge at the start of the route is not sufficient to drive the route. There are other settings where the + // situation is different, e.g. urban, where there may be a CHAIN of activities, and charging in general is done in + // parallel with some of these activities. That second situation is adressed by some "ev" code in the vsp contrib. + // kai, dec'22 } } ); diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExampleWithLTHConsumptionModel.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExampleWithLTHConsumptionModel.java index 86db1f4478a..024bc2e4c54 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExampleWithLTHConsumptionModel.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExampleWithLTHConsumptionModel.java @@ -24,7 +24,6 @@ import java.io.File; import java.io.IOException; -import java.net.URL; import java.util.Arrays; import org.apache.logging.log4j.LogManager; @@ -34,7 +33,6 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.contrib.ev.EvConfigGroup; import org.matsim.contrib.ev.EvModule; -import org.matsim.contrib.ev.charging.VehicleChargingHandler; import org.matsim.contrib.ev.discharging.AuxEnergyConsumption; import org.matsim.contrib.ev.discharging.DriveEnergyConsumption; import org.matsim.contrib.ev.discharging.VehicleTypeSpecificDriveEnergyConsumptionFactory; @@ -46,7 +44,6 @@ import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; -import org.matsim.core.mobsim.qsim.AbstractQSimModule; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.vehicles.VehicleType; @@ -79,7 +76,7 @@ public static void main(String[] args) throws IOException { public void run( String[] args ) { Config config = ConfigUtils.loadConfig(args, new EvConfigGroup()); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); // === @@ -92,7 +89,7 @@ public void run( String[] args ) { VehicleTypeSpecificDriveEnergyConsumptionFactory driveEnergyConsumptionFactory = new VehicleTypeSpecificDriveEnergyConsumptionFactory(); var vehicleType = Id.create( "EV_65.0kWh", VehicleType.class ); driveEnergyConsumptionFactory.addEnergyConsumptionModelFactory( vehicleType, - new LTHConsumptionModelReader( vehicleType ).readURL( ConfigGroup.getInputFileURL( config.getContext(), "MidCarMap.csv" ) ) ); + new LTHConsumptionModelReader().readURL( ConfigGroup.getInputFileURL( config.getContext(), "MidCarMap.csv" ) ) ); controler.addOverridingModule( new EvModule() ); controler.addOverridingModule( new AbstractModule(){ @@ -109,6 +106,7 @@ public void install(){ } ); } + controler.run(); } } diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExampleWithOwnConsumptionModel.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExampleWithOwnConsumptionModel.java new file mode 100644 index 00000000000..eacaba778ad --- /dev/null +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/example/RunEvExampleWithOwnConsumptionModel.java @@ -0,0 +1,137 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2016 by the members listed in the COPYING, * + * LICENSE and WARRANTY file. * + * email : info at matsim dot org * + * * + * *********************************************************************** * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * See also COPYING, LICENSE and WARRANTY file * + * * + * *********************************************************************** */ + +package org.matsim.contrib.ev.example; +/* + * created by jbischoff, 19.03.2019 + */ + +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.api.core.v01.network.Link; +import org.matsim.contrib.ev.EvConfigGroup; +import org.matsim.contrib.ev.EvModule; +import org.matsim.contrib.ev.discharging.AuxEnergyConsumption; +import org.matsim.contrib.ev.discharging.DriveEnergyConsumption; +import org.matsim.contrib.ev.discharging.LTHDriveEnergyConsumption; +import org.matsim.contrib.ev.fleet.ElectricVehicle; +import org.matsim.contrib.ev.infrastructure.LTHConsumptionModelReader; +import org.matsim.contrib.ev.routing.EvNetworkRoutingProvider; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigGroup; +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; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; + +/** + * Runs a sample EV run using a vehicle consumption model designed at LTH in Lund which takes the speed and the slope of a link into account. + * Link slopes may be added using a double array on the network. + * The consumption maps are based on Domingues, Gabriel. / Modeling, Optimization and Analysis of Electromobility Systems. Lund : Department of Biomedical Engineering, Lund university, 2018. 169 p., PhD thesis + */ +public class RunEvExampleWithOwnConsumptionModel{ + static final String DEFAULT_CONFIG_FILE = "test/input/org/matsim/contrib/ev/example/RunEvExample/config.xml"; + private static final Logger log = LogManager.getLogger( RunEvExampleWithOwnConsumptionModel.class ); + + public static void main(String[] args) throws IOException { + if (args.length > 0) { + log.info("Starting simulation run with the following arguments:"); + log.info("args=" + Arrays.toString( args ) ); + } else { + File localConfigFile = new File(DEFAULT_CONFIG_FILE); + if (localConfigFile.exists()) { + log.info("Starting simulation run with the local example config file"); + args = new String[]{ DEFAULT_CONFIG_FILE }; + } else { + log.info("Starting simulation run with the example config file from GitHub repository"); + args = new String[]{"https://raw.githubusercontent.com/matsim-org/matsim/master/contribs/ev/" + + DEFAULT_CONFIG_FILE }; + } + } + new RunEvExampleWithOwnConsumptionModel().run(args ); + } + + public void run( String[] args ) { + Config config = ConfigUtils.loadConfig(args, new EvConfigGroup()); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + + // === + + Scenario scenario = ScenarioUtils.loadScenario(config); + + // === + + Controler controler = new Controler(scenario); + { + DriveEnergyConsumption.Factory driveEnergyConsumptionFactory = new DriveEnergyConsumption.Factory(){ + @Override public DriveEnergyConsumption create( ElectricVehicle electricVehicle ){ + DriveEnergyConsumption.Factory factory = new LTHConsumptionModelReader().readURL( ConfigGroup.getInputFileURL( config.getContext(), "MidCarMap.csv" ) ); + DriveEnergyConsumption delegate = factory.create( electricVehicle ); + + DriveEnergyConsumption consumption = new DriveEnergyConsumption(){ + @Override public double calcEnergyConsumption( Link link, double travelTime, double linkEnterTime ){ + + // discharge because the link must be driven: + double delta = delegate.calcEnergyConsumption( link, travelTime, linkEnterTime ); + + double desiredSocAtEndOfLink = (double) electricVehicle.getVehicleSpecification().getMatsimVehicle().getAttributes().getAttribute( "whatever" ); + + return electricVehicle.getBattery().getSoc() - desiredSocAtEndOfLink; + // * above will often be negative; this is the purpose: discharging is negative i.e. we are + // charging on the link. ((This is why I am in general against hiding the sign in the method + // name. kai)) + + // * above is in SOC space, needs to be translated into kWh space + + // * need to make sure that the above charging is physically possible + + // * need to make sure that we are not discharging beyond what is needed to drive the link + + } + }; + return consumption; + } + }; + + controler.addOverridingModule( new EvModule() ); + controler.addOverridingModule( new AbstractModule(){ + @Override + public void install(){ + bind( DriveEnergyConsumption.Factory.class ).toInstance( driveEnergyConsumptionFactory ); + bind( AuxEnergyConsumption.Factory.class ).toInstance( + electricVehicle -> ( beginTime, duration, linkId ) -> 0 ); //a dummy factory, as aux consumption is part of the drive consumption in the model + + addRoutingModuleBinding( TransportMode.car ).toProvider( new EvNetworkRoutingProvider( TransportMode.car ) ); + // a router that inserts charging activities when the battery is run empty. there may be some other way to insert + // charging activities, based on the situation. kai, dec'22 + } + } ); + } + + + controler.run(); + } +} diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/BatteryImpl.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/BatteryDefaultImpl.java similarity index 94% rename from contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/BatteryImpl.java rename to contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/BatteryDefaultImpl.java index b3be0ab8a02..a9629018dfc 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/BatteryImpl.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/BatteryDefaultImpl.java @@ -23,11 +23,11 @@ import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; -public class BatteryImpl implements Battery { +final class BatteryDefaultImpl implements Battery { private final double capacity; private double charge; - public BatteryImpl(double capacity, double charge) { + BatteryDefaultImpl( double capacity, double charge ) { this.capacity = capacity; this.charge = charge; } diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ConvertInitialChargeToInitialSoc.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ConvertInitialChargeToInitialSoc.java deleted file mode 100644 index 2f1475f964e..00000000000 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ConvertInitialChargeToInitialSoc.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * *********************************************************************** * - * project: org.matsim.* - * *********************************************************************** * - * * - * copyright : (C) 2022 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** * - */ - -package org.matsim.contrib.ev.fleet; - -import static org.matsim.contrib.ev.fleet.ElectricVehicleSpecificationImpl.INITIAL_SOC; - -import org.matsim.vehicles.MatsimVehicleReader; -import org.matsim.vehicles.MatsimVehicleWriter; -import org.matsim.vehicles.VehicleUtils; - -/** - * @author Michal Maciejewski (michalm) - */ -public class ConvertInitialChargeToInitialSoc { - private static final String INITIAL_ENERGY_kWh = "initialEnergyInKWh"; - - public static void run(String file) { - var vehicles = VehicleUtils.createVehiclesContainer(); - var reader = new MatsimVehicleReader(vehicles); - reader.readFile(file); - - for (var v : vehicles.getVehicles().values()) { - double battery_kWh = VehicleUtils.getEnergyCapacity(v.getType().getEngineInformation()); - double initial_kWh = (double)v.getAttributes().getAttribute(INITIAL_ENERGY_kWh); - double initial_soc = initial_kWh / battery_kWh; - v.getAttributes().removeAttribute(INITIAL_ENERGY_kWh); - v.getAttributes().putAttribute(INITIAL_SOC, initial_soc); - } - - var writer = new MatsimVehicleWriter(vehicles); - writer.writeFile(file); - } -} diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetModule.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetModule.java index fc6493ae3b8..179a6ec9116 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetModule.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetModule.java @@ -37,7 +37,7 @@ /** * @author Michal Maciejewski (michalm) */ -public class ElectricFleetModule extends AbstractModule { +public final class ElectricFleetModule extends AbstractModule { @Inject private EvConfigGroup evCfg; @@ -46,9 +46,9 @@ public void install() { bind(ElectricFleetSpecification.class).toProvider(new Provider<>() { @Inject private Vehicles vehicles; @Override public ElectricFleetSpecification get() { - ElectricFleetSpecification fleetSpecification = new ElectricFleetSpecificationImpl(); - ElectricVehicleSpecificationImpl.createAndAddVehicleSpecificationsFromMatsimVehicles(fleetSpecification, - vehicles.getVehicles().values()); + ElectricFleetSpecification fleetSpecification = new ElectricFleetSpecificationDefaultImpl(); + ElectricFleetUtils.createAndAddVehicleSpecificationsFromMatsimVehicles(fleetSpecification, + vehicles.getVehicles().values() ); return fleetSpecification; } }).asEagerSingleton(); @@ -64,8 +64,8 @@ protected void configureQSim() { @Override public ElectricFleet get() { - return ElectricFleets.createDefaultFleet(fleetSpecification, driveConsumptionFactory, auxConsumptionFactory, - chargingPowerFactory); + return ElectricFleetUtils.createDefaultFleet(fleetSpecification, driveConsumptionFactory, auxConsumptionFactory, + chargingPowerFactory ); } }).asEagerSingleton(); @@ -77,7 +77,7 @@ public ElectricFleet get() { for (var oldSpec : electricFleetSpecification.getVehicleSpecifications().values()) { var matsimVehicle = oldSpec.getMatsimVehicle(); double socAtEndOfCurrentIteration = electricFleet.getElectricVehicles().get(oldSpec.getId()).getBattery().getSoc(); - ElectricVehicleSpecifications.setInitialSoc(matsimVehicle, socAtEndOfCurrentIteration); + ElectricFleetUtils.setInitialSoc(matsimVehicle, socAtEndOfCurrentIteration ); } } }); diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationImpl.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationDefaultImpl.java similarity index 96% rename from contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationImpl.java rename to contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationDefaultImpl.java index 14a70682741..b24583feb13 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationImpl.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationDefaultImpl.java @@ -30,7 +30,7 @@ /** * @author Michal Maciejewski (michalm) */ -public final class ElectricFleetSpecificationImpl implements ElectricFleetSpecification { +final class ElectricFleetSpecificationDefaultImpl implements ElectricFleetSpecification { private final Map, ElectricVehicleSpecification> specifications = new LinkedHashMap<>(); @Override diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetUtils.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetUtils.java new file mode 100644 index 00000000000..0e92b52759c --- /dev/null +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetUtils.java @@ -0,0 +1,90 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 2022 by the members listed in the COPYING, * + * LICENSE and WARRANTY file. * + * email : info at matsim dot org * + * * + * *********************************************************************** * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * See also COPYING, LICENSE and WARRANTY file * + * * + * *********************************************************************** * + */ + +package org.matsim.contrib.ev.fleet; + +import java.util.Collection; +import java.util.Objects; + +import com.google.common.collect.ImmutableMap; +import org.matsim.api.core.v01.Id; +import org.matsim.contrib.ev.charging.ChargingPower; +import org.matsim.contrib.ev.discharging.AuxEnergyConsumption; +import org.matsim.contrib.ev.discharging.DriveEnergyConsumption; +import org.matsim.vehicles.*; + +public final class ElectricFleetUtils { + public static final String EV_ENGINE_HBEFA_TECHNOLOGY = "electricity"; + public static final String INITIAL_SOC = "initialSoc";// in [0, 1] + public static final String CHARGER_TYPES = "chargerTypes"; + private static final String INITIAL_ENERGY_kWh = "initialEnergyInKWh"; + private ElectricFleetUtils(){} // do not instantiate + public static void setInitialSoc(Vehicle vehicle, double initialSoc) { + vehicle.getAttributes().putAttribute( INITIAL_SOC, initialSoc ); + } + + public static void setChargerTypes(EngineInformation engineInformation, Collection chargerTypes) { + engineInformation.getAttributes().putAttribute( CHARGER_TYPES, chargerTypes ); + } + public static void run(String file) { + var vehicles = VehicleUtils.createVehiclesContainer(); + var reader = new MatsimVehicleReader(vehicles); + reader.readFile(file); + + for (var v : vehicles.getVehicles().values()) { + double battery_kWh = VehicleUtils.getEnergyCapacity(v.getType().getEngineInformation()); + double initial_kWh = (double)v.getAttributes().getAttribute(INITIAL_ENERGY_kWh); + double initial_soc = initial_kWh / battery_kWh; + v.getAttributes().removeAttribute(INITIAL_ENERGY_kWh); + v.getAttributes().putAttribute(INITIAL_SOC, initial_soc); + } + + var writer = new MatsimVehicleWriter(vehicles); + writer.writeFile(file); + } + public static ElectricVehicle create( ElectricVehicleSpecification vehicleSpecification, + DriveEnergyConsumption.Factory driveFactory, AuxEnergyConsumption.Factory auxFactory, + ChargingPower.Factory chargingFactory ) { + ElectricVehicleDefaultImpl ev = new ElectricVehicleDefaultImpl(vehicleSpecification); + ev.driveEnergyConsumption = Objects.requireNonNull(driveFactory.create(ev ) ); + ev.auxEnergyConsumption = Objects.requireNonNull(auxFactory.create(ev)); + ev.chargingPower = Objects.requireNonNull(chargingFactory.create(ev)); + return ev; + } + public static void createAndAddVehicleSpecificationsFromMatsimVehicles(ElectricFleetSpecification fleetSpecification, Collection vehicles) { + vehicles.stream() + .filter(vehicle -> EV_ENGINE_HBEFA_TECHNOLOGY.equals(VehicleUtils.getHbefaTechnology(vehicle.getType().getEngineInformation()))) + .map( ElectricVehicleSpecificationDefaultImpl::new ) + .forEach(fleetSpecification::addVehicleSpecification); + } + public static ElectricVehicleSpecification createElectricVehicleSpecificationDefaultImpl( Vehicle matsimVehicle ){ + return new ElectricVehicleSpecificationDefaultImpl( matsimVehicle ); + } + public static ElectricFleet createDefaultFleet(ElectricFleetSpecification fleetSpecification, + DriveEnergyConsumption.Factory driveConsumptionFactory, AuxEnergyConsumption.Factory auxConsumptionFactory, + ChargingPower.Factory chargingFactory) { + ImmutableMap, ElectricVehicle> vehicles = fleetSpecification.getVehicleSpecifications() + .values() + .stream() + .map(s -> create(s, driveConsumptionFactory, auxConsumptionFactory, chargingFactory )) + .collect(ImmutableMap.toImmutableMap(ElectricVehicle::getId, v -> v)); + return () -> vehicles; + } +} diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleets.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleets.java deleted file mode 100644 index fbe29db0ab3..00000000000 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleets.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * *********************************************************************** * - * project: org.matsim.* - * *********************************************************************** * - * * - * 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.contrib.ev.fleet; - -import org.matsim.api.core.v01.Id; -import org.matsim.contrib.ev.charging.ChargingPower; -import org.matsim.contrib.ev.discharging.AuxEnergyConsumption; -import org.matsim.contrib.ev.discharging.DriveEnergyConsumption; -import org.matsim.vehicles.Vehicle; - -import com.google.common.collect.ImmutableMap; - -public class ElectricFleets { - public static ElectricFleet createDefaultFleet(ElectricFleetSpecification fleetSpecification, - DriveEnergyConsumption.Factory driveConsumptionFactory, AuxEnergyConsumption.Factory auxConsumptionFactory, - ChargingPower.Factory chargingFactory) { - ImmutableMap, ElectricVehicle> vehicles = fleetSpecification.getVehicleSpecifications() - .values() - .stream() - .map(s -> ElectricVehicleImpl.create(s, driveConsumptionFactory, auxConsumptionFactory, - chargingFactory)) - .collect(ImmutableMap.toImmutableMap(ElectricVehicle::getId, v -> v)); - return () -> vehicles; - } -} diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleImpl.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleDefaultImpl.java similarity index 74% rename from contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleImpl.java rename to contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleDefaultImpl.java index 91125b6500d..c4da3c65565 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleImpl.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleDefaultImpl.java @@ -20,8 +20,6 @@ package org.matsim.contrib.ev.fleet; -import java.util.Objects; - import org.matsim.api.core.v01.Id; import org.matsim.contrib.ev.charging.ChargingPower; import org.matsim.contrib.ev.discharging.AuxEnergyConsumption; @@ -31,27 +29,18 @@ import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; -public class ElectricVehicleImpl implements ElectricVehicle { - public static ElectricVehicle create(ElectricVehicleSpecification vehicleSpecification, - DriveEnergyConsumption.Factory driveFactory, AuxEnergyConsumption.Factory auxFactory, - ChargingPower.Factory chargingFactory) { - ElectricVehicleImpl ev = new ElectricVehicleImpl(vehicleSpecification); - ev.driveEnergyConsumption = Objects.requireNonNull(driveFactory.create(ev)); - ev.auxEnergyConsumption = Objects.requireNonNull(auxFactory.create(ev)); - ev.chargingPower = Objects.requireNonNull(chargingFactory.create(ev)); - return ev; - } +final class ElectricVehicleDefaultImpl implements ElectricVehicle { private final ElectricVehicleSpecification vehicleSpecification; private final Battery battery; - private DriveEnergyConsumption driveEnergyConsumption; - private AuxEnergyConsumption auxEnergyConsumption; - private ChargingPower chargingPower; + DriveEnergyConsumption driveEnergyConsumption; + AuxEnergyConsumption auxEnergyConsumption; + ChargingPower chargingPower; - private ElectricVehicleImpl(ElectricVehicleSpecification vehicleSpecification) { + ElectricVehicleDefaultImpl( ElectricVehicleSpecification vehicleSpecification ) { this.vehicleSpecification = vehicleSpecification; - battery = new BatteryImpl(vehicleSpecification.getBatteryCapacity(), vehicleSpecification.getInitialCharge()); + battery = new BatteryDefaultImpl(vehicleSpecification.getBatteryCapacity(), vehicleSpecification.getInitialCharge()); } @Override diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationImpl.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationDefaultImpl.java similarity index 73% rename from contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationImpl.java rename to contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationDefaultImpl.java index 70d4c100f77..ef18ae6cce6 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationImpl.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationDefaultImpl.java @@ -33,23 +33,11 @@ /** * @author Michal Maciejewski (michalm) */ -public class ElectricVehicleSpecificationImpl implements ElectricVehicleSpecification { - public static final String EV_ENGINE_HBEFA_TECHNOLOGY = "electricity"; - - public static final String INITIAL_SOC = "initialSoc";// in [0, 1] - public static final String CHARGER_TYPES = "chargerTypes"; - - public static void createAndAddVehicleSpecificationsFromMatsimVehicles(ElectricFleetSpecification fleetSpecification, - Collection vehicles) { - vehicles.stream() - .filter(vehicle -> EV_ENGINE_HBEFA_TECHNOLOGY.equals(VehicleUtils.getHbefaTechnology(vehicle.getType().getEngineInformation()))) - .map(ElectricVehicleSpecificationImpl::new) - .forEach(fleetSpecification::addVehicleSpecification); - } +final class ElectricVehicleSpecificationDefaultImpl implements ElectricVehicleSpecification { private final Vehicle matsimVehicle; - public ElectricVehicleSpecificationImpl(Vehicle matsimVehicle) { + ElectricVehicleSpecificationDefaultImpl( Vehicle matsimVehicle ) { this.matsimVehicle = matsimVehicle; //provided per vehicle type (in engine info) Preconditions.checkArgument(getInitialSoc() >= 0 && getInitialSoc() <= 1, "Invalid initialCharge or batteryCapacity of vehicle: %s", getId()); @@ -68,12 +56,12 @@ public Vehicle getMatsimVehicle() { @Override public ImmutableList getChargerTypes() { var engineInfo = matsimVehicle.getType().getEngineInformation(); - return ImmutableList.copyOf((Collection)engineInfo.getAttributes().getAttribute(CHARGER_TYPES)); + return ImmutableList.copyOf((Collection)engineInfo.getAttributes().getAttribute( ElectricFleetUtils.CHARGER_TYPES ) ); } @Override public double getInitialSoc() { - return (double)matsimVehicle.getAttributes().getAttribute(INITIAL_SOC); + return (double)matsimVehicle.getAttributes().getAttribute( ElectricFleetUtils.INITIAL_SOC ); } @Override diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecifications.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecifications.java deleted file mode 100644 index 225d5be689d..00000000000 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecifications.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * *********************************************************************** * - * project: org.matsim.* - * *********************************************************************** * - * * - * copyright : (C) 2022 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** * - */ - -package org.matsim.contrib.ev.fleet; - -import java.util.Collection; - -import org.matsim.vehicles.EngineInformation; -import org.matsim.vehicles.Vehicle; - -public class ElectricVehicleSpecifications { - public static void setInitialSoc(Vehicle vehicle, double initialSoc) { - vehicle.getAttributes().putAttribute(ElectricVehicleSpecificationImpl.INITIAL_SOC, initialSoc); - } - - public static void setChargerTypes(EngineInformation engineInformation, Collection chargerTypes) { - engineInformation.getAttributes().putAttribute(ElectricVehicleSpecificationImpl.CHARGER_TYPES, chargerTypes); - } -} diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerImpl.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerDefaultImpl.java similarity index 95% rename from contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerImpl.java rename to contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerDefaultImpl.java index a37cd181c9e..d2efb68578d 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerImpl.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerDefaultImpl.java @@ -29,13 +29,13 @@ import com.google.common.base.Preconditions; -public class ChargerImpl implements Charger { +class ChargerDefaultImpl implements Charger { private final ChargerSpecification specification; private final Link link; private final ChargingLogic logic; - public ChargerImpl(ChargerSpecification specification, Link link, ChargingLogic logic) { + ChargerDefaultImpl( ChargerSpecification specification, Link link, ChargingLogic logic ) { Preconditions.checkArgument(link.getId().equals(specification.getLinkId()), "link.id != specification.linkId"); this.specification = specification; this.link = link; diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerReader.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerReader.java index 27f21fe2fff..9864622b4cb 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerReader.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerReader.java @@ -28,7 +28,7 @@ import org.matsim.core.utils.io.MatsimXmlParser; import org.xml.sax.Attributes; -public class ChargerReader extends MatsimXmlParser { +public final class ChargerReader extends MatsimXmlParser { private final static String CHARGER = "charger"; private final ChargingInfrastructureSpecification chargingInfrastructure; diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerWriter.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerWriter.java index bb03bc9f063..8955b266984 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerWriter.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargerWriter.java @@ -29,7 +29,7 @@ import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.io.MatsimXmlWriter; -public class ChargerWriter extends MatsimXmlWriter { +public final class ChargerWriter extends MatsimXmlWriter { private final Stream chargerSpecifications; public ChargerWriter(Stream chargerSpecifications) { diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureModule.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureModule.java index ea2e2526afb..f44bee53f11 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureModule.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureModule.java @@ -36,7 +36,7 @@ /** * @author Michal Maciejewski (michalm) */ -public class ChargingInfrastructureModule extends AbstractModule { +public final class ChargingInfrastructureModule extends AbstractModule { public static final String CHARGERS = "chargers"; private final Key networkKey; @@ -56,7 +56,7 @@ public void install() { bind(Network.class).annotatedWith(Names.named(CHARGERS)).to(networkKey).asEagerSingleton(); bind(ChargingInfrastructureSpecification.class).toProvider(() -> { - ChargingInfrastructureSpecification chargingInfrastructureSpecification = new ChargingInfrastructureSpecificationImpl(); + ChargingInfrastructureSpecification chargingInfrastructureSpecification = new ChargingInfrastructureSpecificationDefaultImpl(); new ChargerReader(chargingInfrastructureSpecification).parse( ConfigGroup.getInputFileURL(getConfig().getContext(), evCfg.chargersFile)); return chargingInfrastructureSpecification; @@ -76,8 +76,8 @@ protected void configureQSim() { @Override public ChargingInfrastructure get() { - return ChargingInfrastructures.createChargingInfrastructure(chargingInfrastructureSpecification, - network.getLinks()::get, chargingLogicFactory); + return ChargingInfrastructureUtils.createChargingInfrastructure(chargingInfrastructureSpecification, + network.getLinks()::get, chargingLogicFactory ); } }).asEagerSingleton(); } diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationImpl.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationDefaultImpl.java similarity index 95% rename from contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationImpl.java rename to contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationDefaultImpl.java index ceeba42372f..48a27563616 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationImpl.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationDefaultImpl.java @@ -28,7 +28,7 @@ /** * @author Michal Maciejewski (michalm) */ -public class ChargingInfrastructureSpecificationImpl implements ChargingInfrastructureSpecification { +final class ChargingInfrastructureSpecificationDefaultImpl implements ChargingInfrastructureSpecification { private final SpecificationContainer container = new SpecificationContainer<>(); @Override diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructures.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureUtils.java similarity index 90% rename from contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructures.java rename to contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureUtils.java index b86a140fcbb..e4e7ca5c4fa 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructures.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureUtils.java @@ -37,8 +37,10 @@ /** * @author Michal Maciejewski (michalm) */ -public class ChargingInfrastructures { - static final Logger log = LogManager.getLogger(ChargingInfrastructures.class); +public class ChargingInfrastructureUtils{ + static final Logger log = LogManager.getLogger( ChargingInfrastructureUtils.class ); + + private ChargingInfrastructureUtils(){} // do not instantiate public static ChargingInfrastructure createChargingInfrastructure( ChargingInfrastructureSpecification infrastructureSpecification, Function, Link> linkProvider, @@ -46,7 +48,7 @@ public static ChargingInfrastructure createChargingInfrastructure( var chargers = infrastructureSpecification.getChargerSpecifications() .values() .stream() - .map(s -> new ChargerImpl(s, linkProvider.apply(s.getLinkId()), chargingLogicFactory.create(s))) + .map(s -> new ChargerDefaultImpl(s, linkProvider.apply(s.getLinkId() ), chargingLogicFactory.create(s )) ) .collect(ImmutableMap.toImmutableMap(Charger::getId, c -> (Charger)c)); return () -> chargers; } @@ -72,7 +74,7 @@ public static ChargingInfrastructure createModalNetworkChargers(ChargingInfrastr var reachableLinks = network.getLinks(); var filteredChargers = infrastructure.getChargers().values().stream().map(c -> { var link = reachableLinks.get(c.getLink().getId()); - return link == null ? null : new ChargerImpl(c.getSpecification(), link, c.getLogic()); + return link == null ? null : new ChargerDefaultImpl(c.getSpecification(), link, c.getLogic()); }).filter(Objects::nonNull).collect(ImmutableMap.toImmutableMap(Charger::getId, c -> (Charger)c)); int chargerCount = infrastructure.getChargers().size(); diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ImmutableChargerSpecification.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ImmutableChargerSpecification.java index aa08f5d6b85..a3d7192b793 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ImmutableChargerSpecification.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ImmutableChargerSpecification.java @@ -40,7 +40,7 @@ public class ImmutableChargerSpecification implements ChargerSpecification { private final double plugPower; private final int plugCount; - private ImmutableChargerSpecification(Builder builder) { + private ImmutableChargerSpecification( ChargerSpecificationBuilder builder ) { id = Objects.requireNonNull(builder.id); linkId = Objects.requireNonNull(builder.linkId); chargerType = Objects.requireNonNull(builder.chargerType); @@ -51,12 +51,12 @@ private ImmutableChargerSpecification(Builder builder) { Preconditions.checkArgument(plugCount >= 0, "Negative plugCount of charger: %s", id); } - public static Builder newBuilder() { - return new Builder(); + public static ChargerSpecificationBuilder newBuilder() { + return new ChargerSpecificationBuilder(); } - public static Builder newBuilder(ChargerSpecification copy) { - Builder builder = new Builder(); + public static ChargerSpecificationBuilder newBuilder( ChargerSpecification copy ) { + ChargerSpecificationBuilder builder = new ChargerSpecificationBuilder(); builder.id = copy.getId(); builder.linkId = copy.getLinkId(); builder.chargerType = copy.getChargerType(); @@ -101,37 +101,37 @@ public String toString() { .toString(); } - public static final class Builder { + public static final class ChargerSpecificationBuilder{ private Id id; private Id linkId; private String chargerType; private Double plugPower; private Integer plugCount; - private Builder() { + private ChargerSpecificationBuilder() { } - public Builder id(Id val) { + public ChargerSpecificationBuilder id( Id val ) { id = val; return this; } - public Builder linkId(Id val) { + public ChargerSpecificationBuilder linkId( Id val ) { linkId = val; return this; } - public Builder chargerType(String val) { + public ChargerSpecificationBuilder chargerType( String val ) { chargerType = val; return this; } - public Builder plugPower(double val) { + public ChargerSpecificationBuilder plugPower( double val ) { plugPower = val; return this; } - public Builder plugCount(int val) { + public ChargerSpecificationBuilder plugCount( int val ) { plugCount = val; return this; } diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/LTHConsumptionModelReader.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/LTHConsumptionModelReader.java index 5cb4e90d129..0b8e732e85a 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/LTHConsumptionModelReader.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/LTHConsumptionModelReader.java @@ -28,6 +28,7 @@ import java.util.List; import org.matsim.api.core.v01.Id; +import org.matsim.contrib.ev.discharging.DriveEnergyConsumption; import org.matsim.contrib.ev.discharging.LTHDriveEnergyConsumption; import org.matsim.core.utils.io.tabularFileParser.TabularFileHandler; import org.matsim.core.utils.io.tabularFileParser.TabularFileParser; @@ -43,10 +44,10 @@ */ public class LTHConsumptionModelReader { - public LTHConsumptionModelReader(Id vehicleTypeId) { + public LTHConsumptionModelReader() { } - public LTHDriveEnergyConsumption.Factory readURL(URL fileUrl) { + public DriveEnergyConsumption.Factory readURL( URL fileUrl ) { List speeds = new ArrayList<>(); List slopes = new ArrayList<>(); TabularFileParserConfig tabularFileParserConfig = new TabularFileParserConfig(); diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/package-info.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/package-info.java index b8acc39a3f7..1ae999170d8 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/package-info.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/package-info.java @@ -17,8 +17,6 @@ * * * *********************************************************************** */ -package org.matsim.contrib.ev; - /** * All values used in this package use SI base and derived units. In particular: *