diff --git a/.github/dependabot.yml b/.github/dependabot.yml index b76b8957033..9878d8651cc 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,7 +4,11 @@ updates: directory: "/" schedule: interval: "daily" + - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" + groups: + github-actions: + patterns: ["*"] diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 00000000000..021bae1c67c --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,49 @@ +name: CodeQL + +on: + push: + branches: 'master' + +jobs: + analyze: + name: Analyze + runs-on: 'ubuntu-latest' + timeout-minutes: 360 + permissions: + actions: read + contents: read + security-events: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Java + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'zulu' + cache: 'maven' + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: 'java' + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:java" diff --git a/.github/workflows/deploy-on-pr-merge.yaml b/.github/workflows/deploy-on-pr-merge.yaml index deed3a54d24..332a3dfe178 100644 --- a/.github/workflows/deploy-on-pr-merge.yaml +++ b/.github/workflows/deploy-on-pr-merge.yaml @@ -10,8 +10,8 @@ on: jobs: deploy-snapshot: name: deploy PR-labelled version - # for PR-labelled deployment -- only if closed by merging - if: github.event_name == 'push' || github.event.pull_request.merged == true + # only if PR closed by merging + if: github.event.pull_request.merged == true runs-on: ubuntu-latest @@ -25,7 +25,7 @@ jobs: java-version: 17 distribution: 'zulu' cache: 'maven' - server-id: ${{ github.event_name == 'push' && 'matsim-snapshots' || 'matsim-releases' }} #choose mvn repo + server-id: 'matsim-releases' server-username: MAVEN_USERNAME server-password: MAVEN_PASSWORD @@ -43,5 +43,10 @@ jobs: MAVEN_USERNAME: ${{ secrets.REPOMATSIM_USERNAME }} MAVEN_PASSWORD: ${{ secrets.REPOMATSIM_TOKEN }} + - name: Submit Dependency Graph + # Generate a complete dependency graph and submit the graph to the GitHub repository. + # The goal is to improve security alerts from dependabot, because dependabot is not able to compute the complete dependency graph. + uses: advanced-security/maven-dependency-submission-action@v3 + env: MAVEN_OPTS: -Xmx2g diff --git a/.github/workflows/verify-push.yaml b/.github/workflows/verify-push.yaml index 528ebc740d8..f2a5b59d8ee 100644 --- a/.github/workflows/verify-push.yaml +++ b/.github/workflows/verify-push.yaml @@ -55,9 +55,9 @@ jobs: - contribs/socnetsim - contribs/sumo - contribs/pseudosimulation + - 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/README.md b/contribs/README.md index cf682e61410..f29f739c4ef 100644 --- a/contribs/README.md +++ b/contribs/README.md @@ -41,6 +41,7 @@ The MATSim core development team cannot make any guarantee that these extensions | [parking](parking/README.md) | Parking infrastructure and supply constraints | [protobuf](protobuf/README.md) | Protocol buffer implementation and converter for the MATSim event infrastructure | [pseudosimulation](pseudosimulation/README.md) | Pseudo-simulation to speed-up simulation times +| [railsim](railsim/README.md) | A large-scale hybrid micro- and mesoscopic simulation approach for railway operation | [roadpricing](roadpricing/README.md) | Functionality to simulate different road-pricing scenarios in MATSim | [shared_mobility](shared_mobility/README.md) | Simulate human-driven shared mobility (i.e., micromobility) | [signals](signals/README.md) | Simulate traffic lights microscopically 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/traffic/traveltime/SampleValidationRoutes.java b/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/SampleValidationRoutes.java index da7a70673d6..168bf28499e 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/SampleValidationRoutes.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/SampleValidationRoutes.java @@ -24,8 +24,8 @@ import org.matsim.application.options.OutputOptions; import org.matsim.application.options.ShpOptions; import org.matsim.core.network.NetworkUtils; -import org.matsim.core.router.FastDijkstraFactory; import org.matsim.core.router.costcalculators.OnlyTimeDependentTravelDisutility; +import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.scenario.ProjectionUtils; import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; @@ -156,7 +156,7 @@ public Integer call() throws Exception { FreeSpeedTravelTime tt = new FreeSpeedTravelTime(); OnlyTimeDependentTravelDisutility util = new OnlyTimeDependentTravelDisutility(tt); - LeastCostPathCalculator router = new FastDijkstraFactory(false).createPathCalculator(network, util, tt); + LeastCostPathCalculator router = new SpeedyALTFactory().createPathCalculator(network, util, tt); List routes = sampleRoutes(network, router, rnd); diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/TravelTimeComparison.java b/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/TravelTimeComparison.java index 5947ce4231b..3c22fc678a3 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/TravelTimeComparison.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/TravelTimeComparison.java @@ -11,15 +11,14 @@ import org.matsim.application.options.OutputOptions; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.events.EventsUtils; -import org.matsim.core.router.FastDijkstraFactory; import org.matsim.core.router.costcalculators.OnlyTimeDependentTravelDisutility; +import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.TravelTime; import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; import org.matsim.core.trafficmonitoring.TravelTimeCalculator; import org.matsim.core.utils.io.IOUtils; import picocli.CommandLine; -import scala.util.parsing.combinator.testing.Str; import tech.tablesaw.api.ColumnType; import tech.tablesaw.api.DoubleColumn; import tech.tablesaw.api.Row; @@ -81,8 +80,8 @@ public Integer call() throws Exception { OnlyTimeDependentTravelDisutility util = new OnlyTimeDependentTravelDisutility(tt); - LeastCostPathCalculator congestedRouter = new FastDijkstraFactory(false).createPathCalculator(network, util, tt); - LeastCostPathCalculator freeflowRouter = new FastDijkstraFactory(false).createPathCalculator(network, new OnlyTimeDependentTravelDisutility(fs), fs); + LeastCostPathCalculator congestedRouter = new SpeedyALTFactory().createPathCalculator(network, util, tt); + LeastCostPathCalculator freeflowRouter = new SpeedyALTFactory().createPathCalculator(network, new OnlyTimeDependentTravelDisutility(fs), fs); data.addColumns( DoubleColumn.create("simulated", data.rowCount()), 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/application/prepare/population/AdjustActivityToLinkDistances.java b/contribs/application/src/main/java/org/matsim/application/prepare/population/AdjustActivityToLinkDistances.java index 33bb953f305..d0daecccda7 100644 --- a/contribs/application/src/main/java/org/matsim/application/prepare/population/AdjustActivityToLinkDistances.java +++ b/contribs/application/src/main/java/org/matsim/application/prepare/population/AdjustActivityToLinkDistances.java @@ -134,6 +134,7 @@ public Integer call() throws Exception { v = new Coord(coord.getX() - y * m, coord.getY() + x * m); } + v = CoordUtils.round(v); mapping.put(act.getCoord(), v); } diff --git a/contribs/application/src/main/java/org/matsim/application/prepare/population/ExtractHomeCoordinates.java b/contribs/application/src/main/java/org/matsim/application/prepare/population/ExtractHomeCoordinates.java index e8f343ffa1f..9ceef42f3e4 100644 --- a/contribs/application/src/main/java/org/matsim/application/prepare/population/ExtractHomeCoordinates.java +++ b/contribs/application/src/main/java/org/matsim/application/prepare/population/ExtractHomeCoordinates.java @@ -8,6 +8,7 @@ import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import org.matsim.core.population.PopulationUtils; +import org.matsim.core.utils.geometry.CoordUtils; import picocli.CommandLine; import java.nio.file.Path; @@ -15,10 +16,10 @@ import java.util.Map; @CommandLine.Command( - name = "extract-home-coordinates", - description = "Extract the home coordinates of a person" + name = "extract-home-coordinates", + description = "Extract the home coordinates of a person" ) -public class ExtractHomeCoordinates implements MATSimAppCommand { +public final class ExtractHomeCoordinates implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(ExtractHomeCoordinates.class); @@ -34,6 +35,29 @@ public class ExtractHomeCoordinates implements MATSimAppCommand { @CommandLine.Mixin private CsvOptions options = new CsvOptions(); + /** + * Set and return home coordinate of this person. Can be null if no home activity is known. + */ + public static Coord setHomeCoordinate(Person person) { + for (Plan plan : person.getPlans()) { + for (PlanElement planElement : plan.getPlanElements()) { + if (planElement instanceof Activity) { + String actType = ((Activity) planElement).getType(); + if (actType.startsWith("home")) { + Coord homeCoord = CoordUtils.round(((Activity) planElement).getCoord()); + + person.getAttributes().putAttribute("home_x", homeCoord.getX()); + person.getAttributes().putAttribute("home_y", homeCoord.getY()); + + return homeCoord; + } + } + } + } + + return null; + } + @Override public Integer call() throws Exception { @@ -42,24 +66,9 @@ public Integer call() throws Exception { Map coords = new LinkedHashMap<>(); for (Person person : population.getPersons().values()) { - outer: - for (Plan plan : person.getPlans()) { - for (PlanElement planElement : plan.getPlanElements()) { - if (planElement instanceof Activity) { - String actType = ((Activity) planElement).getType(); - if (actType.startsWith("home")) { - Coord homeCoord = ((Activity) planElement).getCoord(); - coords.put(person, homeCoord); - - person.getAttributes().putAttribute("home_x", homeCoord.getX()); - person.getAttributes().putAttribute("home_y", homeCoord.getY()); - - break outer; - } - } - } - - } + Coord coord = setHomeCoordinate(person); + if (coord != null) + coords.put(person, coord); } if (csv != null) { diff --git a/contribs/application/src/main/java/org/matsim/application/prepare/population/ResolveGridCoordinates.java b/contribs/application/src/main/java/org/matsim/application/prepare/population/ResolveGridCoordinates.java index 7c223d08484..c2cacd46992 100644 --- a/contribs/application/src/main/java/org/matsim/application/prepare/population/ResolveGridCoordinates.java +++ b/contribs/application/src/main/java/org/matsim/application/prepare/population/ResolveGridCoordinates.java @@ -14,6 +14,7 @@ import org.matsim.application.options.ShpOptions; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PopulationUtils; +import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.geometry.geotools.MGC; import picocli.CommandLine; @@ -93,7 +94,7 @@ public Integer call() throws Exception { Coord newCoord = mapping.getOrDefault(coord, null); if (newCoord == null) { - newCoord = landuse.select(crs.getInputCRS(), + newCoord = CoordUtils.round(landuse.select(crs.getInputCRS(), () -> { double x = rnd.nextDouble(-gridResolution / 2, gridResolution / 2); double y = rnd.nextDouble(-gridResolution / 2, gridResolution / 2); @@ -103,7 +104,7 @@ public Integer call() throws Exception { else return new Coord(coord.getX() + x, coord.getY() + y); } - ); + )); mapping.put(coord, newCoord); } 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 70e7f37a962..bc64ce1501a 100644 --- a/contribs/application/test/input/org/matsim/smallScaleCommercialTrafficGeneration/config_demand.xml +++ b/contribs/application/test/input/org/matsim/smallScaleCommercialTrafficGeneration/config_demand.xml @@ -47,7 +47,7 @@ - + @@ -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 a50d4e78394..d7c91a56d08 100644 --- a/contribs/commercialTrafficApplications/scenarios/grid/jointDemand_config.xml +++ b/contribs/commercialTrafficApplications/scenarios/grid/jointDemand_config.xml @@ -1,15 +1,6 @@ - - - - - - - - - @@ -47,7 +38,7 @@ - + @@ -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/DrtDashboard.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java index 291c0fbaf92..b7e1aeda0f9 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java @@ -140,11 +140,6 @@ public void configure(Header header, Layout layout) { viz.center = data.context().getCenter(); viz.zoom = data.context().mapZoomLevel; }) - //TODO group rejections per time bin. better put it into the plot with wait stats over daty time. -// .el(Line.class, (viz, data) -> { -// viz.dataset = data.output("ITERS/it." + lastIteration + "/*rejections_" + drtConfigGroup.mode + ".csv"); -// viz.x = "time"; -// }) ; // This plot is not absolutely necesarry given the hex plots @@ -163,12 +158,13 @@ public void configure(Header header, Layout layout) { viz.title = "Final Demand and Wait Stats over day time"; viz.description = "Number of rides (customers) is displayed in bars, wait statistics in lines"; - Plotly.DataSet dataset = viz.addDataset(data.output("*_waitStats_" + drtConfigGroup.mode + ".csv")); + Plotly.DataSet waitStats = viz.addDataset(data.output("*_waitStats_" + drtConfigGroup.mode + ".csv")); + Plotly.DataSet rejections = viz.addDataset(data.output("*drt_rejections_perTimeBin_" + drtConfigGroup.mode + ".csv")); viz.layout = tech.tablesaw.plotly.components.Layout.builder() .xAxis(Axis.builder().title("Time Bin").build()) .yAxis(Axis.builder().title("Wait Time [s]").build()) - .yAxis2(Axis.builder().title("Nr of Rides") + .yAxis2(Axis.builder().title("Nr of Rides/Rejections") .side(Axis.Side.right) .overlaying(ScatterTrace.YAxis.Y) .build()) @@ -179,7 +175,7 @@ public void configure(Header header, Layout layout) { .mode(ScatterTrace.Mode.LINE) .name("Average") .build(), - dataset.mapping() + waitStats.mapping() .x("timebin") .y("average_wait") ); @@ -188,7 +184,7 @@ public void configure(Header header, Layout layout) { .mode(ScatterTrace.Mode.LINE) .name("P5") .build(), - dataset.mapping() + waitStats.mapping() .x("timebin") .y("p_5") ); @@ -197,7 +193,7 @@ public void configure(Header header, Layout layout) { .mode(ScatterTrace.Mode.LINE) .name("P95") .build(), - dataset.mapping() + waitStats.mapping() .x("timebin") .y("p_95") ); @@ -207,11 +203,21 @@ public void configure(Header header, Layout layout) { .yAxis(ScatterTrace.YAxis.Y2.toString()) .name("Rides") .build(), - dataset.mapping() + waitStats.mapping() .x("timebin") .y("legs") ); + viz.addTrace(BarTrace.builder(Plotly.OBJ_INPUT, Plotly.INPUT) + .opacity(0.3) + .yAxis(ScatterTrace.YAxis.Y2.toString()) + .name("Rejections") + .build(), + rejections.mapping() + .x("timebin") + .y("rejections") + ); + }) .el(Area.class, (viz, data) -> { viz.title = "Vehicle occupancy"; //actually, without title the area plot won't work @@ -248,7 +254,7 @@ public void configure(Header header, Layout layout) { dataset.mapping() .x("iteration") .y("rejections") - .color(Plotly.ColorScheme.RdBu) +// .color(Plotly.ColorScheme.RdBu) ); viz.addTrace(BarTrace.builder(Plotly.OBJ_INPUT, Plotly.INPUT) @@ -257,7 +263,7 @@ public void configure(Header header, Layout layout) { dataset.mapping() .x("iteration") .y("rides") - .color(Plotly.ColorScheme.RdBu) +// .color(Plotly.ColorScheme.RdBu) ); }) @@ -294,7 +300,7 @@ public void configure(Header header, Layout layout) { dataset.mapping() .x("iteration") .y("inVehicleTravelTime_mean") - .color(Plotly.ColorScheme.RdBu) +// .color(Plotly.ColorScheme.RdBu) ); viz.addTrace(BarTrace.builder(Plotly.OBJ_INPUT, Plotly.INPUT) @@ -304,7 +310,7 @@ public void configure(Header header, Layout layout) { dataset.mapping() .x("iteration") .y("wait_average") - .color(Plotly.ColorScheme.RdBu) +// .color(Plotly.ColorScheme.RdBu) ); }) .el(Line.class, (viz, data) -> { 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/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/eshifts/charging/ChargingChangeoverActivity.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/charging/ChargingChangeoverActivity.java index 2c5d784e8da..f5771c79f09 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/charging/ChargingChangeoverActivity.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/charging/ChargingChangeoverActivity.java @@ -25,9 +25,9 @@ public ChargingChangeoverActivity(ChargingTask chargingTask, PassengerHandler pa DynAgent driver, StayTask task, Map, ? extends AcceptedDrtRequest> dropoffRequests, Map, ? extends AcceptedDrtRequest> pickupRequests) { - chargingDelegate = new FixedTimeChargingActivity(chargingTask, task.getEndTime()); - busStopDelegate = new DrtStopActivity(passengerHandler, driver, task, dropoffRequests, pickupRequests, ""); endTime = task.getEndTime(); + chargingDelegate = new FixedTimeChargingActivity(chargingTask, endTime); + busStopDelegate = new DrtStopActivity(passengerHandler, driver, () -> endTime, dropoffRequests, pickupRequests, ""); } @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/operations/shifts/schedule/ShiftDrtActionCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java index 42c7c18db1a..0f65e1208f0 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java @@ -32,11 +32,11 @@ public DynAction createAction(DynAgent dynAgent, DvrpVehicle vehicle, double now Task task = vehicle.getSchedule().getCurrentTask(); if (task instanceof ShiftBreakTask) { DrtStopTask t = (DrtStopTask)task; - return new DrtStopActivity(passengerHandler, dynAgent, t, t.getDropoffRequests(), t.getPickupRequests(), + return new DrtStopActivity(passengerHandler, dynAgent, t::getEndTime, t.getDropoffRequests(), t.getPickupRequests(), DRT_SHIFT_BREAK_NAME); } else if (task instanceof ShiftChangeOverTask) { DrtStopTask t = (DrtStopTask) task; - return new DrtStopActivity(passengerHandler, dynAgent, t, t.getDropoffRequests(), t.getPickupRequests(), + return new DrtStopActivity(passengerHandler, dynAgent, t::getEndTime, t.getDropoffRequests(), t.getPickupRequests(), DRT_SHIFT_CHANGEOVER_NAME); } else if (task instanceof WaitForShiftStayTask) { return new IdleDynActivity(DRT_SHIFT_WAIT_FOR_SHIFT_NAME, task::getEndTime); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java index 8b076be9b0d..f5101d68987 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java @@ -4,7 +4,6 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; import org.matsim.contrib.drt.extension.operations.shifts.schedule.*; @@ -26,7 +25,7 @@ import org.matsim.contrib.dvrp.tracker.OnlineDriveTaskTracker; import org.matsim.contrib.dvrp.util.LinkTimePair; import org.matsim.core.mobsim.framework.MobsimTimer; -import org.matsim.core.router.FastAStarEuclideanFactory; +import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; @@ -60,7 +59,7 @@ public ShiftTaskSchedulerImpl(Network network, TravelTime travelTime, TravelDisu this.taskFactory = taskFactory; this.network = network; this.drtShiftParams = drtShiftParams; - this.router = new FastAStarEuclideanFactory().createPathCalculator(network, travelDisutility, travelTime); + this.router = new SpeedyALTFactory().createPathCalculator(network, travelDisutility, travelTime); ShiftSchedules.initSchedules(operationFacilities, fleet, taskFactory); } 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 c6ad3f7dff8..2f88290727e 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/src/main/java/org/matsim/contrib/drt/analysis/DrtAnalysisControlerListener.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/DrtAnalysisControlerListener.java index 7fd5197abe8..ab98bfcc71a 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 @@ -19,31 +19,7 @@ package org.matsim.contrib.drt.analysis; -import static java.util.stream.Collectors.toList; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.io.BufferedWriter; -import java.io.FileOutputStream; -import java.io.IOException; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.TreeMap; -import java.util.function.Function; -import java.util.stream.Collectors; - +import com.google.common.base.Preconditions; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.logging.log4j.LogManager; @@ -70,12 +46,13 @@ import org.matsim.contrib.drt.passenger.events.DrtRequestSubmittedEvent; import org.matsim.contrib.drt.run.DrtConfigGroup; import org.matsim.contrib.drt.schedule.DrtStayTask; +import org.matsim.contrib.dvrp.analysis.VehicleOccupancyProfileCalculator; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.fleet.DvrpVehicleSpecification; import org.matsim.contrib.dvrp.fleet.FleetSpecification; import org.matsim.contrib.dvrp.optimizer.Request; import org.matsim.contrib.dvrp.passenger.PassengerPickedUpEvent; -import org.matsim.contrib.dvrp.analysis.VehicleOccupancyProfileCalculator; +import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEvent; import org.matsim.core.config.Config; import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.controler.MatsimServices; @@ -87,7 +64,20 @@ import org.matsim.core.utils.misc.Time; import org.matsim.vehicles.Vehicle; -import com.google.common.base.Preconditions; +import java.awt.*; +import java.io.BufferedWriter; +import java.io.FileOutputStream; +import java.io.IOException; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static java.util.stream.Collectors.toList; /** * @author jbischoff @@ -120,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)); @@ -163,7 +153,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); @@ -176,6 +166,13 @@ public void notifyIterationEnds(IterationEndsEvent event) { .sorted(Comparator.comparing(leg -> leg.departureTime)) .collect(toList()); + List rejectionEvents = drtEventSequenceCollector.getRejectedRequestSequences() + .values() + .stream() + .map(eventSequence -> eventSequence.getRejected().get()) + .sorted(Comparator.comparing(rejectionEvent -> rejectionEvent.getTime())) + .collect(toList()); + collection2Text(drtEventSequenceCollector.getRejectedRequestSequences().values(), filename(event, "drt_rejections", ".csv"), String.join(delimiter, "time", "personId", "fromLinkId", "toLinkId", "fromX", "fromY", "toX", "toY"), seq -> { DrtRequestSubmittedEvent submission = seq.getSubmitted(); @@ -252,6 +249,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { writeVehicleDistances(drtVehicleStats.getVehicleStates(), filename(event, "vehicleDistanceStats", ".csv"), delimiter); analyseDetours(network, legs, drtVehicleStats.getTravelDistances(), drtCfg, filename(event, "drt_detours"), createGraphs, delimiter); analyseWaitTimes(filename(event, "waitStats"), legs, 1800, createGraphs, delimiter); + analyseRejections(filename(event,"drt_rejections_perTimeBin"), rejectionEvents,1800, createGraphs, delimiter); analyseConstraints(filename(event, "constraints"), legs, createGraphs); double endTime = qSimCfg.getEndTime() @@ -399,6 +397,7 @@ public void notifyShutdown(ShutdownEvent event) { dumpOutput(event.getIteration(), "waitTimeComparison", ".png"); dumpOutput(event.getIteration(), "waitTimeComparison", ".csv"); dumpOutput(event.getIteration(), "drt_rejections", ".csv"); + dumpOutput(event.getIteration(), "drt_rejections_perTimeBin", ".csv"); dumpOutput(event.getIteration(), "drt_legs", ".csv"); dumpOutput(event.getIteration(), "vehicleDistanceStats", ".csv"); dumpOutput(event.getIteration(), "drt_detours", ".csv"); @@ -453,6 +452,33 @@ private static Map> splitLegsIntoBins(Collection le return splitLegs; } + private static Map> splitEventsIntoBins(List rejectionEvents, int binSize_s) { + Map> rejections = new TreeMap<>(); + + int startTime = ((int)(rejectionEvents.get(0).getTime() / binSize_s)) * binSize_s; + int endTime = ((int)(rejectionEvents.get(rejectionEvents.size() - 1).getTime() / binSize_s) + 1) * binSize_s; + + for (int time = startTime; time < endTime; time = time + binSize_s) { + + // rejection list in this timebin + List rejectionList = new ArrayList<>(); + + //Iterate through each rejection + for (PassengerRequestRejectedEvent rejectedEvent : rejectionEvents){ + double rejectionTime = rejectedEvent.getTime(); + if (rejectionTime > endTime || rejectionTime < startTime) { + LogManager.getLogger(DrtAnalysisControlerListener.class).error("wrong end / start Times for analysis"); + } + + if (rejectionTime > time && rejectionTime < time + binSize_s) { + rejectionList.add(rejectedEvent); + } + } + rejections.put((double)time, rejectionList); + } + return rejections; + } + private static void analyzeBoardingsAndDeboardings(List legs, String delimiter, double startTime, double endTime, double timeBinSize, String boardingsFile, String deboardingsFile, Network network) { if (endTime < startTime) { @@ -708,6 +734,55 @@ private static void analyseWaitTimes(String fileName, List legs, int bin } + private static void analyseRejections(String fileName, List rejectionEvents, int binsize_s, boolean createGraphs, String delimiter) { + if (rejectionEvents.size() == 0) + return; + + Map> splitEvents = splitEventsIntoBins(rejectionEvents, binsize_s); + + DecimalFormat format = new DecimalFormat(); + format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); + format.setMinimumIntegerDigits(1); + format.setMaximumFractionDigits(2); + format.setGroupingUsed(false); + + SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss"); + + BufferedWriter bw = IOUtils.getBufferedWriter(fileName + ".csv"); + TimeSeriesCollection dataset = new TimeSeriesCollection(); + TimeSeries rejections = new TimeSeries("number of rejections"); + + try { + bw.write(String.join(delimiter, "timebin", "rejections")); + + for(Map.Entry> e : splitEvents.entrySet()){ + int drt_numOfRejection = 0; + if (!e.getValue().isEmpty()) { + drt_numOfRejection = e.getValue().size(); + } + + Minute h = new Minute(sdf2.parse(Time.writeTime(e.getKey()))); + + rejections.addOrUpdate(h, Double.valueOf(drt_numOfRejection)); + bw.newLine(); + bw.write(String.join(delimiter, Time.writeTime(e.getKey()) + "",// + format.format(drt_numOfRejection) +"")); + } + + bw.flush(); + bw.close(); + if (createGraphs) { + dataset.addSeries(rejections); + JFreeChart chart = chartProfile(splitEvents.size(), dataset, "Number of rejections", "Number"); + ChartSaveUtils.saveAsPNG(chart, fileName, 1500, 1000); + } + + } catch (IOException | ParseException e) { + + e.printStackTrace(); + } + } + private static JFreeChart chartProfile(int length, TimeSeriesCollection dataset, String descriptor, String yax) { JFreeChart chart = ChartFactory.createTimeSeriesChart(descriptor, "Time", yax, dataset); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/DefaultDrtOptimizer.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/DefaultDrtOptimizer.java index 0c7fd8da55e..5eef0f27f20 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/DefaultDrtOptimizer.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/DefaultDrtOptimizer.java @@ -26,7 +26,6 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.drt.optimizer.depot.DepotFinder; -import org.matsim.contrib.drt.optimizer.depot.Depots; import org.matsim.contrib.drt.optimizer.insertion.UnplannedRequestInserter; import org.matsim.contrib.drt.optimizer.rebalancing.RebalancingStrategy; import org.matsim.contrib.drt.optimizer.rebalancing.RebalancingStrategy.Relocation; @@ -43,6 +42,8 @@ import org.matsim.core.mobsim.framework.MobsimTimer; import org.matsim.core.mobsim.framework.events.MobsimBeforeSimStepEvent; +import static org.matsim.contrib.drt.schedule.DrtTaskBaseType.STAY; + /** * @author michalm */ @@ -95,6 +96,7 @@ public void notifyMobsimBeforeSimStep(@SuppressWarnings("rawtypes") MobsimBefore requestInserter.scheduleUnplannedRequests(unplannedRequests.getSchedulableRequests()); } + relocateVehiclesToDepot(drtCfg.returnToDepotEvaluationInterval, drtCfg.returnToDepotTimeout); if (rebalancingInterval != null && e.getSimulationTime() % rebalancingInterval == 0) { if (!scheduleTimingUpdated) { for (DvrpVehicle v : fleet.getVehicles().values()) { @@ -116,7 +118,7 @@ private void rebalanceFleet() { for (Relocation r : relocations) { Link currentLink = ((DrtStayTask)r.vehicle.getSchedule().getCurrentTask()).getLink(); if (currentLink != r.link) { - relocator.relocateVehicle(r.vehicle, r.link); + relocator.relocateVehicle(r.vehicle, r.link, EmptyVehicleRelocator.RELOCATE_VEHICLE_TASK_TYPE); } } } @@ -130,15 +132,29 @@ public void requestSubmitted(Request request) { @Override public void nextTask(DvrpVehicle vehicle) { scheduleTimingUpdater.updateBeforeNextTask(vehicle); - vehicle.getSchedule().nextTask(); + } - // if STOP->STAY then choose the best depot - if (drtCfg.idleVehiclesReturnToDepots && Depots.isSwitchingFromStopToStay(vehicle)) { - Link depotLink = depotFinder.findDepot(vehicle); - if (depotLink != null) { - relocator.relocateVehicle(vehicle, depotLink); - } + private void relocateVehiclesToDepot(double evaluationInterval, double timeout) { + if (drtCfg.idleVehiclesReturnToDepots && mobsimTimer.getTimeOfDay() % evaluationInterval == 0) { + fleet.getVehicles().values().stream() + .filter(scheduleInquiry::isIdle) + .filter(v -> stayTimeoutExceeded(v, timeout)) + .forEach(v -> { + Link depotLink = depotFinder.findDepot(v); + if (depotLink != null) { + relocator.relocateVehicle(v, depotLink, EmptyVehicleRelocator.RELOCATE_VEHICLE_TO_DEPOT_TASK_TYPE); + } + }); + } + } + + boolean stayTimeoutExceeded(DvrpVehicle vehicle, double timeout) { + if (STAY.isBaseTypeOf(vehicle.getSchedule().getCurrentTask())) { + double now = mobsimTimer.getTimeOfDay(); + double taskStart = vehicle.getSchedule().getCurrentTask().getBeginTime(); + return (now - taskStart) > timeout; } + return false; } } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/VehicleDataEntryFactoryImpl.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/VehicleDataEntryFactoryImpl.java index 1b5ec6a5d94..98b961e2204 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/VehicleDataEntryFactoryImpl.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/VehicleDataEntryFactoryImpl.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.List; +import org.matsim.contrib.drt.passenger.AcceptedDrtRequest; import org.matsim.contrib.drt.run.DrtConfigGroup; import org.matsim.contrib.drt.schedule.DrtStopTask; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; @@ -100,31 +101,40 @@ public VehicleEntry create(DvrpVehicle vehicle, double currentTime) { Waypoint.Stop s = stops[i] = new Waypoint.Stop(stopTasks.get(i), outgoingOccupancy); outgoingOccupancy -= s.getOccupancyChange(); } + + Waypoint.Stop startStop = startTask != null && STOP.isBaseTypeOf(startTask) + ? new Waypoint.Stop((DrtStopTask) startTask, 0) + : null; - var slackTimes = computeSlackTimes(vehicle, currentTime, stops); + var slackTimes = computeSlackTimes(vehicle, currentTime, stops, startStop); return new VehicleEntry(vehicle, new Waypoint.Start(startTask, start.link, start.time, outgoingOccupancy), - ImmutableList.copyOf(stops), slackTimes); + ImmutableList.copyOf(stops), slackTimes, currentTime); } public boolean isNotEligibleForRequestInsertion(DvrpVehicle vehicle, double currentTime) { return currentTime + lookAhead < vehicle.getServiceBeginTime() || currentTime >= vehicle.getServiceEndTime(); } - static double[] computeSlackTimes(DvrpVehicle vehicle, double now, Waypoint.Stop[] stops) { - double[] slackTimes = new double[stops.length + 1]; + static double[] computeSlackTimes(DvrpVehicle vehicle, double now, Waypoint.Stop[] stops, Waypoint.Stop start) { + double[] slackTimes = new double[stops.length + 2]; //vehicle double slackTime = calcVehicleSlackTime(vehicle, now); - slackTimes[stops.length] = slackTime; + slackTimes[stops.length + 1] = slackTime; //stops for (int i = stops.length - 1; i >= 0; i--) { var stop = stops[i]; slackTime = Math.min(stop.latestArrivalTime - stop.task.getBeginTime(), slackTime); slackTime = Math.min(stop.latestDepartureTime - stop.task.getEndTime(), slackTime); - slackTimes[i] = slackTime; + slackTimes[i + 1] = slackTime; } + + // start + slackTimes[0] = start == null ? slackTime : + Math.min(start.latestDepartureTime - start.task.getEndTime(), slackTime); + return slackTimes; } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/VehicleEntry.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/VehicleEntry.java index b79c3523f33..df2bd47957b 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/VehicleEntry.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/VehicleEntry.java @@ -37,14 +37,16 @@ public interface EntryFactory { public final ImmutableList stops; public final Waypoint.End end; private final double[] slackTimes;// for all insertion points + public final double createTime; public VehicleEntry(DvrpVehicle vehicle, Waypoint.Start start, ImmutableList stops, - double[] slackTimes) { + double[] slackTimes, double createTime) { this.vehicle = vehicle; this.start = start; this.stops = stops; this.end = Waypoint.End.OPEN_END; this.slackTimes = slackTimes; + this.createTime = createTime; } protected VehicleEntry(VehicleEntry that) { @@ -53,6 +55,7 @@ protected VehicleEntry(VehicleEntry that) { this.stops = that.stops; this.end = that.end; this.slackTimes = that.slackTimes; + this.createTime = that.createTime; } public Waypoint getWaypoint(int index) { @@ -64,6 +67,10 @@ public boolean isAfterLastStop(int index) { } public double getSlackTime(int index) { - return slackTimes[index]; + return slackTimes[index + 1]; + } + + public double getStartSlackTime() { + return slackTimes[0]; } } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculator.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculator.java index 9ff3a41e82d..4e0006320cc 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculator.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculator.java @@ -152,39 +152,8 @@ private PickupTimeInfo calculatePickupIfSameLink(VehicleEntry vEntry, int pickup return new PickupTimeInfo(departureTime, additionalStopDuration); } else { // case 3: previous waypoint is an ongoing (started) stop - // insertion is the beginning of the planned stop (traditionally) - - /* - * TODO: Generally, DRT is allowed to insert pickups into ongoing stop tasks. - * However, currently, stop tasks have a fixed duration that is never changed. - * This means that a pickup is added to an ongoing task that will end, maybe in - * 20s. The task will then end regardless of the added pickup. The request will, - * hence, have a wait time of 20s although the configured stop duration may be - * 60s. We can even frequently have requests with zero wait time. - * - * To mitigate the problem, the following steps are necessary: - * - Impose here not the stopTask.beginTime as the time at which the request is inserted, - * but impose the current time ("now") as the point of insertion. - * - The underlying StopTimeCalculator should make proper use of this information and - * *extend* the stop task here in the insertion algorithm. - * - This should equally be done in RequestInsertionScheduler where the stop task must be - * extended according to the information given by StopTimeCalculator. - * - The DrtStopActvity should not be based on the endTime of the stop that is known at - * time of construction, but it should depend dynamically on the end time (basically, - * like a stay task). - * - Finally, all of this means that by adding a pickup to an ongoing stop and, potentially, - * shifting the end time of the task, we may shift already assigned pick-ups beyond their - * latestDepartureTime. Testing for this requires to extend the definition of slack times. - * Specifically, VehicleEntryFactoryImpl only generates the slack *after* the start of the - * schedule. In an empty schedule this is the slack from the initial stay to the end time - * of the vehicle service. Hence, we need to introduce a "start slack" that indicates the - * slack at the very beginning of the schedule (i.e., how far can I extend the start stop - * if there is any to maintain a valid timing). - */ - - double insertionTime = stopTask.getBeginTime(); - double departureTime = stopTimeCalculator.updateEndTimeForPickup(vEntry.vehicle, stopTask, - insertionTime, request); + // insertion is a soon as possible (now) + double departureTime = stopTimeCalculator.updateEndTimeForPickup(vEntry.vehicle, stopTask, vEntry.createTime, request); double additionalStopDuration = departureTime - stopTask.getEndTime(); return new PickupTimeInfo(departureTime, additionalStopDuration); } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGenerator.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGenerator.java index 55d381daf01..1316ccde366 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGenerator.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGenerator.java @@ -27,8 +27,10 @@ import org.matsim.contrib.drt.optimizer.insertion.InsertionDetourTimeCalculator.DetourTimeInfo; import org.matsim.contrib.drt.optimizer.insertion.InsertionDetourTimeCalculator.PickupDetourInfo; import org.matsim.contrib.drt.passenger.DrtRequest; -import org.matsim.contrib.drt.stops.PassengerStopDurationProvider; +import org.matsim.contrib.drt.schedule.DrtStopTask; +import org.matsim.contrib.drt.schedule.DrtTaskBaseType; import org.matsim.contrib.drt.stops.StopTimeCalculator; +import org.matsim.contrib.dvrp.schedule.Task; import com.google.common.base.MoreObjects; @@ -180,6 +182,11 @@ private void generateDropoffInsertions(DrtRequest request, VehicleEntry vEntry, toPickupDepartureTime + toPickupTT); //TODO stopDuration not included var pickupDetourInfo = detourTimeCalculator.calcPickupDetourInfo(vEntry, pickupInsertion, toPickupTT, fromPickupTT, true, request); + + if (i == 0 && !checkStartSlack(vEntry, request, pickupDetourInfo)) { + // Inserting at schedule start and extending an ongoing stop task further than allowed + return; + } int stopCount = vEntry.stops.size(); // i == j @@ -252,6 +259,26 @@ private Waypoint.Stop currentStop(VehicleEntry entry, int insertionIdx) { private Waypoint.Stop nextStop(VehicleEntry entry, int insertionIdx) { return entry.stops.get(insertionIdx); } + + private boolean checkStartSlack(VehicleEntry vEntry, DrtRequest request, PickupDetourInfo pickupDetourInfo) { + if (vEntry.start.task.isEmpty()) { + return true; + } + + Task startTask = vEntry.start.task.get(); + + if (!DrtTaskBaseType.STOP.isBaseTypeOf(startTask)) { + return true; + } + + DrtStopTask stopTask = (DrtStopTask) startTask; + + if (stopTask.getLink() != request.getFromLink()) { + return true; + } + + return vEntry.getStartSlackTime() >= pickupDetourInfo.departureTime - stopTask.getEndTime(); + } private InsertionWithDetourData createInsertionWithDetourData(DrtRequest request, VehicleEntry vehicleEntry, InsertionPoint pickupInsertion, double fromPickupTT, PickupDetourInfo pickupDetourInfo, int dropoffIdx) { diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/CustomRebalancingStrategyParams.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/CustomRebalancingStrategyParams.java new file mode 100644 index 00000000000..266229bc349 --- /dev/null +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/CustomRebalancingStrategyParams.java @@ -0,0 +1,33 @@ +/* *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 2023 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.optimizer.rebalancing; + +import org.matsim.core.config.ReflectiveConfigGroup; + +/** + * Custom rebalancing strategy parameters. User is responsible for installing rebalancing module and parameters. + */ +public final class CustomRebalancingStrategyParams extends ReflectiveConfigGroup + implements RebalancingParams.RebalancingStrategyParams { + public static final String SET_NAME = "CustomRebalancingStrategy"; + + public CustomRebalancingStrategyParams() { + super(SET_NAME); + } +} diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/RebalancingModule.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/RebalancingModule.java index a263bca4e35..b9c008bc3a1 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/RebalancingModule.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/RebalancingModule.java @@ -54,6 +54,8 @@ public void install() { install(new DrtModePlusOneRebalanceModule(drtCfg)); } else if (rebalancingParams.getRebalancingStrategyParams() instanceof FeedforwardRebalancingStrategyParams) { install(new DrtModeFeedforwardRebalanceModule(drtCfg)); + } else if (rebalancingParams.getRebalancingStrategyParams() instanceof CustomRebalancingStrategyParams) { + // User is responsible for installing custom module } else { throw new RuntimeException( "Unsupported rebalancingStrategyParams: " + rebalancingParams.getRebalancingStrategyParams()); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/RebalancingParams.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/RebalancingParams.java index 09c826427c4..07b422912d9 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/RebalancingParams.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/rebalancing/RebalancingParams.java @@ -79,6 +79,9 @@ private void initSingletonParameterSets() { addDefinition(PlusOneRebalancingStrategyParams.SET_NAME, PlusOneRebalancingStrategyParams::new, () -> (ConfigGroup)rebalancingStrategyParams, params -> rebalancingStrategyParams = (RebalancingStrategyParams)params); + addDefinition(CustomRebalancingStrategyParams.SET_NAME, CustomRebalancingStrategyParams::new, + () -> (ConfigGroup)rebalancingStrategyParams, + params -> rebalancingStrategyParams = (RebalancingStrategyParams)params); } @Override diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/passenger/DrtStopActivity.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/passenger/DrtStopActivity.java index 6d7a375efe7..e646c761df1 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/passenger/DrtStopActivity.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/passenger/DrtStopActivity.java @@ -21,6 +21,7 @@ package org.matsim.contrib.drt.passenger; import java.util.Map; +import java.util.function.Supplier; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Person; @@ -42,11 +43,11 @@ public class DrtStopActivity extends FirstLastSimStepDynActivity implements Pass private final DynAgent driver; private final Map, ? extends AcceptedDrtRequest> dropoffRequests; private final Map, ? extends AcceptedDrtRequest> pickupRequests; - private final double expectedEndTime; + private final Supplier endTime; private int passengersPickedUp = 0; - public DrtStopActivity(PassengerHandler passengerHandler, DynAgent driver, StayTask task, + public DrtStopActivity(PassengerHandler passengerHandler, DynAgent driver, Supplier endTime, Map, ? extends AcceptedDrtRequest> dropoffRequests, Map, ? extends AcceptedDrtRequest> pickupRequests, String activityType) { super(activityType); @@ -54,12 +55,12 @@ public DrtStopActivity(PassengerHandler passengerHandler, DynAgent driver, StayT this.driver = driver; this.dropoffRequests = dropoffRequests; this.pickupRequests = pickupRequests; - this.expectedEndTime = task.getEndTime(); + this.endTime = endTime; } @Override protected boolean isLastStep(double now) { - return passengersPickedUp == pickupRequests.size() && now >= expectedEndTime; + return passengersPickedUp == pickupRequests.size() && now >= endTime.get(); } @Override @@ -72,7 +73,7 @@ protected void beforeFirstStep(double now) { @Override protected void simStep(double now) { - if (now == expectedEndTime) { + if (now == endTime.get()) { for (var request : pickupRequests.values()) { if (passengerHandler.tryPickUpPassenger(this, driver, request.getId(), now)) { passengersPickedUp++; @@ -83,7 +84,7 @@ protected void simStep(double now) { @Override public void notifyPassengerIsReadyForDeparture(MobsimPassengerAgent passenger, double now) { - if (now < expectedEndTime) { + if (now < endTime.get()) { return;// pick up only at the end of stop activity } 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 43c2cff26fb..5b54e43eb45 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; @@ -130,6 +130,15 @@ public static DrtConfigGroup getSingleModeDrtConfig(Config config) { @Comment("Idle vehicles return to the nearest of all start links. See: DvrpVehicle.getStartLink()") public boolean idleVehiclesReturnToDepots = false; + @Parameter + @Comment("Specifies the duration (seconds) a vehicle needs to be idle in order to get send back to the depot." + + "Please be aware, that returnToDepotEvaluationInterval describes the minimal time a vehicle will be idle before it gets send back to depot.") + public double returnToDepotTimeout = 60; + + @Parameter + @Comment("Specifies the time interval (seconds) a vehicle gets evaluated to be send back to depot.") + public double returnToDepotEvaluationInterval = 60; + public enum OperationalScheme { stopbased, door2door, serviceAreaBased } @@ -273,6 +282,11 @@ protected void checkConsistency(Config config) { + " in order to speed up the DRT route update during the replanning phase."); } + if (this.idleVehiclesReturnToDepots && this.returnToDepotTimeout < this.returnToDepotEvaluationInterval) { + log.warn("idleVehiclesReturnToDepots is active and returnToDepotTimeout < returnToDepotEvaluationInterval. " + + "Vehicles will be send back to depot after {} seconds",returnToDepotEvaluationInterval); + } + Verify.verify(getParameterSets(MinCostFlowRebalancingStrategyParams.SET_NAME).size() <= 1, "More than one rebalancing parameter sets is specified"); @@ -311,7 +325,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 6176da047c8..fac873dbb8e 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 @@ -77,16 +77,16 @@ 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)); }); - + 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/scheduler/DefaultRequestInsertionScheduler.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/scheduler/DefaultRequestInsertionScheduler.java index 9f184486755..5f40c9a80f6 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/scheduler/DefaultRequestInsertionScheduler.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/scheduler/DefaultRequestInsertionScheduler.java @@ -126,6 +126,7 @@ private void verifyTimes(String messageStart, double timeFromInsertionData, doub } private DrtStopTask insertPickup(AcceptedDrtRequest request, InsertionWithDetourData insertionWithDetourData) { + final double now = timer.getTimeOfDay(); var insertion = insertionWithDetourData.insertion; VehicleEntry vehicleEntry = insertion.vehicleEntry; Schedule schedule = vehicleEntry.vehicle.getSchedule(); @@ -164,7 +165,6 @@ private DrtStopTask insertPickup(AcceptedDrtRequest request, InsertionWithDetour stayTask.setEndTime(stayTask.getBeginTime());// could get later removed with ScheduleTimingUpdater } else if (STAY.isBaseTypeOf(currentTask)) { stayTask = (DrtStayTask)currentTask; // ongoing stay task - double now = timer.getTimeOfDay(); if (stayTask.getEndTime() > now) { // stop stay task; a new stop/drive task can be inserted now stayTask.setEndTime(now); } @@ -179,15 +179,9 @@ private DrtStopTask insertPickup(AcceptedDrtRequest request, InsertionWithDetour // add pickup request to stop task stopTask.addPickupRequest(request); - /* - * TODO: insertionTime should be set to "now" here to avoid adding pickups to - * ongoing tasks "for free" and generating requests with zero wait time. See - * InsertionDetourTimeCalculator.calculatePickupIfSameLink for more details. - */ - - double insertionTime = stopTask.getBeginTime(); + // potentially extend task stopTask.setEndTime(stopTimeCalculator.updateEndTimeForPickup(vehicleEntry.vehicle, stopTask, - insertionTime, request.getRequest())); + now, request.getRequest())); /// ADDED //// TODO this is copied, but has not been updated !!!!!!!!!!!!!!! @@ -285,6 +279,7 @@ private DrtStopTask insertPickup(AcceptedDrtRequest request, InsertionWithDetour private DrtStopTask insertDropoff(AcceptedDrtRequest request, InsertionWithDetourData insertionWithDetourData, DrtStopTask pickupTask) { + final double now = timer.getTimeOfDay(); var insertion = insertionWithDetourData.insertion; VehicleEntry vehicleEntry = insertion.vehicleEntry; Schedule schedule = vehicleEntry.vehicle.getSchedule(); @@ -303,15 +298,9 @@ private DrtStopTask insertDropoff(AcceptedDrtRequest request, InsertionWithDetou // add dropoff request to stop task, and extend the stop task (when incremental stop task duration is used) stopTask.addDropoffRequest(request); - /* - * TODO: insertionTime should be set to "now" here to avoid adding pickups to - * ongoing tasks "for free" and generating requests with zero wait time. See - * InsertionDetourTimeCalculator.calculatePickupIfSameLink for more details. - */ - - double insertionTime = stopTask.getBeginTime(); + // potentially extend task stopTask.setEndTime(stopTimeCalculator.updateEndTimeForDropoff(vehicleEntry.vehicle, stopTask, - insertionTime, request.getRequest())); + now, request.getRequest())); scheduleTimingUpdater.updateTimingsStartingFromTaskIdx(vehicleEntry.vehicle, stopTask.getTaskIdx() + 1, stopTask.getEndTime()); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/scheduler/EmptyVehicleRelocator.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/scheduler/EmptyVehicleRelocator.java index 57567dd5634..98a1994e268 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/scheduler/EmptyVehicleRelocator.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/scheduler/EmptyVehicleRelocator.java @@ -41,6 +41,7 @@ */ public class EmptyVehicleRelocator { public static final DrtTaskType RELOCATE_VEHICLE_TASK_TYPE = new DrtTaskType("RELOCATE", DRIVE); + public static final DrtTaskType RELOCATE_VEHICLE_TO_DEPOT_TASK_TYPE = new DrtTaskType("RELOCATE_TO_DEPOT", DRIVE); private final TravelTime travelTime; private final MobsimTimer timer; @@ -55,7 +56,7 @@ public EmptyVehicleRelocator(Network network, TravelTime travelTime, TravelDisut router = new SpeedyALTFactory().createPathCalculator(network, travelDisutility, travelTime); } - public void relocateVehicle(DvrpVehicle vehicle, Link link) { + public void relocateVehicle(DvrpVehicle vehicle, Link link, DrtTaskType relocationTaskType) { DrtStayTask currentTask = (DrtStayTask)vehicle.getSchedule().getCurrentTask(); Link currentLink = currentTask.getLink(); @@ -63,12 +64,12 @@ public void relocateVehicle(DvrpVehicle vehicle, Link link) { VrpPathWithTravelData path = VrpPaths.calcAndCreatePath(currentLink, link, timer.getTimeOfDay(), router, travelTime); if (path.getArrivalTime() < vehicle.getServiceEndTime()) { - relocateVehicleImpl(vehicle, path); + relocateVehicleImpl(vehicle, path, relocationTaskType); } } } - private void relocateVehicleImpl(DvrpVehicle vehicle, VrpPathWithTravelData vrpPath) { + private void relocateVehicleImpl(DvrpVehicle vehicle, VrpPathWithTravelData vrpPath, DrtTaskType relocationTaskType) { Schedule schedule = vehicle.getSchedule(); DrtStayTask stayTask = (DrtStayTask)schedule.getCurrentTask(); if (stayTask.getTaskIdx() != schedule.getTaskCount() - 1) { @@ -76,7 +77,7 @@ private void relocateVehicleImpl(DvrpVehicle vehicle, VrpPathWithTravelData vrpP } stayTask.setEndTime(vrpPath.getDepartureTime()); // finish STAY - schedule.addTask(taskFactory.createDriveTask(vehicle, vrpPath, RELOCATE_VEHICLE_TASK_TYPE)); // add RELOCATE + schedule.addTask(taskFactory.createDriveTask(vehicle, vrpPath, relocationTaskType)); // add RELOCATE // append STAY schedule.addTask(taskFactory.createStayTask(vehicle, vrpPath.getArrivalTime(), vehicle.getServiceEndTime(), vrpPath.getToLink())); 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/main/java/org/matsim/contrib/drt/vrpagent/DrtActionCreator.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/vrpagent/DrtActionCreator.java index a1ced347d8a..1d57080e521 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/vrpagent/DrtActionCreator.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/vrpagent/DrtActionCreator.java @@ -63,7 +63,7 @@ public DynAction createAction(DynAgent dynAgent, DvrpVehicle vehicle, double now case STOP: DrtStopTask t = (DrtStopTask)task; - return new DrtStopActivity(passengerHandler, dynAgent, t, t.getDropoffRequests(), t.getPickupRequests(), + return new DrtStopActivity(passengerHandler, dynAgent, t::getEndTime, t.getDropoffRequests(), t.getPickupRequests(), DRT_STOP_NAME); case STAY: diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/VehicleDataEntryFactoryImplTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/VehicleDataEntryFactoryImplTest.java index 45fae689ef2..79bde9d12c8 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/VehicleDataEntryFactoryImplTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/VehicleDataEntryFactoryImplTest.java @@ -49,34 +49,46 @@ public class VehicleDataEntryFactoryImplTest { @Test public void computeSlackTimes_withStops() { //final stay task not started - vehicle slack time is 50 - assertThat(computeSlackTimes(vehicle(500, 450), 100, new Stop[] { stop0, stop1 })).containsExactly(20, 30, 50); + assertThat(computeSlackTimes(vehicle(500, 450), 100, new Stop[] { stop0, stop1 }, null)).containsExactly(20, 20, 30, 50); //final stay task not started - vehicle slack time is 25 and limits the slack times at stop1 - assertThat(computeSlackTimes(vehicle(500, 475), 100, new Stop[] { stop0, stop1 })).containsExactly(20, 25, 25); + assertThat(computeSlackTimes(vehicle(500, 475), 100, new Stop[] { stop0, stop1 }, null)).containsExactly(20, 20, 25, 25); //final stay task not started - vehicle slack time is 10 and limits the slack times at all stops - assertThat(computeSlackTimes(vehicle(500, 490), 100, new Stop[] { stop0, stop1 })).containsExactly(10, 10, 10); + assertThat(computeSlackTimes(vehicle(500, 490), 100, new Stop[] { stop0, stop1 }, null)).containsExactly(10, 10, 10, 10); } @Test public void computeSlackTimes_withoutStops() { //final stay task not started yet - vehicle slack time is 10 - assertThat(computeSlackTimes(vehicle(500, 490), 485, new Stop[] {})).containsExactly(10); + assertThat(computeSlackTimes(vehicle(500, 490), 485, new Stop[] {}, null)).containsExactly(10, 10); //final stay task just started - vehicle slack time is 10 - assertThat(computeSlackTimes(vehicle(500, 490), 490, new Stop[] {})).containsExactly(10); + assertThat(computeSlackTimes(vehicle(500, 490), 490, new Stop[] {}, null)).containsExactly(10, 10); //final stay task half completed - vehicle slack time is 5 - assertThat(computeSlackTimes(vehicle(500, 490), 495, new Stop[] {})).containsExactly(5); + assertThat(computeSlackTimes(vehicle(500, 490), 495, new Stop[] {}, null)).containsExactly(5, 5); //final stay task just completed - vehicle slack time is 0 - assertThat(computeSlackTimes(vehicle(500, 490), 500, new Stop[] {})).containsExactly(0); + assertThat(computeSlackTimes(vehicle(500, 490), 500, new Stop[] {}, null)).containsExactly(0, 0); //final stay task started, but delayed - vehicle slack time is 0 - assertThat(computeSlackTimes(vehicle(500, 510), 510, new Stop[] {})).containsExactly(0); + assertThat(computeSlackTimes(vehicle(500, 510), 510, new Stop[] {}, null)).containsExactly(0, 0); //final stay task planned after vehicle end time - vehicle slack time is 0s - assertThat(computeSlackTimes(vehicle(500, 510), 300, new Stop[] {})).containsExactly(0); + assertThat(computeSlackTimes(vehicle(500, 510), 300, new Stop[] {}, null)).containsExactly(0, 0); + } + + @Test + public void computeSlackTimes_withStart() { + //start without stop + assertThat(computeSlackTimes(vehicle(500, 450), 100, new Stop[] {}, stop0)).containsExactly(30, 50); + + //start without stop + assertThat(computeSlackTimes(vehicle(500, 450), 100, new Stop[] {}, stop1)).containsExactly(30, 50); + + //start with stop + assertThat(computeSlackTimes(vehicle(500, 450), 100, new Stop[] { stop1 }, stop0)).containsExactly(30, 30, 50); } private Stop stop(double beginTime, double latestArrivalTime, double endTime, double latestDepartureTime) { diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/BestInsertionFinderTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/BestInsertionFinderTest.java index cc7fdac6b04..14b8c359ec5 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/BestInsertionFinderTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/BestInsertionFinderTest.java @@ -132,7 +132,7 @@ private void whenInsertionThenCost(InsertionWithDetourData insertion, double cos private InsertionWithDetourData insertion(String vehicleId, int pickupIdx, int dropoffIdx) { var vehicle = mock(DvrpVehicle.class); when(vehicle.getId()).thenReturn(Id.create(vehicleId, DvrpVehicle.class)); - var vehicleEntry = new VehicleEntry(vehicle, null, null, null); + var vehicleEntry = new VehicleEntry(vehicle, null, null, null, 0); var pickupInsertion = new InsertionGenerator.InsertionPoint(pickupIdx, null, null, null); var dropoffInsertion = new InsertionGenerator.InsertionPoint(dropoffIdx, null, null, null); diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/DefaultUnplannedRequestInserterTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/DefaultUnplannedRequestInserterTest.java index afb8b62cc58..dcdc662f335 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/DefaultUnplannedRequestInserterTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/DefaultUnplannedRequestInserterTest.java @@ -197,7 +197,7 @@ public void acceptedRequest() { var unplannedRequests = requests(request1); double now = 15; - var vehicle1Entry = new VehicleEntry(vehicle1, null, null, null); + var vehicle1Entry = new VehicleEntry(vehicle1, null, null, null, 0); var createEntryCounter = new MutableInt(); VehicleEntry.EntryFactory entryFactory = (vehicle, currentTime) -> { //make sure the right arguments are passed 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/optimizer/insertion/InsertionCostCalculatorTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionCostCalculatorTest.java index 22af2a9cf15..f9c25dd60cf 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionCostCalculatorTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionCostCalculatorTest.java @@ -42,7 +42,7 @@ public class InsertionCostCalculatorTest { @Test public void testCalculate() { - VehicleEntry entry = entry(new double[] { 20, 50 }); + VehicleEntry entry = entry(new double[] { 20, 20, 50 }); var insertion = insertion(entry, 0, 1); //feasible solution @@ -71,7 +71,7 @@ private void assertCalculate(Insertion insertion, DetourTimeInfo detourTimeInfo, } private VehicleEntry entry(double[] slackTimes) { - return new VehicleEntry(null, null, null, slackTimes); + return new VehicleEntry(null, null, null, slackTimes, 0); } private Link link(String id) { diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculatorTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculatorTest.java index 010e531b996..16e708701fd 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculatorTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculatorTest.java @@ -234,7 +234,7 @@ private Waypoint.Stop stop(double beginTime, Link link) { } private VehicleEntry entry(Waypoint.Start start, Waypoint.Stop... stops) { - return new VehicleEntry(null, start, ImmutableList.copyOf(stops), null); + return new VehicleEntry(null, start, ImmutableList.copyOf(stops), null, 0); } private InsertionDetourData detourData(double toPickupTT, double fromPickupTT, double toDropoffTT, diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculatorWithVariableDurationTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculatorWithVariableDurationTest.java index 37f95db5c83..8f9b037a7dc 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculatorWithVariableDurationTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionDetourTimeCalculatorWithVariableDurationTest.java @@ -274,7 +274,7 @@ private Waypoint.Stop stop(double beginTime, Link link) { } private VehicleEntry entry(Waypoint.Start start, Waypoint.Stop... stops) { - return new VehicleEntry(null, start, ImmutableList.copyOf(stops), null); + return new VehicleEntry(null, start, ImmutableList.copyOf(stops), null, 0); } private InsertionWithDetourData insertion(VehicleEntry entry, int pickupIdx, int dropoffIdx, diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGeneratorTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGeneratorTest.java index 22da5b22295..4509e5f90ad 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGeneratorTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGeneratorTest.java @@ -207,10 +207,10 @@ public void startEmpty_twoStops_notFullBetweenStops_tightSlackTimes() { Waypoint.Stop stop0 = stop(start.time + TIME_REPLACED_DRIVE, link("stop0"), 1);//pick up 1 pax Waypoint.Stop stop1 = stop(stop0.getDepartureTime() + TIME_REPLACED_DRIVE, link("stop1"), 0);//drop off 1 pax - double[] slackTimes = { 0, // impossible insertions: 00, 01, 02 (pickup at 0 is not possible) + double[] slackTimes = { 0, 0, // impossible insertions: 00, 01, 02 (pickup at 0 is not possible) 500, // additional impossible insertions: 11 (too long total detour); however 12 is possible 1000 }; // 22 is possible - VehicleEntry entry = new VehicleEntry(vehicle, start, ImmutableList.of(stop0, stop1), slackTimes); + VehicleEntry entry = new VehicleEntry(vehicle, start, ImmutableList.of(stop0, stop1), slackTimes, 0); var insertions = new ArrayList(); {//12 @@ -399,8 +399,8 @@ private Waypoint.Stop stop(double beginTime, Link link, int outgoingOccupancy) { } private VehicleEntry entry(Waypoint.Start start, Waypoint.Stop... stops) { - var slackTimes = new double[stops.length + 1]; + var slackTimes = new double[stops.length + 2]; Arrays.fill(slackTimes, Double.POSITIVE_INFINITY); - return new VehicleEntry(vehicle, start, ImmutableList.copyOf(stops), slackTimes); + return new VehicleEntry(vehicle, start, ImmutableList.copyOf(stops), slackTimes, 0); } } diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/extensive/DetourPathDataCacheTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/extensive/DetourPathDataCacheTest.java index 37ac3a13a1d..283f69b0cf3 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/extensive/DetourPathDataCacheTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/extensive/DetourPathDataCacheTest.java @@ -132,7 +132,7 @@ private Link link(String id) { private VehicleEntry entry(Link startLink, Link... stopLinks) { return new VehicleEntry(null, new Waypoint.Start(null, startLink, 0, 0), - Arrays.stream(stopLinks).map(this::stop).collect(ImmutableList.toImmutableList()), null); + Arrays.stream(stopLinks).map(this::stop).collect(ImmutableList.toImmutableList()), null, 0); } private Waypoint.Stop stop(Link link) { diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/extensive/KNearestInsertionsAtEndFilterTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/extensive/KNearestInsertionsAtEndFilterTest.java index 8711a88a795..e971c5a312e 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/extensive/KNearestInsertionsAtEndFilterTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/extensive/KNearestInsertionsAtEndFilterTest.java @@ -124,7 +124,7 @@ private Waypoint.Stop stop(double endTime) { private VehicleEntry vehicleEntry(String id, Waypoint.Start start, Waypoint.Stop... stops) { var vehicle = mock(DvrpVehicle.class); when(vehicle.getId()).thenReturn(Id.create(id, DvrpVehicle.class)); - return new VehicleEntry(vehicle, start, ImmutableList.copyOf(stops), null); + return new VehicleEntry(vehicle, start, ImmutableList.copyOf(stops), null, 0); } private List filterOneInsertionAtEnd(InsertionWithDetourData... insertions) { 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 0c18bbb7fe4..fe7d10d9b7b 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 @@ -38,6 +38,7 @@ import org.matsim.contrib.drt.optimizer.insertion.selective.SelectiveInsertionSearchParams; import org.matsim.contrib.drt.run.DrtControlerCreator; import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; +import org.matsim.contrib.drt.stops.CorrectedStopTimeCalculator; import org.matsim.contrib.drt.stops.CumulativeStopTimeCalculator; import org.matsim.contrib.drt.stops.MinimumStopDurationAdapter; import org.matsim.contrib.drt.stops.StaticPassengerStopDurationProvider; @@ -77,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() @@ -111,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() @@ -145,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() @@ -175,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() @@ -198,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,6 +214,41 @@ public void testRunDrtStopbasedExample() { verifyDrtCustomerStatsCloseToExpectedStats(utils.getOutputDirectory(), expectedStats); } + @Test + 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.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") { + @Override + public void install() { + StopTimeCalculator stopTimeCalculator = new CorrectedStopTimeCalculator(60.0); + bindModal(StopTimeCalculator.class).toInstance(stopTimeCalculator); + } + }); + + controller.run(); + + var expectedStats = Stats.newBuilder() + .rejectionRate(0.05) + .rejections(17) + .waitAverage(261.88) + .inVehicleTravelTimeMean(376.04) + .totalTravelTimeMean(637.93) + .build(); + + verifyDrtCustomerStatsCloseToExpectedStats(utils.getOutputDirectory(), expectedStats); + } + @Test public void testRunServiceAreabasedExampleWithSpeedUp() { Id.resetCaches(); @@ -221,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() @@ -243,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); @@ -263,9 +299,9 @@ public void install() { var expectedStats = Stats.newBuilder() .rejectionRate(0.04) .rejections(16) - .waitAverage(278.11) + .waitAverage(278.92) .inVehicleTravelTimeMean(384.6) - .totalTravelTimeMean(662.71) + .totalTravelTimeMean(663.52) .build(); verifyDrtCustomerStatsCloseToExpectedStats(utils.getOutputDirectory(), expectedStats); 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 d2c002a68a9..37ec10d3eda 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 b34b5af05ad..43510e98db7 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/main/java/org/matsim/contrib/zone/skims/TravelTimeMatrices.java b/contribs/dvrp/src/main/java/org/matsim/contrib/zone/skims/TravelTimeMatrices.java index 38e5709b173..792140c173d 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/zone/skims/TravelTimeMatrices.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/zone/skims/TravelTimeMatrices.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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.zone.skims; import java.util.ArrayList; 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/pom.xml b/contribs/ev/pom.xml index f2c94d726b6..ba04bbce066 100644 --- a/contribs/ev/pom.xml +++ b/contribs/ev/pom.xml @@ -30,5 +30,11 @@ commons-csv 1.10.0 + + one.util + streamex + 0.8.2 + compile + 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..81f6682c3ff 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 @@ -43,7 +43,7 @@ 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.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<>(); 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..406f0e647dc 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(){ 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..15ed10c0627 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); // === diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/routing/EvNetworkRoutingProvider.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/routing/EvNetworkRoutingProvider.java index d183fd702fd..bb424097ef5 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/routing/EvNetworkRoutingProvider.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/routing/EvNetworkRoutingProvider.java @@ -14,8 +14,8 @@ import org.matsim.contrib.ev.fleet.ElectricFleetSpecification; import org.matsim.contrib.ev.infrastructure.ChargingInfrastructureSpecification; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; import org.matsim.core.router.DefaultRoutingModules; @@ -46,7 +46,7 @@ public class EvNetworkRoutingProvider implements Provider { private Config config; @Inject - private PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; + private RoutingConfigGroup routingConfigGroup; @Inject private Network network; @@ -129,7 +129,7 @@ public RoutingModule get() { travelDisutilityFactory.createTravelDisutility(travelTime), travelTime); // the following again refers to the (transport)mode, since it will determine the mode of the leg on the network: - if (!plansCalcRouteConfigGroup.getAccessEgressType().equals(AccessEgressType.none)) { + if (!routingConfigGroup.getAccessEgressType().equals(AccessEgressType.none)) { throw new IllegalArgumentException("Bushwacking is not currently supported by the EV routing module"); } else { return new EvNetworkRoutingModule(mode, filteredNetwork, diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerOccupancyTimeProfileCollectorProvider.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerOccupancyTimeProfileCollectorProvider.java index ecf41a5fe45..5c13fac0868 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerOccupancyTimeProfileCollectorProvider.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerOccupancyTimeProfileCollectorProvider.java @@ -67,7 +67,7 @@ public MobsimListener get() { }; var collector = new TimeProfileCollector(header, calc, 300, "charger_occupancy_time_profiles", matsimServices); - if (matsimServices.getConfig().controler().isCreateGraphs()) { + if (matsimServices.getConfig().controller().isCreateGraphs()) { collector.setChartTypes(ChartType.Line, ChartType.StackedArea); } else { collector.setChartTypes(); diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerPowerTimeProfileCalculator.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerPowerTimeProfileCalculator.java new file mode 100644 index 00000000000..78e7f6987ef --- /dev/null +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerPowerTimeProfileCalculator.java @@ -0,0 +1,82 @@ +package org.matsim.contrib.ev.stats; + +import java.util.HashMap; +import java.util.Map; + +import org.matsim.api.core.v01.Id; +import org.matsim.contrib.common.timeprofile.TimeDiscretizer; +import org.matsim.contrib.ev.EvConfigGroup; +import org.matsim.contrib.ev.EvUnits; +import org.matsim.contrib.ev.charging.ChargingEndEvent; +import org.matsim.contrib.ev.charging.ChargingEndEventHandler; +import org.matsim.contrib.ev.charging.ChargingStartEvent; +import org.matsim.contrib.ev.charging.ChargingStartEventHandler; +import org.matsim.contrib.ev.infrastructure.Charger; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.config.groups.QSimConfigGroup; +import org.matsim.vehicles.Vehicle; + +import com.google.inject.Inject; + +public class ChargerPowerTimeProfileCalculator implements ChargingStartEventHandler, ChargingEndEventHandler { + + private final Map, double[]> chargerProfiles = new HashMap<>(); + private final Map, Double> chargingStartTimeMap = new HashMap<>(); + private final Map, Double> chargingStartEnergyMap = new HashMap<>(); + + private final TimeDiscretizer timeDiscretizer; + private final double qsimEndTime; + + /** + * Calculation of average power output for each charging station for each charging event. Charging stations without any charging events will not + * be present in the output file. Implementation does only work when the Qsim end time is defined in the config, i.e., will not work for + * extensions drt and taxi or others depending on the ev contrib without a defined Qsim end time. + * @author mattiasingelstrom + */ + @Inject + public ChargerPowerTimeProfileCalculator(Config config) { + int chargeTimeStep = ConfigUtils.addOrGetModule(config, EvConfigGroup.class).chargeTimeStep; + qsimEndTime = ConfigUtils.addOrGetModule(config, QSimConfigGroup.class).getEndTime().orElse(0.0); + timeDiscretizer = new TimeDiscretizer((int)Math.ceil(qsimEndTime), chargeTimeStep); + } + + + public Map, double[]> getChargerProfiles() { + return chargerProfiles; + } + + @Override + public void handleEvent(ChargingStartEvent event) { + chargingStartTimeMap.put(event.getVehicleId(), event.getTime()); + chargingStartEnergyMap.put(event.getVehicleId(), EvUnits.J_to_kWh(event.getCharge())); + } + + @Override + + public void handleEvent(ChargingEndEvent event) { + double chargingTimeIn_h = (event.getTime() - chargingStartTimeMap.get(event.getVehicleId())) / 3600.0; + double averagePowerIn_kW = (EvUnits.J_to_kWh(event.getCharge()) - chargingStartEnergyMap.get(event.getVehicleId())) / chargingTimeIn_h; + increment(averagePowerIn_kW, event.getChargerId(), chargingStartTimeMap.get(event.getVehicleId()), event.getTime()); + } + private void increment(double averagePower, Id chargerId, double chargingStartTime, double chargingEndTime) { + + //If Qsim end time is undefined in config, qsimEndTime will be 0.0 and will therefore not proceed in calculating the power curves. + if (chargingStartTime == chargingEndTime || chargingStartTime >= qsimEndTime || qsimEndTime == 0.0) { + return; + } + chargingEndTime = Math.min(chargingEndTime, qsimEndTime); + + int fromIdx = timeDiscretizer.getIdx(chargingStartTime); + int toIdx = timeDiscretizer.getIdx(chargingEndTime); + + for (int i = fromIdx; i < toIdx; i++) { + double[] chargingVector = chargerProfiles.computeIfAbsent(chargerId, c -> new double[timeDiscretizer.getIntervalCount()]); + chargingVector[i] += averagePower; + } + } + + public TimeDiscretizer getTimeDiscretizer() { + return timeDiscretizer; + } +} diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerPowerTimeProfileView.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerPowerTimeProfileView.java new file mode 100644 index 00000000000..d0941954540 --- /dev/null +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargerPowerTimeProfileView.java @@ -0,0 +1,39 @@ +package org.matsim.contrib.ev.stats; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.tuple.Pair; +import org.matsim.api.core.v01.Id; +import org.matsim.contrib.common.timeprofile.ProfileWriter; + +import java.awt.*; +import java.util.Map; + +public class ChargerPowerTimeProfileView implements ProfileWriter.ProfileView { + private final ChargerPowerTimeProfileCalculator calculator; + + public ChargerPowerTimeProfileView(ChargerPowerTimeProfileCalculator calculator) { + this.calculator = calculator; + + } + @Override + public double[] times() { + return calculator.getTimeDiscretizer().getTimes(); + } + + @Override + public ImmutableMap profiles() { + return calculator.getChargerProfiles() + .entrySet() + .stream() + .sorted(Map.Entry.comparingByKey(Id::compareTo)) + .map(e -> Pair.of(e.getKey().toString(), e.getValue())) + .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + @Override + public Map seriesPaints() { + return Map.of(); + } + + +} diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/EvStatsModule.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/EvStatsModule.java index 4aa2596c6ca..91f9de2878b 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/EvStatsModule.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/EvStatsModule.java @@ -20,10 +20,14 @@ package org.matsim.contrib.ev.stats; +import com.google.inject.Provider; +import org.matsim.contrib.common.timeprofile.ProfileWriter; import org.matsim.contrib.ev.EvConfigGroup; import org.matsim.contrib.ev.EvModule; import org.matsim.contrib.ev.charging.ChargingEventSequenceCollector; import org.matsim.core.controler.AbstractModule; +import org.matsim.core.controler.MatsimServices; +import org.matsim.core.controler.listener.ControlerListener; import org.matsim.core.mobsim.qsim.AbstractQSimModule; import com.google.inject.Inject; @@ -44,11 +48,11 @@ public void install() { @Override protected void configureQSim() { if (evCfg.timeProfiles) { - addQSimComponentBinding(EvModule.EV_COMPONENT).toProvider( SocHistogramTimeProfileCollectorProvider.class); - addQSimComponentBinding(EvModule.EV_COMPONENT).toProvider( IndividualChargeTimeProfileCollectorProvider.class); - addQSimComponentBinding(EvModule.EV_COMPONENT).toProvider( ChargerOccupancyTimeProfileCollectorProvider.class); + addQSimComponentBinding(EvModule.EV_COMPONENT).toProvider(SocHistogramTimeProfileCollectorProvider.class); + addQSimComponentBinding(EvModule.EV_COMPONENT).toProvider(IndividualChargeTimeProfileCollectorProvider.class); + addQSimComponentBinding(EvModule.EV_COMPONENT).toProvider(ChargerOccupancyTimeProfileCollectorProvider.class); addQSimComponentBinding(EvModule.EV_COMPONENT).to(ChargerOccupancyXYDataCollector.class).asEagerSingleton(); - addQSimComponentBinding(EvModule.EV_COMPONENT).toProvider( VehicleTypeAggregatedChargeTimeProfileCollectorProvider.class); + addQSimComponentBinding(EvModule.EV_COMPONENT).toProvider(VehicleTypeAggregatedChargeTimeProfileCollectorProvider.class); bind(ChargerPowerCollector.class).asEagerSingleton(); addMobsimScopeEventHandlerBinding().to(ChargerPowerCollector.class); @@ -61,5 +65,20 @@ protected void configureQSim() { } } }); + bind(ChargerPowerTimeProfileCalculator.class).asEagerSingleton(); + addEventHandlerBinding().to(ChargerPowerTimeProfileCalculator.class); + addControlerListenerBinding().toProvider(new Provider<>() { + @Inject + private ChargerPowerTimeProfileCalculator calculator; + @Inject + private MatsimServices matsimServices; + + @Override + public ControlerListener get() { + var profileView = new ChargerPowerTimeProfileView(calculator); + return new ProfileWriter(matsimServices,"ev",profileView,"charger_power_time_profiles"); + + } + }); } } diff --git a/contribs/ev/src/test/java/org/matsim/contrib/ev/temperature/TemperatureChangeModuleIntegrationTest.java b/contribs/ev/src/test/java/org/matsim/contrib/ev/temperature/TemperatureChangeModuleIntegrationTest.java index d5779706334..7c39936e0b6 100644 --- a/contribs/ev/src/test/java/org/matsim/contrib/ev/temperature/TemperatureChangeModuleIntegrationTest.java +++ b/contribs/ev/src/test/java/org/matsim/contrib/ev/temperature/TemperatureChangeModuleIntegrationTest.java @@ -49,7 +49,7 @@ public void testTemperatureChangeModule() { Config config = ConfigUtils.loadConfig(utils.getClassInputDirectory() + "/config.xml", new TemperatureChangeConfigGroup()); - config.controler() + config.controller() .setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); config.qsim().setSimStarttimeInterpretation(QSimConfigGroup.StarttimeInterpretation.onlyUseStarttime); Scenario scenario = ScenarioUtils.loadScenario(config); diff --git a/contribs/eventsBasedPTRouter/pom.xml b/contribs/eventsBasedPTRouter/pom.xml deleted file mode 100644 index 6544fa91056..00000000000 --- a/contribs/eventsBasedPTRouter/pom.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - org.matsim - contrib - 16.0-SNAPSHOT - - 4.0.0 - org.matsim.contrib - events-based-pt-router - eventsBasedPTRouter - diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/MultiDestinationDijkstra.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/MultiDestinationDijkstra.java deleted file mode 100644 index 686ce4cebab..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/MultiDestinationDijkstra.java +++ /dev/null @@ -1,547 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * Dijkstra.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007 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.eventsBasedPTRouter; - -import java.util.ArrayList; -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.network.Link; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.router.util.DijkstraNodeData; -import org.matsim.core.router.util.LeastCostPathCalculator.Path; -import org.matsim.core.router.util.PreProcessDijkstra; -import org.matsim.core.router.util.TravelTime; -import org.matsim.core.utils.collections.PseudoRemovePriorityQueue; -import org.matsim.core.utils.misc.Time; -import org.matsim.pt.router.TransitTravelDisutility; - - -/** - * Implementation of
Dijkstra's - * shortest-path algorithm on a time-dependent network with arbitrary - * non-negative cost functions (e.g. negative link cost are not allowed). So - * 'shortest' in our context actually means 'least-cost'. - * - *

- * For every router, there exists a class which computes some preprocessing data - * and is passed to the router class constructor in order to accelerate the - * routing procedure. The one used for Dijkstra is - * {@link org.matsim.core.router.util.PreProcessDijkstra}. - *

- *
- * - *

Code example:

- *

- * PreProcessDijkstra preProcessData = new PreProcessDijkstra();
- * preProcessData.run(network);
- * TravelCost costFunction = ...
- * LeastCostPathCalculator routingAlgo = new Dijkstra(network, costFunction, preProcessData);
- * routingAlgo.calcLeastCostPath(fromNode, toNode, startTime);
- *

- *

- * If you don't want to preprocess the network, you can invoke Dijkstra as - * follows: - *

- *

- * LeastCostPathCalculator routingAlgo = new Dijkstra(network, costFunction); - *

- * - *

Important note

- * This class is NOT threadsafe! - * - * @see org.matsim.core.router.util.PreProcessDijkstra - * @see org.matsim.core.router.AStarEuclidean - * @see org.matsim.core.router.AStarLandmarks - * @author lnicolas - * @author mrieser - */ -public class MultiDestinationDijkstra { - - private final static Logger log = LogManager.getLogger(MultiDestinationDijkstra.class); - - /** - * The network on which we find routes. - */ - protected Network network; - - /** - * The cost calculator. Provides the cost for each link and time step. - */ - final TransitTravelDisutility costFunction; - - /** - * The travel time calculator. Provides the travel time for each link and time step. - */ - final TravelTime timeFunction; - - final Map, DijkstraNodeData> nodeData; - - /** - * Provides an unique id (loop number) for each routing request, so we don't - * have to reset all nodes at the beginning of each re-routing but can use the - * loop number instead. - */ - private int iterationID = Integer.MIN_VALUE + 1; - - /** - * Temporary field that is only used if dead ends are being pruned during - * routing and is updated each time a new route has to be calculated. - */ - private Set deadEndEntryNodes = new HashSet(); - - /** - * Determines whether we should mark nodes in dead ends during a - * pre-processing step so they won't be expanded during routing. - */ - /*package*/ final boolean pruneDeadEnds; - - /** - * Comparator that defines how to order the nodes in the pending nodes queue - * during routing. - */ - - private final PreProcessDijkstra preProcessData; - - - private String[] modeRestriction = null; - - private Person person = null; - - /** - * Default constructor. - * - * @param network - * The network on which to route. - * @param costFunction - * Determines the link cost defining the cheapest route. - * @param timeFunction - * Determines the travel time on links. - */ - public MultiDestinationDijkstra(final Network network, final TransitTravelDisutility costFunction, final TravelTime timeFunction) { - this(network, costFunction, timeFunction, null); - } - - /** - * Constructor. - * - * @param network - * The network on which to route. - * @param costFunction - * Determines the link cost defining the cheapest route. - * @param timeFunction - * Determines the travel time on each link. - * @param preProcessData - * The pre processing data used during the routing phase. - */ - public MultiDestinationDijkstra(final Network network, final TransitTravelDisutility costFunction, final TravelTime timeFunction, - final PreProcessDijkstra preProcessData) { - - this.network = network; - this.costFunction = costFunction; - this.timeFunction = timeFunction; - this.preProcessData = preProcessData; - - this.nodeData = new HashMap, DijkstraNodeData>((int)(network.getNodes().size() * 1.1), 0.95f); - - if (preProcessData != null) { - if (preProcessData.containsData() == false) { - this.pruneDeadEnds = false; - log.warn("The preprocessing data provided to router class Dijkstra contains no data! Please execute its run(...) method first!"); - log.warn("Running without dead-end pruning."); - } else { - this.pruneDeadEnds = true; - } - } else { - this.pruneDeadEnds = false; - } - } - - public void setModeRestriction(final Set modeRestriction) { - if (modeRestriction == null) { - this.modeRestriction = null; - } else { - this.modeRestriction = modeRestriction.toArray(new String[modeRestriction.size()]); - } - } - - /** - * Calculates the cheapest route from Node 'fromNode' to Node 'toNode' at - * starting time 'startTime'. - * - * @param fromNode - * The Node at which the route should start. - * @param toNode - * The Node at which the route should end. - * @param startTime - * The time at which the route should start. Note: Using - * {@link Time#UNDEFINED_TIME} does not imply "time is not relevant", - * rather, {@link Path#travelTime} will return {@link Double#NaN}. - * @see org.matsim.core.router.util.LeastCostPathCalculator#calcLeastCostPath(org.matsim.core.network.Node, - * org.matsim.core.network.Node, double) - */ - public Map, Path> calcLeastCostPath(final Node fromNode, final Set toNodes, final double startTime, final Person person) { - - Map, Double> arrivalTimes = new HashMap, Double>(); - boolean stillSearching = true; - int finishedNodes = 0; - augmentIterationId(); // this call makes the class not threadsafe - this.person = person; - - if (this.pruneDeadEnds == true) { - for(Node toNode:toNodes) - deadEndEntryNodes.add(getPreProcessData(toNode).getDeadEndEntryNode()); - } - - PseudoRemovePriorityQueue pendingNodes = new PseudoRemovePriorityQueue(500); - initFromNode(fromNode, startTime, pendingNodes); - - while (stillSearching) { - Node outNode = pendingNodes.poll(); - - if (outNode == null) { - log.warn("No route was found from node " + fromNode.getId() + " to all nodes: " + finishedNodes + " of " + toNodes.size()); - stillSearching = false; - } - else { - if (toNodes.contains(outNode)) { - DijkstraNodeData outData = getData(outNode); - arrivalTimes.put(outNode.getId(), outData.getTime()); - finishedNodes++; - } - relaxNode(outNode, pendingNodes); - if(finishedNodes==toNodes.size()) - stillSearching = false; - } - } - - // now construct and return the path - return constructPaths(fromNode, toNodes, startTime, arrivalTimes); - - } - - /** - * Constructs the path after the algorithm has been run. - * - * @param fromNode - * The node where the path starts. - * @param toNode - * The node where the path ends. - * @param startTime - * The time when the trip starts. - * @param preProcessData - * The time when the trip ends. - */ - protected Map, Path> constructPaths(Node fromNode, Set toNodes, double startTime, Map, Double> arrivalTimes) { - Map, Path> paths = new HashMap, Path>(); - for(Node toNode:toNodes) { - Double arrivalTime = arrivalTimes.get(toNode.getId()); - Path path = null; - if(arrivalTime != null) { - ArrayList nodes = new ArrayList(); - ArrayList links = new ArrayList(); - - nodes.add(0, toNode); - Link tmpLink = getData(toNode).getPrevLink(); - if (tmpLink != null) { - while (tmpLink.getFromNode() != fromNode) { - links.add(0, tmpLink); - nodes.add(0, tmpLink.getFromNode()); - tmpLink = getData(tmpLink.getFromNode()).getPrevLink(); - } - links.add(0, tmpLink); - nodes.add(0, tmpLink.getFromNode()); - } - - DijkstraNodeData toNodeData = getData(toNode); - path = new Path(nodes, links, arrivalTime - startTime, toNodeData.getCost()); - } - paths.put(toNode.getId(), path); - } - return paths; - } - - /** - * Initializes the first node of a route. - * - * @param fromNode - * The Node to be initialized. - * @param toNode - * The Node at which the route should end. - * @param startTime - * The time we start routing. - * @param pendingNodes - * The pending nodes so far. - */ - /*package*/ void initFromNode(final Node fromNode, final double startTime, - final PseudoRemovePriorityQueue pendingNodes) { - DijkstraNodeData data = getData(fromNode); - visitNode(fromNode, data, pendingNodes, startTime, 0, null); - } - - /** - * Expands the given Node in the routing algorithm; may be overridden in - * sub-classes. - * - * @param outNode - * The Node to be expanded. - * @param toNode - * The target Node of the route. - * @param pendingNodes - * The set of pending nodes so far. - */ - protected void relaxNode(final Node outNode, final PseudoRemovePriorityQueue pendingNodes) { - - DijkstraNodeData outData = getData(outNode); - double currTime = outData.getTime(); - double currCost = outData.getCost(); - if (this.pruneDeadEnds) { - PreProcessDijkstra.DeadEndData ddOutData = getPreProcessData(outNode); - - for (Link l : outNode.getOutLinks().values()) { - relaxNodeLogic(l, pendingNodes, currTime, currCost, ddOutData); - } - } else { // this.pruneDeadEnds == false - for (Link l : outNode.getOutLinks().values()) { - relaxNodeLogic(l, pendingNodes, currTime, currCost, null); - } - } - } - - /** - * Logic that was previously located in the relaxNode(...) method. - * By doing so, the FastDijkstra can overwrite relaxNode without copying the logic. - */ - /*package*/ void relaxNodeLogic(final Link l, final PseudoRemovePriorityQueue pendingNodes, - final double currTime, final double currCost, - final PreProcessDijkstra.DeadEndData ddOutData) { - if (this.pruneDeadEnds) { - if (canPassLink(l)) { - Node n = l.getToNode(); - PreProcessDijkstra.DeadEndData ddData = getPreProcessData(n); - /* IF the current node n is not in a dead end - * OR it is in the same dead end as the fromNode - * OR it is in the same dead end as the toNode - * THEN we add the current node to the pending nodes */ - if(ddData.getDeadEndEntryNode()==null || ddOutData.getDeadEndEntryNode()!=null) - addToPendingNodes(l, n, pendingNodes, currTime, currCost); - else { - TO_NODES: - for(Node deadEndEntryNode:deadEndEntryNodes) - if(deadEndEntryNode != null && deadEndEntryNode.getId() == ddData.getDeadEndEntryNode().getId()) { - addToPendingNodes(l, n, pendingNodes, currTime, currCost); - break TO_NODES; - } - } - } - } else { - if (canPassLink(l)) { - addToPendingNodes(l, l.getToNode(), pendingNodes, currTime, currCost); - } - } - } - - /** - * Adds some parameters to the given Node then adds it to the set of pending - * nodes. - * - * @param l - * The link from which we came to this Node. - * @param n - * The Node to add to the pending nodes. - * @param pendingNodes - * The set of pending nodes. - * @param currTime - * The time at which we started to traverse l. - * @param currCost - * The cost at the time we started to traverse l. - * @param toNode - * The target Node of the route. - * @return true if the node was added to the pending nodes, false otherwise - * (e.g. when the same node already has an earlier visiting time). - */ - protected boolean addToPendingNodes(final Link l, final Node n, - final PseudoRemovePriorityQueue pendingNodes, final double currTime, - final double currCost) { - - double travelTime = this.timeFunction.getLinkTravelTime(l, currTime, person, null); - double travelCost = this.costFunction.getLinkTravelDisutility(l, currTime, this.person, null, null); - DijkstraNodeData data = getData(n); - double nCost = data.getCost(); - if (!data.isVisited(getIterationId())) { - visitNode(n, data, pendingNodes, currTime + travelTime, currCost - + travelCost, l); - return true; - } - double totalCost = currCost + travelCost; - if (totalCost < nCost) { - revisitNode(n, data, pendingNodes, currTime + travelTime, totalCost, l); - return true; - } - - return false; - } - - /** - * @param link - * @return true if the link can be passed with respect to a possible mode restriction set - * - * @see #setModeRestriction(Set) - */ - protected boolean canPassLink(final Link link) { - if (this.modeRestriction == null) { - return true; - } - for (String mode : this.modeRestriction) { - if (link.getAllowedModes().contains(mode)) { - return true; - } - } - return false; - } - - /** - * Changes the position of the given Node n in the pendingNodes queue and - * updates its time and cost information. - * - * @param n - * The Node that is revisited. - * @param data - * The data for n. - * @param pendingNodes - * The nodes visited and not processed yet. - * @param time - * The time of the visit of n. - * @param cost - * The accumulated cost at the time of the visit of n. - * @param outLink - * The link from which we came visiting n. - */ - void revisitNode(final Node n, final DijkstraNodeData data, - final PseudoRemovePriorityQueue pendingNodes, final double time, final double cost, - final Link outLink) { - pendingNodes.remove(n); - - data.visit(outLink, cost, time, getIterationId()); - pendingNodes.add(n, getPriority(data)); - } - - /** - * Inserts the given Node n into the pendingNodes queue and updates its time - * and cost information. - * - * @param n - * The Node that is revisited. - * @param data - * The data for n. - * @param pendingNodes - * The nodes visited and not processed yet. - * @param time - * The time of the visit of n. - * @param cost - * The accumulated cost at the time of the visit of n. - * @param outLink - * The node from which we came visiting n. - */ - protected void visitNode(final Node n, final DijkstraNodeData data, - final PseudoRemovePriorityQueue pendingNodes, final double time, final double cost, - final Link outLink) { - data.visit(outLink, cost, time, getIterationId()); - pendingNodes.add(n, getPriority(data)); - } - - /** - * Augments the iterationID and checks whether the visited information in - * the nodes in the nodes have to be reset. - */ - protected void augmentIterationId() { - if (getIterationId() == Integer.MAX_VALUE) { - this.iterationID = Integer.MIN_VALUE + 1; - resetNetworkVisited(); - } else { - this.iterationID++; - } - } - - /** - * @return iterationID - */ - /*package*/ int getIterationId() { - return this.iterationID; - } - - /** - * Resets all nodes in the network as if they have not been visited yet. - */ - private void resetNetworkVisited() { - for (Node node : this.network.getNodes().values()) { - DijkstraNodeData data = getData(node); - data.resetVisited(); - } - } - - /** - * The value used to sort the pending nodes during routing. - * This implementation compares the total effective travel cost - * to sort the nodes in the pending nodes queue during routing. - */ - protected double getPriority(final DijkstraNodeData data) { - return data.getCost(); - } - - /** - * Returns the data for the given node. Creates a new NodeData if none exists - * yet. - * - * @param n - * The Node for which to return the data. - * @return The data for the given Node - */ - protected DijkstraNodeData getData(final Node n) { - DijkstraNodeData r = this.nodeData.get(n.getId()); - if (null == r) { - r = new DijkstraNodeData(); - this.nodeData.put(n.getId(), r); - } - return r; - } - - protected PreProcessDijkstra.DeadEndData getPreProcessData(final Node n) { - return this.preProcessData.getNodeData(n); - } - - protected final Person getPerson() { - return this.person; - } - - protected final void setPerson(final Person person) { - this.person = person; - } - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/SerializableLinkTravelTimes.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/SerializableLinkTravelTimes.java deleted file mode 100644 index 2ca3400149b..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/SerializableLinkTravelTimes.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter; - -import java.io.Serializable; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.router.util.TravelTime; -import org.matsim.vehicles.Vehicle; - -public class SerializableLinkTravelTimes implements Serializable, TravelTime { - - private final double[][] times; - private final Map indices = new HashMap<>(); - private final int travelTimeBinSize; - - public SerializableLinkTravelTimes(TravelTime linkTravelTimes, - int traveltimeBinSize, double endTime, - Collection links) { - this.travelTimeBinSize = traveltimeBinSize; - endTime = endTime <= 0 ? 86400 : endTime; - times = new double[links.size()][(int) (endTime / traveltimeBinSize)]; - Iterator iterator = links.iterator(); - for (int i = 0; i < times.length; i++) { - Link link = iterator.next(); - indices.put(link.getId().toString(), i); - for (int j = 0; j < times[i].length; j++) - times[i][j] = linkTravelTimes.getLinkTravelTime(link, - traveltimeBinSize * j, null, null); - } - } - - @Override - public double getLinkTravelTime(Link link, double time, Person person, - Vehicle vehicle) { - time = time % 86400; - try { - return times[indices.get(link.getId().toString())][(int) (time / travelTimeBinSize)]; - } catch (ArrayIndexOutOfBoundsException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return time; - } - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterEventsWLFactory.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterEventsWLFactory.java deleted file mode 100644 index f163879e763..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterEventsWLFactory.java +++ /dev/null @@ -1,61 +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.eventsBasedPTRouter; - -import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; -import org.matsim.core.controler.MatsimServices; -import org.matsim.pt.router.PreparedTransitSchedule; -import org.matsim.pt.router.TransitRouter; -import org.matsim.pt.router.TransitRouterConfig; - -import jakarta.inject.Provider; -import jakarta.inject.Singleton; - - -/** - * Factory for the variable transit router - * - * @author sergioo - */ -@Singleton -public class TransitRouterEventsWLFactory implements Provider { - - private final TransitRouterConfig config; - private final TransitRouterNetworkWW routerNetwork; - private final Network network; - private MatsimServices controler; - private final WaitTime waitTime; - - public TransitRouterEventsWLFactory(final MatsimServices controler, final WaitTime waitTime) { - this.config = new TransitRouterConfig(controler.getScenario().getConfig().planCalcScore(), - controler.getScenario().getConfig().plansCalcRoute(), controler.getScenario().getConfig().transitRouter(), - controler.getScenario().getConfig().vspExperimental()); - this.network = controler.getScenario().getNetwork(); - this.controler = controler; - this.waitTime = waitTime; - routerNetwork = TransitRouterNetworkWW.createFromSchedule(network, controler.getScenario().getTransitSchedule(), this.config.getBeelineWalkConnectionDistance()); - } - @Override - public TransitRouter get() { - return new TransitRouterVariableImpl(config, new TransitRouterNetworkTravelTimeAndDisutilityWW(config, network, routerNetwork, controler.getLinkTravelTimes(), waitTime, controler.getConfig().travelTimeCalculator(), controler.getConfig().qsim(), new PreparedTransitSchedule(controler.getScenario().getTransitSchedule())), routerNetwork); - } - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterEventsWSFactory.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterEventsWSFactory.java deleted file mode 100644 index 51a71883525..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterEventsWSFactory.java +++ /dev/null @@ -1,71 +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.eventsBasedPTRouter; - -import com.google.inject.Inject; -import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; -import org.matsim.pt.router.PreparedTransitSchedule; -import org.matsim.pt.router.TransitRouter; -import org.matsim.pt.router.TransitRouterConfig; - -import jakarta.inject.Provider; -import jakarta.inject.Singleton; - -/** - * Factory for the variable transit router - * - * @author sergioo - */ -@Singleton -public class TransitRouterEventsWSFactory implements Provider { - - private final TransitRouterConfig config; - private final TransitRouterNetworkWW routerNetwork; - private final Scenario scenario; - private WaitTime waitTime; - - public void setStopStopTime(StopStopTime stopStopTime) { - this.stopStopTime = stopStopTime; - } - - public void setWaitTime(WaitTime waitTime) { - this.waitTime = waitTime; - } - - private StopStopTime stopStopTime; - - @Inject - public TransitRouterEventsWSFactory(final Scenario scenario, final WaitTime waitTime, final StopStopTime stopStopTime) { - this.config = new TransitRouterConfig(scenario.getConfig().planCalcScore(), - scenario.getConfig().plansCalcRoute(), scenario.getConfig().transitRouter(), - scenario.getConfig().vspExperimental()); - routerNetwork = TransitRouterNetworkWW.createFromSchedule(scenario.getNetwork(), scenario.getTransitSchedule(), this.config.getBeelineWalkConnectionDistance()); - this.scenario = scenario; - this.waitTime = waitTime; - this.stopStopTime = stopStopTime; - } - @Override - public TransitRouter get() { - return new TransitRouterVariableImpl(config, new TransitRouterNetworkTravelTimeAndDisutilityWS(config, routerNetwork, waitTime, stopStopTime, scenario.getConfig().travelTimeCalculator(), scenario.getConfig().qsim(), new PreparedTransitSchedule(scenario.getTransitSchedule())), routerNetwork); - } - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterEventsWSVFactory.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterEventsWSVFactory.java deleted file mode 100644 index d3c398de718..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterEventsWSVFactory.java +++ /dev/null @@ -1,63 +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.eventsBasedPTRouter; - -import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; -import org.matsim.contrib.eventsBasedPTRouter.vehicleOccupancy.VehicleOccupancy; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; -import org.matsim.pt.router.PreparedTransitSchedule; -import org.matsim.pt.router.TransitRouter; -import org.matsim.pt.router.TransitRouterConfig; - -import jakarta.inject.Provider; -import jakarta.inject.Singleton; - -/** - * Factory for the variable transit router - * - * @author sergioo - */ -@Singleton -public class TransitRouterEventsWSVFactory implements Provider { - - private final TransitRouterConfig config; - private final TransitRouterNetworkWW routerNetwork; - private final Scenario scenario; - private final WaitTime waitTime; - private final StopStopTime stopStopTime; - private final VehicleOccupancy vehicleOccupancy; - - public TransitRouterEventsWSVFactory(final Scenario scenario, final WaitTime waitTime, final StopStopTime stopStopTime, final VehicleOccupancy vehicleOccupancy) { - this.config = new TransitRouterConfig(scenario.getConfig().planCalcScore(), - scenario.getConfig().plansCalcRoute(), scenario.getConfig().transitRouter(), - scenario.getConfig().vspExperimental()); - routerNetwork = TransitRouterNetworkWW.createFromSchedule(scenario.getNetwork(), scenario.getTransitSchedule(), this.config.getBeelineWalkConnectionDistance()); - this.scenario = scenario; - this.waitTime = waitTime; - this.stopStopTime = stopStopTime; - this.vehicleOccupancy = vehicleOccupancy; - } - @Override - public TransitRouter get() { - return new TransitRouterVariableImpl(config, new TransitRouterNetworkTravelTimeAndDisutilityWSV(config, routerNetwork, waitTime, stopStopTime, vehicleOccupancy, scenario.getConfig().travelTimeCalculator(), scenario.getConfig().qsim(), new PreparedTransitSchedule(scenario.getTransitSchedule())), routerNetwork); - } - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterNetworkTravelTimeAndDisutilityWS.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterNetworkTravelTimeAndDisutilityWS.java deleted file mode 100644 index 2c2b68c17a7..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterNetworkTravelTimeAndDisutilityWS.java +++ /dev/null @@ -1,144 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TransitRouterNetworkTravelTimeAndDisutilityVariableWW.java - * * - * *********************************************************************** * - * * - * 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.eventsBasedPTRouter; - -import java.util.HashMap; -import java.util.Map; - -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.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; -import org.matsim.core.config.groups.QSimConfigGroup; -import org.matsim.core.config.groups.TravelTimeCalculatorConfigGroup; -import org.matsim.core.router.util.TravelDisutility; -import org.matsim.pt.router.CustomDataManager; -import org.matsim.pt.router.PreparedTransitSchedule; -import org.matsim.pt.router.TransitRouterConfig; -import org.matsim.pt.router.TransitRouterNetworkTravelTimeAndDisutility; -import org.matsim.vehicles.Vehicle; - -import com.google.inject.Provider; - -/** - * TravelTime and TravelDisutility calculator to be used with the transit network used for transit routing. - * This version considers waiting time at stops, and takes travel time between stops from a {@link StopStopTime} object. - * - * @author sergioo - */ -public class TransitRouterNetworkTravelTimeAndDisutilityWS extends TransitRouterNetworkTravelTimeAndDisutility implements TravelDisutility { - - private Link previousLink; - private double previousTime; - private double cachedLinkTime; - private final Map, double[]> linkTravelTimes = new HashMap, double[]>(); - private final Map, double[]> linkWaitingTimes = new HashMap, double[]>(); - private final int numSlots; - private final double timeSlot; - - public TransitRouterNetworkTravelTimeAndDisutilityWS(final TransitRouterConfig config, TransitRouterNetworkWW routerNetwork, Provider waitTime, Provider stopStopTime, TravelTimeCalculatorConfigGroup tTConfigGroup, QSimConfigGroup qSimConfigGroup, PreparedTransitSchedule preparedTransitSchedule) { - this(config, routerNetwork, waitTime.get(), stopStopTime.get(), tTConfigGroup, qSimConfigGroup.getStartTime().seconds(), qSimConfigGroup.getEndTime().seconds(), preparedTransitSchedule); - } - - public TransitRouterNetworkTravelTimeAndDisutilityWS(final TransitRouterConfig config, TransitRouterNetworkWW routerNetwork, WaitTime waitTime, StopStopTime stopStopTime, TravelTimeCalculatorConfigGroup tTConfigGroup, QSimConfigGroup qSimConfigGroup, PreparedTransitSchedule preparedTransitSchedule) { - this(config, routerNetwork, waitTime, stopStopTime, tTConfigGroup, qSimConfigGroup.getStartTime().seconds(), qSimConfigGroup.getEndTime().seconds(), preparedTransitSchedule); - } - public TransitRouterNetworkTravelTimeAndDisutilityWS(final TransitRouterConfig config, TransitRouterNetworkWW routerNetwork, WaitTime waitTime, StopStopTime stopStopTime, TravelTimeCalculatorConfigGroup tTConfigGroup, double startTime, double endTime, PreparedTransitSchedule preparedTransitSchedule) { - super(config, preparedTransitSchedule); - timeSlot = tTConfigGroup.getTraveltimeBinSize(); - numSlots = (int) ((endTime-startTime)/timeSlot); - for(TransitRouterNetworkWW.TransitRouterNetworkLink link:routerNetwork.getLinks().values()) - if(link.route!=null) { - double[] times = new double[numSlots]; - for(int slot = 0; slot, double[]> linkTravelTimes = new HashMap, double[]>(); - private final Map, double[]> linkWaitingTimes = new HashMap, double[]>(); - private final Map, double[]> linkVehicleOccupancy = new HashMap, double[]>(); - private final int numSlots; - private final double timeSlot; - - public TransitRouterNetworkTravelTimeAndDisutilityWSV(final TransitRouterConfig config, TransitRouterNetworkWW routerNetwork, WaitTime waitTime, StopStopTime stopStopTime, VehicleOccupancy vehicleOccupancy, TravelTimeCalculatorConfigGroup tTConfigGroup, QSimConfigGroup qSimConfigGroup, PreparedTransitSchedule preparedTransitSchedule) { - this(config, routerNetwork, waitTime, stopStopTime, vehicleOccupancy, tTConfigGroup, qSimConfigGroup.getStartTime().seconds(), qSimConfigGroup.getEndTime().seconds(), preparedTransitSchedule); - } - public TransitRouterNetworkTravelTimeAndDisutilityWSV(final TransitRouterConfig config, TransitRouterNetworkWW routerNetwork, WaitTime waitTime, StopStopTime stopStopTime, VehicleOccupancy vehicleOccupancy, TravelTimeCalculatorConfigGroup tTConfigGroup, double startTime, double endTime, PreparedTransitSchedule preparedTransitSchedule) { - super(config, preparedTransitSchedule); - timeSlot = tTConfigGroup.getTraveltimeBinSize(); - numSlots = (int) ((endTime-startTime)/timeSlot); - for(TransitRouterNetworkWW.TransitRouterNetworkLink link:routerNetwork.getLinks().values()) - if(link.route!=null) { - double[] times = new double[numSlots]; - double[] occs = new double[numSlots]; - for(int slot = 0; slotSIT_PERCENTAGE?NO_SIT_FACTOR:1 - - link.getLength() * this.config.getMarginalUtilityOfTravelDistancePt_utl_m(); - else if (wrapped.toNode.route!=null) - // it's a wait link - return -(cachedTravelDisutility?cachedTravelTime:linkWaitingTimes.get(wrapped.getId())[time/timeSlotSIT_PERCENTAGE?NO_SIT_FACTOR:1 - - link.getLength() * this.config.getMarginalUtilityOfTravelDistancePt_utl_m(); - else if (wrapped.toNode.route!=null) - // it's a wait link - return - linkWaitingTimes.get(wrapped.getId())[time/timeSlot, double[]> linkTravelTimes = new HashMap, double[]>(); - private final Map, double[]> linkWaitingTimes = new HashMap, double[]>(); - private final double timeSlot; - private final int numSlots; - private Link previousLink; - private double previousTime; - private double cachedTravelTime; - - public TransitRouterNetworkTravelTimeAndDisutilityWW(final TransitRouterConfig config, Network network, TransitRouterNetworkWW routerNetwork, TravelTime travelTime, WaitTime waitTime, TravelTimeCalculatorConfigGroup tTConfigGroup, QSimConfigGroup qSimConfigGroup, PreparedTransitSchedule preparedTransitSchedule) { - this(config, network, routerNetwork, travelTime, waitTime, tTConfigGroup, qSimConfigGroup.getStartTime().seconds(), qSimConfigGroup.getEndTime().seconds(), preparedTransitSchedule); - } - public TransitRouterNetworkTravelTimeAndDisutilityWW(final TransitRouterConfig config, Network network, TransitRouterNetworkWW routerNetwork, TravelTime travelTime, WaitTime waitTime, TravelTimeCalculatorConfigGroup tTConfigGroup, double startTime, double endTime, PreparedTransitSchedule preparedTransitSchedule) { - super(config, preparedTransitSchedule); - timeSlot = tTConfigGroup.getTraveltimeBinSize(); - numSlots = (int) ((endTime-startTime)/timeSlot); - for(TransitRouterNetworkWW.TransitRouterNetworkLink link:routerNetwork.getLinks().values()) - if(link.route!=null) { - double[] times = new double[numSlots]; - for(int slot = 0; slot linkId:link.route.getRoute().getSubRoute(link.fromNode.stop.getStopFacility().getLinkId(), link.toNode.stop.getStopFacility().getLinkId()).getLinkIds()) - linksTime += travelTime.getLinkTravelTime(network.getLinks().get(linkId), startTime+slot*timeSlot, null, null); - times[slot] = linksTime; - } - linkTravelTimes.put(link.getId(), times); - } - else if(link.toNode.route!=null) { - double[] times = new double[numSlots]; - for(int slot = 0; slot, TransitRouterNetworkLink> links = new LinkedHashMap<>(); - private final Map, TransitRouterNetworkNode> nodes = new LinkedHashMap<>(); - protected QuadTree qtNodes = null; - - private long nextNodeId = 0; - protected long nextLinkId = 0; - - public static final class TransitRouterNetworkNode implements Node { - - public final TransitRouteStop stop; - public final TransitRoute route; - public final TransitLine line; - final Id id; - final Map, TransitRouterNetworkLink> ingoingLinks = new LinkedHashMap<>(); - final Map, TransitRouterNetworkLink> outgoingLinks = new LinkedHashMap<>(); - - public TransitRouterNetworkNode(final Id id, final TransitRouteStop stop, final TransitRoute route, final TransitLine line) { - this.id = id; - this.stop = stop; - this.route = route; - this.line = line; - } - - @Override - public Map, ? extends Link> getInLinks() { - return this.ingoingLinks; - } - - @Override - public Map, ? extends Link> getOutLinks() { - return this.outgoingLinks; - } - - @Override - public boolean addInLink(final Link link) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addOutLink(final Link link) { - throw new UnsupportedOperationException(); - } - - @Override - public Coord getCoord() { - return this.stop.getStopFacility().getCoord(); - } - - @Override - public Id getId() { - return this.id; - } - - public TransitRouteStop getStop() { - return stop; - } - - public TransitRoute getRoute() { - return route; - } - - public TransitLine getLine() { - return line; - } - - @Override - public Link removeInLink(Id linkId) { - throw new RuntimeException("not implemented") ; - } - - @Override - public Link removeOutLink(Id outLinkId) { - throw new RuntimeException("not implemented") ; - } - - @Override - public void setCoord(Coord coord) { - throw new RuntimeException("not implemented") ; - } - - @Override - public Attributes getAttributes() { - throw new UnsupportedOperationException(); - } - } - - /** - * Looks to me like an implementation of the Link interface, with get(Transit)Route and get(Transit)Line on top. - * To recall: TransitLine is something like M44. But it can have more than one route, e.g. going north, going south, - * long route, short route. That is, presumably we have one such TransitRouterNetworkLink per TransitRoute. kai/manuel, feb'12 - */ - public static final class TransitRouterNetworkLink implements Link { - - final TransitRouterNetworkNode fromNode; - final TransitRouterNetworkNode toNode; - final TransitRoute route; - final TransitLine line; - final Id id; - private double length; - - public TransitRouterNetworkLink(final Id id, final TransitRouterNetworkNode fromNode, final TransitRouterNetworkNode toNode, final TransitRoute route, final TransitLine line, Network network) { - this.id = id; - this.fromNode = fromNode; - this.toNode = toNode; - this.route = route; - this.line = line; - if(route==null) - this.length = CoordUtils.calcEuclideanDistance(this.toNode.stop.getStopFacility().getCoord(), this.fromNode.stop.getStopFacility().getCoord()); - else { - this.length = 0; - for(Id linkId:route.getRoute().getSubRoute(fromNode.stop.getStopFacility().getLinkId(), toNode.stop.getStopFacility().getLinkId()).getLinkIds()) - this.length += network.getLinks().get(linkId).getLength(); - this.length += network.getLinks().get(toNode.stop.getStopFacility().getLinkId()).getLength(); - } - } - - @Override - public TransitRouterNetworkNode getFromNode() { - return this.fromNode; - } - - @Override - public TransitRouterNetworkNode getToNode() { - return this.toNode; - } - - @Override - public double getCapacity() { - return 9999; - } - - @Override - public double getCapacity(final double time) { - return getCapacity(); - } - - @Override - public double getFreespeed() { - return 10; - } - - @Override - public double getFreespeed(final double time) { - return getFreespeed(); - } - - @Override - public Id getId() { - return this.id; - } - - @Override - public double getNumberOfLanes() { - return 1; - } - - @Override - public double getNumberOfLanes(final double time) { - return getNumberOfLanes(); - } - - @Override - public double getLength() { - return this.length; - } - - @Override - public void setCapacity(final double capacity) { - throw new UnsupportedOperationException(); - } - - @Override - public void setFreespeed(final double freespeed) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean setFromNode(final Node node) { - throw new UnsupportedOperationException(); - } - - @Override - public void setNumberOfLanes(final double lanes) { - throw new UnsupportedOperationException(); - } - - @Override - public void setLength(final double length) { - this.length = length; - } - - @Override - public boolean setToNode(final Node node) { - throw new UnsupportedOperationException(); - } - - @Override - public Coord getCoord() { - throw new UnsupportedOperationException(); - } - - @Override - public Set getAllowedModes() { - return null; - } - - @Override - public void setAllowedModes(final Set modes) { - throw new UnsupportedOperationException(); - } - - public TransitRoute getRoute() { - return route; - } - - public TransitLine getLine() { - return line; - } - - @Override - public double getCapacityPeriod() { - throw new UnsupportedOperationException(); - } - - @Override - public Attributes getAttributes() { - throw new UnsupportedOperationException(); - } - } - public TransitRouterNetworkNode createNode(final TransitRouteStop stop, final TransitRoute route, final TransitLine line) { - Id id = null; - if(line==null && route==null) - id = Id.createNodeId(stop.getStopFacility().getId().toString()); - else - id = Id.createNodeId("number:"+nextNodeId++); - final TransitRouterNetworkNode node = new TransitRouterNetworkNode(id, stop, route, line); - if(this.nodes.get(node.getId())!=null) - throw new RuntimeException(); - this.nodes.put(node.getId(), node); - return node; - } - - public TransitRouterNetworkLink createLink(final Network network, final TransitRouterNetworkNode fromNode, final TransitRouterNetworkNode toNode) { - final TransitRouterNetworkLink link = new TransitRouterNetworkLink(Id.createLinkId(this.nextLinkId++), fromNode, toNode, null, null, network); - this.links.put(link.getId(), link); - fromNode.outgoingLinks.put(link.getId(), link); - toNode.ingoingLinks.put(link.getId(), link); - return link; - } - public TransitRouterNetworkLink createLink(final Network network, final TransitRouterNetworkNode fromNode, final TransitRouterNetworkNode toNode, final TransitRoute route, final TransitLine line) { - final TransitRouterNetworkLink link = new TransitRouterNetworkLink(Id.createLinkId(this.nextLinkId++), fromNode, toNode, route, line, network); - this.getLinks().put(link.getId(), link); - fromNode.outgoingLinks.put(link.getId(), link); - toNode.ingoingLinks.put(link.getId(), link); - return link; - } - @Override - public Map, TransitRouterNetworkNode> getNodes() { - return this.nodes; - } - @Override - public Map, TransitRouterNetworkLink> getLinks() { - return this.links; - } - public void finishInit() { - double minX = Double.POSITIVE_INFINITY; - double minY = Double.POSITIVE_INFINITY; - double maxX = Double.NEGATIVE_INFINITY; - double maxY = Double.NEGATIVE_INFINITY; - for (TransitRouterNetworkNode node : getNodes().values()) - if(node.line == null) { - Coord c = node.stop.getStopFacility().getCoord(); - if (c.getX() < minX) - minX = c.getX(); - if (c.getY() < minY) - minY = c.getY(); - if (c.getX() > maxX) - maxX = c.getX(); - if (c.getY() > maxY) - maxY = c.getY(); - } - QuadTree quadTree = new QuadTree(minX, minY, maxX, maxY); - for (TransitRouterNetworkNode node : getNodes().values()) { - if(node.line == null) { - Coord c = node.stop.getStopFacility().getCoord(); - quadTree.put(c.getX(), c.getY(), node); - } - } - this.qtNodes = quadTree; - } - public static TransitRouterNetworkWW createFromSchedule(final Network network, final TransitSchedule schedule, final double maxBeelineWalkConnectionDistance) { - log.info("start creating transit network"); - final TransitRouterNetworkWW transitNetwork = new TransitRouterNetworkWW(); - final Counter linkCounter = new Counter(" link #"); - final Counter nodeCounter = new Counter(" node #"); - int numTravelLinks = 0, numWaitingLinks = 0, numInsideLinks = 0, numTransferLinks = 0; - Map, TransitRouterNetworkNode> stops = new HashMap, TransitRouterNetworkNode>(); - TransitRouterNetworkNode nodeSR, nodeS; - // build stop nodes - for (TransitLine line : schedule.getTransitLines().values()) - for (TransitRoute route : line.getRoutes().values()) - for (TransitRouteStop stop : route.getStops()) { - nodeS = stops.get(stop.getStopFacility().getId()); - if(nodeS == null) { - nodeS = transitNetwork.createNode(stop, null, null); - nodeCounter.incCounter(); - stops.put(stop.getStopFacility().getId(), nodeS); - } - } - transitNetwork.finishInit(); - // build transfer links - log.info("add transfer links"); - // connect all stops with walking links if they're located less than beelineWalkConnectionDistance from each other - for (TransitRouterNetworkNode node : transitNetwork.getNodes().values()) - for (TransitRouterNetworkNode node2 : transitNetwork.getNearestNodes(node.stop.getStopFacility().getCoord(), maxBeelineWalkConnectionDistance)) - if (node!=node2) { - transitNetwork.createLink(network, node, node2); - linkCounter.incCounter(); - numTransferLinks++; - } - // build nodes and links connecting the nodes according to the transit routes - log.info("add travel, waiting and inside links"); - for (TransitLine line : schedule.getTransitLines().values()) - for (TransitRoute route : line.getRoutes().values()) { - TransitRouterNetworkNode prevNode = null; - for (TransitRouteStop stop : route.getStops()) { - nodeS = stops.get(stop.getStopFacility().getId()); - nodeSR = transitNetwork.createNode(stop, route, line); - nodeCounter.incCounter(); - if (prevNode != null) { - transitNetwork.createLink(network, prevNode, nodeSR, route, line); - linkCounter.incCounter(); - numTravelLinks++; - } - prevNode = nodeSR; - transitNetwork.createLink(network, nodeS, nodeSR); - linkCounter.incCounter(); - numWaitingLinks++; - transitNetwork.createLink(network, nodeSR, nodeS); - linkCounter.incCounter(); - numInsideLinks++; - } - } - log.info("transit router network statistics:"); - log.info(" # nodes: " + transitNetwork.getNodes().size()); - log.info(" # links total: " + transitNetwork.getLinks().size()); - log.info(" # travel links: " + numTravelLinks); - log.info(" # waiting links: " + numWaitingLinks); - log.info(" # inside links: " + numInsideLinks); - log.info(" # transfer links: " + numTransferLinks); - return transitNetwork; - } - public Collection getNearestNodes(final Coord coord, final double distance) { - return this.qtNodes.getDisk(coord.getX(), coord.getY(), distance); - } - - public TransitRouterNetworkNode getNearestNode(final Coord coord) { - return this.qtNodes.getClosest(coord.getX(), coord.getY()); - } - - @Override - public double getCapacityPeriod() { - return 3600.0; - } - - @Override - public NetworkFactory getFactory() { - return null; - } - - @Override - public double getEffectiveLaneWidth() { - return 3; - } - - @Override - public void addNode(Node nn) { - throw new UnsupportedOperationException(); - } - - @Override - public void addLink(Link ll) { - throw new UnsupportedOperationException(); - } - - @Override - public Link removeLink(Id linkId) { - throw new UnsupportedOperationException(); - } - - @Override - public Node removeNode(Id nodeId) { - throw new UnsupportedOperationException(); - } - - @Override - public void setCapacityPeriod(double capPeriod) { - throw new RuntimeException("not implemented") ; - } - - @Override - public void setEffectiveCellSize(double effectiveCellSize) { - throw new RuntimeException("not implemented") ; - } - - @Override - public void setEffectiveLaneWidth(double effectiveLaneWidth) { - throw new RuntimeException("not implemented") ; - } - - @Override - public void setName(String name) { - throw new RuntimeException("not implemented") ; - } - - @Override - public String getName() { - throw new RuntimeException("not implemented") ; - } - - @Override - public double getEffectiveCellSize() { - throw new RuntimeException("not implemented") ; - } - - @Override - public Attributes getAttributes() { - throw new UnsupportedOperationException(); - } -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterVariableImpl.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterVariableImpl.java deleted file mode 100644 index c3abfc1fb38..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/TransitRouterVariableImpl.java +++ /dev/null @@ -1,244 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TranitRouterVariableImpl.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 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.eventsBasedPTRouter; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.TransportMode; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Person; -import org.matsim.api.core.v01.population.Route; -import org.matsim.core.population.PopulationUtils; -import org.matsim.core.population.routes.RouteUtils; -import org.matsim.core.router.InitialNode; -import org.matsim.core.router.RoutingRequest; -import org.matsim.core.router.TripStructureUtils; -import org.matsim.core.router.util.LeastCostPathCalculator.Path; -import org.matsim.core.router.util.PreProcessDijkstra; -import org.matsim.core.utils.geometry.CoordUtils; -import org.matsim.facilities.Facility; -import org.matsim.pt.router.MultiNodeDijkstra; -import org.matsim.pt.router.TransitRouter; -import org.matsim.pt.router.TransitRouterConfig; -import org.matsim.pt.router.TransitRouterNetworkTravelTimeAndDisutility; -import org.matsim.pt.routes.DefaultTransitPassengerRoute; -import org.matsim.pt.routes.TransitPassengerRoute; -import org.matsim.pt.transitSchedule.api.TransitRouteStop; - -public class TransitRouterVariableImpl implements TransitRouter { - - private final TransitRouterNetworkWW transitNetwork; - - private final MultiNodeDijkstra dijkstra; - private final MultiDestinationDijkstra mDijkstra; - private final TransitRouterConfig config; - private final TransitRouterNetworkTravelTimeAndDisutility ttCalculator; - - public TransitRouterVariableImpl(final TransitRouterConfig config, final TransitRouterNetworkTravelTimeAndDisutility ttCalculator, final TransitRouterNetworkWW routerNetwork) { - this.config = config; - this.transitNetwork = routerNetwork; - this.ttCalculator = ttCalculator; - this.dijkstra = new MultiNodeDijkstra(this.transitNetwork, this.ttCalculator, this.ttCalculator); - PreProcessDijkstra preProcessDijkstra = new PreProcessDijkstra(); - preProcessDijkstra.run(routerNetwork); - mDijkstra = new MultiDestinationDijkstra(routerNetwork, this.ttCalculator, this.ttCalculator, preProcessDijkstra); - } - - private Map locateWrappedNearestTransitNodes(Person person, Coord coord, double departureTime){ - Collection nearestNodes = this.transitNetwork.getNearestNodes(coord, this.config.getSearchRadius()); - if (nearestNodes.size() < 2) { - // also enlarge search area if only one stop found, maybe a second one is near the border of the search area - TransitRouterNetworkWW.TransitRouterNetworkNode nearestNode = this.transitNetwork.getNearestNode(coord); - double distance = CoordUtils.calcEuclideanDistance(coord, nearestNode.stop.getStopFacility().getCoord()); - nearestNodes = this.transitNetwork.getNearestNodes(coord, distance + this.config.getExtensionRadius()); - } - Map wrappedNearestNodes = new LinkedHashMap(); - for (TransitRouterNetworkWW.TransitRouterNetworkNode node : nearestNodes) { - Coord toCoord = node.stop.getStopFacility().getCoord(); - double initialTime = getWalkTime(person, coord, toCoord); - double initialCost = getWalkDisutility(person, coord, toCoord); - wrappedNearestNodes.put(node, new InitialNode(initialCost, initialTime + departureTime)); - } - return wrappedNearestNodes; - } - - private double getWalkTime(Person person, Coord coord, Coord toCoord) { - return this.ttCalculator.getWalkTravelTime(person, coord, toCoord); - } - - private double getWalkDisutility(Person person, Coord coord, Coord toCoord) { - return this.ttCalculator.getWalkTravelDisutility(person, coord, toCoord); - } - - public Map, Path> calcPathRoutes(final Id fromNodeId, final Set> toNodeIds, final double startTime, final Person person) { - Set toNodes = new HashSet<>(); - for(Id toNode:toNodeIds) - if(transitNetwork.getNodes().get(toNode)!=null) - toNodes.add(transitNetwork.getNodes().get(toNode)); - Node node = transitNetwork.getNodes().get(fromNodeId); - if(node!=null) - return mDijkstra.calcLeastCostPath(node, toNodes, startTime, person); - else - return new HashMap<>(); - } - @Override - public List calcRoute(RoutingRequest request) { - final Facility fromFacility = request.getFromFacility(); - final Facility toFacility = request.getToFacility(); - final double departureTime = request.getDepartureTime(); - final Person person = request.getPerson(); - - // find possible start stops - Map wrappedFromNodes = this.locateWrappedNearestTransitNodes(person, fromFacility.getCoord(), departureTime); - // find possible end stops - Map wrappedToNodes = this.locateWrappedNearestTransitNodes(person, toFacility.getCoord(), departureTime); - - // find routes between start and end stops - Path p = this.dijkstra.calcLeastCostPath(wrappedFromNodes, wrappedToNodes, person); - if (p == null) { - return null; - } - - double directWalkCost = CoordUtils.calcEuclideanDistance(fromFacility.getCoord(), toFacility.getCoord()) / this.config.getBeelineWalkSpeed() * ( 0 - this.config.getMarginalUtilityOfTravelTimeWalk_utl_s()); - double pathCost = p.travelCost + wrappedFromNodes.get(p.getFromNode()).initialCost + wrappedToNodes.get( - p.getToNode()).initialCost; - if (directWalkCost < pathCost) { - List legs = new ArrayList(); - Leg leg = PopulationUtils.createLeg(TransportMode.walk); // formerly transit_walk - TripStructureUtils.setRoutingMode(leg, TransportMode.pt); - double walkDistance = CoordUtils.calcEuclideanDistance(fromFacility.getCoord(), toFacility.getCoord()); - Route walkRoute = RouteUtils.createGenericRouteImpl(null, null); - walkRoute.setDistance(walkDistance); - leg.setRoute(walkRoute); - leg.setTravelTime(walkDistance/this.config.getBeelineWalkSpeed()); - legs.add(leg); - return legs; - } - - return convertPathToLegList( departureTime, p, fromFacility.getCoord(), toFacility.getCoord(), person ) ; - } - - public Path calcPathRoute(final Coord fromCoord, final Coord toCoord, final double departureTime, final Person person) { - // find possible start stops - // find possible start stops - Map wrappedFromNodes = this.locateWrappedNearestTransitNodes(person, fromCoord, departureTime); - // find possible end stops - Map wrappedToNodes = this.locateWrappedNearestTransitNodes(person, toCoord, departureTime); - // find routes between start and end stops - Path path = this.dijkstra.calcLeastCostPath(wrappedFromNodes, wrappedToNodes, person); - if (path == null) { - return null; - } - double directWalkTime = CoordUtils.calcEuclideanDistance(fromCoord, toCoord) / this.config.getBeelineWalkSpeed(); - double directWalkCost = directWalkTime * ( 0 - this.config.getMarginalUtilityOfTravelTimeWalk_utl_s()); - double pathCost = path.travelCost + wrappedFromNodes.get(path.getFromNode()).initialCost + wrappedToNodes.get( - path.getToNode()).initialCost; - if (directWalkCost < pathCost) { - return new Path(new ArrayList(), new ArrayList(), directWalkTime, directWalkCost); - } - double pathTime = path.travelTime + wrappedFromNodes.get(path.getFromNode()).initialTime + wrappedToNodes.get( - path.getToNode()).initialTime - 2 * departureTime; - return new Path(path.nodes, path.links, pathTime, pathCost); - } - - protected List convertPathToLegList( double departureTime, Path p, Coord fromCoord, Coord toCoord, Person person) { - List legs = new ArrayList(); - Leg leg; - double walkDistance, walkWaitTime, travelTime = 0; - Route walkRoute; - Coord coord = fromCoord; - TransitRouteStop stop = null; - double time = departureTime; - for (Link link : p.links) { - TransitRouterNetworkWW.TransitRouterNetworkLink l = (TransitRouterNetworkWW.TransitRouterNetworkLink) link; - if(l.route!=null) { - //in line link - double ttime = ttCalculator.getLinkTravelTime(l, time, person, null); - travelTime += ttime; - time += ttime; - } - else if(l.fromNode.route!=null) { - //inside link - leg = PopulationUtils.createLeg(TransportMode.pt); - TransitPassengerRoute ptRoute = new DefaultTransitPassengerRoute(stop.getStopFacility(), l.fromNode.line, l.fromNode.route, l.fromNode.stop.getStopFacility()); - leg.setRoute(ptRoute); - leg.setTravelTime(travelTime); - legs.add(leg); - travelTime = 0; - stop = l.fromNode.stop; - coord = l.fromNode.stop.getStopFacility().getCoord(); - } - else if(l.toNode.route!=null) { - //wait link - leg = PopulationUtils.createLeg(TransportMode.walk); - TripStructureUtils.setRoutingMode(leg, TransportMode.pt); - walkDistance = CoordUtils.calcEuclideanDistance(coord, l.toNode.stop.getStopFacility().getCoord()); - walkWaitTime = walkDistance/this.config.getBeelineWalkSpeed()/*+ttCalculator.getLinkTravelTime(l, time+walkDistance/this.config.getBeelineWalkSpeed(), person, null)*/; - walkRoute = RouteUtils.createGenericRouteImpl(stop==null?null:stop.getStopFacility().getLinkId(), l.toNode.stop.getStopFacility().getLinkId()); - walkRoute.setDistance(walkDistance); - leg.setRoute(walkRoute); - leg.setTravelTime(walkWaitTime); - legs.add(leg); - stop = l.toNode.stop; - time += walkWaitTime; - } - - } - leg = PopulationUtils.createLeg(TransportMode.walk); - TripStructureUtils.setRoutingMode(leg, TransportMode.pt); - walkDistance = CoordUtils.calcEuclideanDistance(coord, toCoord); - walkWaitTime = walkDistance/this.config.getBeelineWalkSpeed(); - walkRoute = RouteUtils.createGenericRouteImpl(stop==null?null:stop.getStopFacility().getLinkId(), null); - walkRoute.setDistance(walkDistance); - leg.setRoute(walkRoute); - leg.setTravelTime(walkWaitTime); - legs.add(leg); - return legs; - } - - public TransitRouterNetworkWW getTransitRouterNetwork() { - return this.transitNetwork; - } - - protected TransitRouterNetworkWW getTransitNetwork() { - return transitNetwork; - } - - protected MultiNodeDijkstra getDijkstra() { - return dijkstra; - } - - protected TransitRouterConfig getConfig() { - return config; - } - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/controler/RunControlerWS.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/controler/RunControlerWS.java deleted file mode 100644 index 56ea9525a6b..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/controler/RunControlerWS.java +++ /dev/null @@ -1,66 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * ControlerWW.java - * * - * *********************************************************************** * - * * - * 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.eventsBasedPTRouter.controler; - -import org.matsim.contrib.eventsBasedPTRouter.TransitRouterEventsWSFactory; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculatorImpl; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeStuckCalculator; -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.pt.router.TransitRouter; - - -/** - * A run Controler for a transit router that depends on the travel times and wait times - * - * @author sergioo - */ - -public class RunControlerWS { - - public static void main(String[] args) { - Config config = ConfigUtils.createConfig(); - ConfigUtils.loadConfig(config, args[0]); - final Controler controler = new Controler(ScenarioUtils.loadScenario(config)); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - final WaitTimeStuckCalculator waitTimeCalculator = new WaitTimeStuckCalculator(controler.getScenario().getPopulation(), - controler.getScenario().getTransitSchedule(), controler.getConfig().travelTimeCalculator().getTraveltimeBinSize(), - (int) (controler.getConfig().qsim().getEndTime().seconds()-controler.getConfig().qsim().getStartTime().seconds())); - controler.getEvents().addHandler(waitTimeCalculator); - final StopStopTimeCalculatorImpl stopStopTimeCalculator = new StopStopTimeCalculatorImpl(controler.getScenario().getTransitSchedule(), - controler.getConfig().travelTimeCalculator().getTraveltimeBinSize(), - (int) (controler.getConfig().qsim().getEndTime().seconds()-controler.getConfig().qsim().getStartTime().seconds())); - controler.getEvents().addHandler(stopStopTimeCalculator); - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - bind(TransitRouter.class).toProvider(new TransitRouterEventsWSFactory(controler.getScenario(), waitTimeCalculator.get(), - stopStopTimeCalculator.get())); - } - }); - controler.run(); - } - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/controler/RunControlerWSV.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/controler/RunControlerWSV.java deleted file mode 100644 index a40e1bdf88f..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/controler/RunControlerWSV.java +++ /dev/null @@ -1,77 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * ControlerWW.java - * * - * *********************************************************************** * - * * - * 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.eventsBasedPTRouter.controler; - -import org.matsim.contrib.eventsBasedPTRouter.TransitRouterEventsWSVFactory; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculatorImpl; -import org.matsim.contrib.eventsBasedPTRouter.vehicleOccupancy.VehicleOccupancyCalculator; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeStuckCalculator; -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.scenario.MutableScenario; -import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.pt.router.TransitRouter; - - -/** - * A run Controler for a transit router that depends on the travel times and wait times - * - * @author sergioo - */ - -public class RunControlerWSV { - - public static void main(String[] args) { - Config config = ConfigUtils.createConfig(); - ConfigUtils.loadConfig(config, args[0]); - final Controler controler = new Controler(ScenarioUtils.loadScenario(config)); - final WaitTimeStuckCalculator waitTimeCalculator = new WaitTimeStuckCalculator(controler.getScenario().getPopulation(), - controler.getScenario().getTransitSchedule(), controler.getConfig().travelTimeCalculator().getTraveltimeBinSize(), - (int) (controler.getConfig().qsim().getEndTime().seconds()-controler.getConfig().qsim().getStartTime().seconds())); - controler.getEvents().addHandler(waitTimeCalculator); - final StopStopTimeCalculatorImpl stopStopTimeCalculator = new StopStopTimeCalculatorImpl(controler.getScenario().getTransitSchedule(), - controler.getConfig().travelTimeCalculator().getTraveltimeBinSize(), - (int) (controler.getConfig().qsim().getEndTime().seconds()-controler.getConfig().qsim().getStartTime().seconds())); - controler.getEvents().addHandler(stopStopTimeCalculator); - final VehicleOccupancyCalculator vehicleOccupancyCalculator = new VehicleOccupancyCalculator(controler.getScenario().getTransitSchedule(), - ((MutableScenario)controler.getScenario()).getTransitVehicles(), - controler.getConfig().travelTimeCalculator().getTraveltimeBinSize(), - (int) (controler.getConfig().qsim().getEndTime().seconds()-controler.getConfig().qsim().getStartTime().seconds())); - controler.getEvents().addHandler(vehicleOccupancyCalculator); - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - bind(TransitRouter.class).toProvider(new TransitRouterEventsWSVFactory(controler.getScenario(), waitTimeCalculator.get(), - stopStopTimeCalculator.get(), vehicleOccupancyCalculator.getVehicleOccupancy())); - } - }); - - // yyyyyy note that in the above script only the router is modified, but not the scoring. With standard matsim, a slower bu - // less crowded pt route will only be accepted by the agent when the faster but more crowded option was never presented - // to the agent. (Alternatively, e.g. with the Singapore scenario, there may be boarding denials, in which case - // routes that avoid crowded sections may also be beneficial.) kai, jul'15 - - controler.run(); - } - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTime.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTime.java deleted file mode 100644 index 0b5fa9056f5..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTime.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.stopStopTimes; - -import org.matsim.api.core.v01.Id; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -import java.io.Serializable; - -public interface StopStopTime extends Serializable { - - //Methods - public double getStopStopTime(Id stopOId, Id stopDId, double time); - public double getStopStopTimeVariance(Id stopOId, Id stopDId, double time); - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculator.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculator.java deleted file mode 100644 index a27652742bd..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculator.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.stopStopTimes; - -import com.google.inject.Provider; -import com.google.inject.Provides; -import org.matsim.api.core.v01.Id; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - - - -public interface StopStopTimeCalculator extends Provider { - - //Methods - double getStopStopTime(Id stopOId, Id stopDId, double time); - - double getStopStopTimeVariance(Id stopOId, Id stopDId, double time); - - @Override - @Provides - StopStopTime get(); -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculatorImpl.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculatorImpl.java deleted file mode 100644 index c2ffef28c35..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculatorImpl.java +++ /dev/null @@ -1,153 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.stopStopTimes; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.PersonLeavesVehicleEvent; -import org.matsim.api.core.v01.events.handler.PersonLeavesVehicleEventHandler; -import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; -import org.matsim.core.api.experimental.events.handler.VehicleArrivesAtFacilityEventHandler; -import org.matsim.core.config.Config; -import org.matsim.core.trafficmonitoring.TimeBinUtils; -import org.matsim.core.utils.collections.Tuple; -import org.matsim.pt.transitSchedule.api.Departure; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.vehicles.Vehicle; - -import com.google.inject.Inject; -import com.google.inject.Provides; -import com.google.inject.Singleton; -@Singleton -public class StopStopTimeCalculatorImpl implements VehicleArrivesAtFacilityEventHandler, PersonLeavesVehicleEventHandler, StopStopTimeCalculator { - - private final Map, Map, StopStopTimeData>> stopStopTimes = new HashMap, Map, StopStopTimeData>>(5000); - private final Map, Map, Double>> scheduledStopStopTimes = new HashMap, Map, Double>>(5000); - private final Map, Tuple, Double>> inTransitVehicles = new HashMap, Tuple, Double>>(1000); - private final Set> vehicleIds = new HashSet>(); - private final double timeSlot; - private final int totalTime; - private boolean useVehicleIds = true; - - //Constructors - @Inject - public StopStopTimeCalculatorImpl(final TransitSchedule transitSchedule, final Config config, EventsManager eventsManager) { - this(transitSchedule, config.travelTimeCalculator().getTraveltimeBinSize(), (int) (config.qsim().getEndTime().seconds()-config.qsim().getStartTime().seconds())); - eventsManager.addHandler(this); - } - public StopStopTimeCalculatorImpl(final TransitSchedule transitSchedule, final double timeSlot, final int totalTime) { - this.timeSlot = timeSlot; - this.totalTime = totalTime; - Map, Map, Integer>> numObservations = new HashMap, Map, Integer>>(); - for(TransitLine line:transitSchedule.getTransitLines().values()) - for(TransitRoute route:line.getRoutes().values()) { - for(int s=0; s, StopStopTimeData> map = stopStopTimes.computeIfAbsent( - route.getStops().get(s).getStopFacility().getId(), - k -> new HashMap<>(2)); - map.put(route.getStops().get(s+1).getStopFacility().getId(), new StopStopTimeDataArray(TimeBinUtils.getTimeBinCount(totalTime, timeSlot))); - Map, Double> map2 = scheduledStopStopTimes.get(route.getStops().get(s).getStopFacility().getId()); - Map, Integer> map3 = numObservations.get(route.getStops().get(s).getStopFacility().getId()); - Double stopStopTime; - Integer num; - if(map2==null) { - map2 = new HashMap, Double>(2); - scheduledStopStopTimes.put(route.getStops().get(s).getStopFacility().getId(), map2); - map3 = new HashMap, Integer>(2); - numObservations.put(route.getStops().get(s).getStopFacility().getId(), map3); - stopStopTime = 0.0; - num = 0; - } - else { - stopStopTime = map2.get(route.getStops().get(s+1).getStopFacility().getId()); - num = map3.get(route.getStops().get(s+1).getStopFacility().getId()); - if(stopStopTime==null) { - stopStopTime = 0.0; - num = 0; - } - } - map2.put(route.getStops().get(s+1).getStopFacility().getId(), - stopStopTime+route.getStops().get(s+1).getArrivalOffset().seconds()-route.getStops().get(s).getDepartureOffset().seconds()); - map3.put(route.getStops().get(s+1).getStopFacility().getId(), ++num); - } - for(Departure departure:route.getDepartures().values()) - vehicleIds.add(departure.getVehicleId()); - } - for(Entry, Map, Double>> entry:scheduledStopStopTimes.entrySet()) - for(Entry, Double> entry2:entry.getValue().entrySet()) - entry.getValue().put(entry2.getKey(), entry2.getValue()/numObservations.get(entry.getKey()).get(entry2.getKey())); - } - - //Methods - @Override - public double getStopStopTime(Id stopOId, Id stopDId, double time) { - StopStopTimeData stopStopTimeData = stopStopTimes.get(stopOId).get(stopDId); - int timeBinIndex = TimeBinUtils.getTimeBinIndex(time, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)); - if(stopStopTimeData.getNumData(timeBinIndex)==0) - return scheduledStopStopTimes.get(stopOId).get(stopDId); - else - return stopStopTimeData.getStopStopTime(timeBinIndex); - } - @Override - public double getStopStopTimeVariance(Id stopOId, Id stopDId, double time) { - StopStopTimeData stopStopTimeData = stopStopTimes.get(stopOId).get(stopDId); - int timeBinIndex = TimeBinUtils.getTimeBinIndex(time, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)); - if(stopStopTimeData.getNumData(timeBinIndex)==0) - return 0; - else - return stopStopTimeData.getStopStopTimeVariance(timeBinIndex); - } - @Override - public void reset(int iteration) { - for(Map, StopStopTimeData> map:stopStopTimes.values()) - for(StopStopTimeData stopStopTimeData:map.values()) - stopStopTimeData.resetStopStopTimes(); - inTransitVehicles.clear(); - } - @Override - public void handleEvent(VehicleArrivesAtFacilityEvent event) { - if(!useVehicleIds || vehicleIds.contains(event.getVehicleId())) { - Tuple, Double> route = inTransitVehicles.remove(event.getVehicleId()); - if(route!=null) - stopStopTimes.get(route.getFirst()).get(event.getFacilityId()).addStopStopTime( - TimeBinUtils.getTimeBinIndex(route.getSecond(), timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)), - event.getTime()-route.getSecond()); - inTransitVehicles.put(event.getVehicleId(), new Tuple, Double>(event.getFacilityId(), event.getTime())); - } - } - @Override - public void handleEvent(PersonLeavesVehicleEvent event) { - if((!useVehicleIds || vehicleIds.contains(event.getVehicleId())) && event.getPersonId().toString().startsWith("pt_") - && event.getPersonId().toString().contains(event.getVehicleId().toString())) - inTransitVehicles.remove(event.getVehicleId()); - } - public void setUseVehicleIds(boolean useVehicleIds) { - this.useVehicleIds = useVehicleIds; - } - - @Override - @Provides - public StopStopTime get() { - return new StopStopTime() { - /** - * - */ - private static final long serialVersionUID = 1L; - @Override - public double getStopStopTime(Id stopOId, Id stopDId, double time) { - return StopStopTimeCalculatorImpl.this.getStopStopTime(stopOId, stopDId, time); - } - @Override - public double getStopStopTimeVariance(Id stopOId, Id stopDId, double time) { - return StopStopTimeCalculatorImpl.this.getStopStopTimeVariance(stopOId, stopDId, time); - } - }; - } -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculatorSerializable.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculatorSerializable.java deleted file mode 100644 index d03b9ed5f2b..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculatorSerializable.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.stopStopTimes; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -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.events.PersonLeavesVehicleEvent; -import org.matsim.api.core.v01.events.handler.PersonLeavesVehicleEventHandler; -import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; -import org.matsim.core.api.experimental.events.handler.VehicleArrivesAtFacilityEventHandler; -import org.matsim.core.config.Config; -import org.matsim.core.trafficmonitoring.TimeBinUtils; -import org.matsim.core.utils.collections.Tuple; -import org.matsim.pt.transitSchedule.api.Departure; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -import com.google.inject.Provider; -import com.google.inject.Provides; - -public class StopStopTimeCalculatorSerializable implements StopStopTimeCalculator, VehicleArrivesAtFacilityEventHandler, PersonLeavesVehicleEventHandler, Serializable, Provider { - - /** - * - */ - private static final long serialVersionUID = 1L; - private final Map> stopStopTimes = new HashMap>(5000); - private final Map> scheduledStopStopTimes = new HashMap>(5000); - private final Map> inTransitVehicles = new HashMap>(1000); - private final Set vehicleIds = new HashSet(); - private final double timeSlot; - private final int totalTime; - private boolean useVehicleIds = true; - private static int scheduleCalls = 0; - private static int totalCalls = 0; - private static double stopTimesInflation = 0; - - //Constructors - public StopStopTimeCalculatorSerializable(final TransitSchedule transitSchedule, final Config config) { - this(transitSchedule, config.travelTimeCalculator().getTraveltimeBinSize(), (int) (config.qsim().getEndTime().seconds()-config.qsim().getStartTime().seconds())); - } - public static void printCallStatisticsAndReset(){ - Logger logger = LogManager.getLogger(StopStopTimeCalculatorSerializable.class); - logger.warn("stop times read from schedule vs total (S:T) = " + scheduleCalls + " : " + totalCalls); - logger.warn("inflation of recorded times called vs their scheduled time:" +stopTimesInflation/(double)(totalCalls -scheduleCalls)); - scheduleCalls = 0; - totalCalls = 0; - stopTimesInflation=0; - } - public StopStopTimeCalculatorSerializable(final TransitSchedule transitSchedule, final double timeSlot, final int totalTime) { - this.timeSlot = timeSlot; - this.totalTime = totalTime; - Map> numObservations = new HashMap>(); - for(TransitLine line:transitSchedule.getTransitLines().values()) - for(TransitRoute route:line.getRoutes().values()) { - for(int s=0; s map = stopStopTimes.get(route.getStops().get(s).getStopFacility().getId().toString()); - if(map==null) { - map = new HashMap(2); - stopStopTimes.put(route.getStops().get(s).getStopFacility().getId().toString(), map); - } - map.put(route.getStops().get(s+1).getStopFacility().getId().toString(), - new StopStopTimeDataArray(TimeBinUtils.getTimeBinCount(totalTime, timeSlot))); - Map map2 = scheduledStopStopTimes.get(route.getStops().get(s).getStopFacility().getId().toString()); - Map map3 = numObservations.get(route.getStops().get(s).getStopFacility().getId().toString()); - Double stopStopTime; - Integer num; - if(map2==null) { - map2 = new HashMap(2); - scheduledStopStopTimes.put(route.getStops().get(s).getStopFacility().getId().toString(), map2); - map3 = new HashMap(2); - numObservations.put(route.getStops().get(s).getStopFacility().getId().toString(), map3); - stopStopTime = 0.0; - num = 0; - } - else { - stopStopTime = map2.get(route.getStops().get(s+1).getStopFacility().getId().toString()); - num = map3.get(route.getStops().get(s+1).getStopFacility().getId().toString()); - if(stopStopTime==null) { - stopStopTime = 0.0; - num = 0; - } - } - map2.put(route.getStops().get(s+1).getStopFacility().getId().toString(), - stopStopTime+route.getStops().get(s+1).getArrivalOffset().seconds() - - route.getStops().get(s).getDepartureOffset().seconds()); - map3.put(route.getStops().get(s+1).getStopFacility().getId().toString(), ++num); - } - for(Departure departure:route.getDepartures().values()) - vehicleIds.add(departure.getVehicleId().toString()); - } - for(Entry> entry:scheduledStopStopTimes.entrySet()) - for(Entry entry2:entry.getValue().entrySet()) - entry.getValue().put(entry2.getKey(), entry2.getValue()/numObservations.get(entry.getKey()).get(entry2.getKey())); - } - - //Methods - public StopStopTime getStopStopTimes() { - return new StopStopTime() { - /** - * - */ - private static final long serialVersionUID = 1L; - @Override - public double getStopStopTime(Id stopOId, Id stopDId, double time) { - return StopStopTimeCalculatorSerializable.this.getStopStopTime(stopOId, stopDId, time); - } - @Override - public double getStopStopTimeVariance(Id stopOId, Id stopDId, double time) { - return StopStopTimeCalculatorSerializable.this.getStopStopTimeVariance(stopOId, stopDId, time); - } - }; - } - @Override - public double getStopStopTime(Id stopOId, Id stopDId, double time) { - StopStopTimeData stopStopTimeData = stopStopTimes.get(stopOId.toString()).get(stopDId.toString()); - totalCalls++; - int timeBinIndex = TimeBinUtils.getTimeBinIndex(time, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)); - if(stopStopTimeData.getNumData(timeBinIndex)==0) { - scheduleCalls++; - return scheduledStopStopTimes.get(stopOId.toString()).get(stopDId.toString()); - } - else { - stopTimesInflation += stopStopTimeData.getStopStopTime(timeBinIndex)/scheduledStopStopTimes.get(stopOId.toString()).get(stopDId.toString()); - return stopStopTimeData.getStopStopTime(timeBinIndex); - } - } - @Override - public double getStopStopTimeVariance(Id stopOId, Id stopDId, double time) { - StopStopTimeData stopStopTimeData = stopStopTimes.get(stopOId.toString()).get(stopDId.toString()); - int timeBinIndex = TimeBinUtils.getTimeBinIndex(time, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)); - if(stopStopTimeData.getNumData(timeBinIndex)==0) - return 0; - else - return stopStopTimeData.getStopStopTimeVariance(timeBinIndex); - } - - @Provides - public StopStopTime get() { - return new StopStopTime() { - @Override - public double getStopStopTime(Id stopOId, Id stopDId, double time) { - return StopStopTimeCalculatorSerializable.this.getStopStopTime(stopOId,stopDId,time); - } - - @Override - public double getStopStopTimeVariance(Id stopOId, Id stopDId, double time) { - return StopStopTimeCalculatorSerializable.this.getStopStopTimeVariance(stopOId,stopDId,time); - } - }; - } - - @Override - public void reset(int iteration) { - for(Map map:stopStopTimes.values()) - for(StopStopTimeData stopStopTimeData:map.values()) - stopStopTimeData.resetStopStopTimes(); - inTransitVehicles.clear(); - } - @Override - public void handleEvent(VehicleArrivesAtFacilityEvent event) { - if(!useVehicleIds || vehicleIds.contains(event.getVehicleId().toString())) { - Tuple route = inTransitVehicles.remove(event.getVehicleId().toString()); - if(route!=null) - try { - stopStopTimes.get(route.getFirst()).get(event.getFacilityId().toString()).addStopStopTime( - TimeBinUtils.getTimeBinIndex(route.getSecond(), timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)), - event.getTime()-route.getSecond()); - } catch(Exception e) { - //System.out.println("No: "+route.getFirst()+"-->"+event.getFacilityId()); - } - inTransitVehicles.put(event.getVehicleId().toString(), new Tuple(event.getFacilityId().toString(), event.getTime())); - } - } - @Override - public void handleEvent(PersonLeavesVehicleEvent event) { - if((!useVehicleIds || vehicleIds.contains(event.getVehicleId().toString())) && event.getPersonId().toString().startsWith("pt_") - && event.getPersonId().toString().contains(event.getVehicleId().toString())) - inTransitVehicles.remove(event.getVehicleId().toString()); - } - public void setUseVehicleIds(boolean useVehicleIds) { - this.useVehicleIds = useVehicleIds; - } -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculatorTuple.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculatorTuple.java deleted file mode 100644 index 1d6a522694e..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeCalculatorTuple.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.stopStopTimes; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Scenario; -import org.matsim.api.core.v01.events.PersonLeavesVehicleEvent; -import org.matsim.api.core.v01.events.handler.PersonLeavesVehicleEventHandler; -import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; -import org.matsim.core.api.experimental.events.handler.VehicleArrivesAtFacilityEventHandler; -import org.matsim.core.config.Config; -import org.matsim.core.config.ConfigUtils; -import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.core.trafficmonitoring.TimeBinUtils; -import org.matsim.core.utils.collections.Tuple; -import org.matsim.core.utils.misc.Time; -import org.matsim.pt.transitSchedule.api.Departure; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitScheduleReader; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.vehicles.Vehicle; - -public class StopStopTimeCalculatorTuple implements VehicleArrivesAtFacilityEventHandler, PersonLeavesVehicleEventHandler { - - private final Map, Id>, StopStopTimeData> stopStopTimes = new HashMap, Id>, StopStopTimeData>(); - private final Map, Id>, Double> scheduledStopStopTimes = new HashMap, Id>, Double>(); - private final Map, Tuple, Double>> inTransitVehicles = new HashMap, Tuple, Double>>(1000); - private final Set> vehicleIds = new HashSet>(); - private final double timeSlot; - private final int totalTime; - - //Constructors - public StopStopTimeCalculatorTuple(final TransitSchedule transitSchedule, final Config config) { - this(transitSchedule, config.travelTimeCalculator().getTraveltimeBinSize(), (int) (config.qsim().getEndTime().seconds()-config.qsim().getStartTime().seconds())); - } - public StopStopTimeCalculatorTuple(final TransitSchedule transitSchedule, final double timeSlot, final int totalTime) { - this.timeSlot = timeSlot; - this.totalTime = totalTime; - Map, Id>, Integer> numObservations = new HashMap, Id>, Integer>(); - for(TransitLine line:transitSchedule.getTransitLines().values()) - for(TransitRoute route:line.getRoutes().values()) { - for(int s=0; s, Id> key = new Tuple, Id>(route.getStops().get(s).getStopFacility().getId(), - route.getStops().get(s+1).getStopFacility().getId()); - StopStopTimeData data = stopStopTimes.get(key); - if(data==null) - stopStopTimes.put(key, new StopStopTimeDataArray(TimeBinUtils.getTimeBinCount(totalTime, timeSlot))); - Double sTime = scheduledStopStopTimes.get(key); - Integer num = numObservations.get(key); - if(sTime==null) { - sTime = 0.0; - scheduledStopStopTimes.put(key, sTime); - num = 0; - numObservations.put(key, num); - } - scheduledStopStopTimes.put(key, (num*sTime+route.getStops().get(s+1).getArrivalOffset().seconds() - - route.getStops().get(s).getDepartureOffset().seconds())/++num); - numObservations.put(key, num); - } - for(Departure departure:route.getDepartures().values()) - vehicleIds.add(departure.getVehicleId()); - } - System.out.println(stopStopTimes.size()); - } - public static void main(String[] args) { - Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); - scenario.getConfig().transit().setUseTransit(true); - new TransitScheduleReader(scenario).readFile(args[0]); - new StopStopTimeCalculatorTuple(scenario.getTransitSchedule(), 900, 30*3600); - } - //Methods - public StopStopTime getStopStopTimes() { - return new StopStopTime() { - /** - * - */ - private static final long serialVersionUID = 1L; - @Override - public double getStopStopTime(Id stopOId, Id stopDId, double time) { - return StopStopTimeCalculatorTuple.this.getStopStopTime(stopOId, stopDId, time); - } - @Override - public double getStopStopTimeVariance(Id stopOId, Id stopDId, double time) { - return StopStopTimeCalculatorTuple.this.getStopStopTimeVariance(stopOId, stopDId, time); - } - }; - } - private double getStopStopTime(Id stopOId, Id stopDId, double time) { - Tuple, Id> key = new Tuple, Id>(stopOId, stopDId); - StopStopTimeData stopStopTimeData = stopStopTimes.get(key); - int timeBinIndex = TimeBinUtils.getTimeBinIndex(time, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)); - if(stopStopTimeData.getNumData(timeBinIndex)==0) - return scheduledStopStopTimes.get(key); - else - return stopStopTimeData.getStopStopTime(timeBinIndex); - } - private double getStopStopTimeVariance(Id stopOId, Id stopDId, double time) { - Tuple, Id> key = new Tuple, Id>(stopOId, stopDId); - StopStopTimeData stopStopTimeData = stopStopTimes.get(key); - int timeBinIndex = TimeBinUtils.getTimeBinIndex(time, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)); - if(stopStopTimeData.getNumData(timeBinIndex)==0) - return 0; - else - return stopStopTimeData.getStopStopTimeVariance(timeBinIndex); - } - @Override - public void reset(int iteration) { - for(StopStopTimeData stopStopTimeData:stopStopTimes.values()) - stopStopTimeData.resetStopStopTimes(); - inTransitVehicles.clear(); - } - @Override - public void handleEvent(VehicleArrivesAtFacilityEvent event) { - if(vehicleIds.contains(event.getVehicleId())) { - Tuple, Double> route = inTransitVehicles.remove(event.getVehicleId()); - if(route!=null) - stopStopTimes.get(new Tuple, Id>(route.getFirst(), - event.getFacilityId())).addStopStopTime( - TimeBinUtils.getTimeBinIndex(route.getSecond(), timeSlot, - TimeBinUtils.getTimeBinCount(totalTime, timeSlot)), event.getTime()-route.getSecond()); - inTransitVehicles.put(event.getVehicleId(), new Tuple, Double>(event.getFacilityId(), event.getTime())); - } - } - @Override - public void handleEvent(PersonLeavesVehicleEvent event) { - if(vehicleIds.contains(event.getVehicleId()) && event.getPersonId().toString().startsWith("pt_"+event.getVehicleId()+"_")) - inTransitVehicles.remove(event.getVehicleId()); - } -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeData.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeData.java deleted file mode 100644 index 9f3de496a90..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeData.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.stopStopTimes; - -import java.io.Serializable; - -public interface StopStopTimeData extends Serializable { - - int getNumData(int i); - double getStopStopTime(int i); - void addStopStopTime(final int timeSlot, final double stopStopTime); - void resetStopStopTimes(); - double getStopStopTimeVariance(int timeSlot); - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeDataArray.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeDataArray.java deleted file mode 100644 index b1ac8626324..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/stopStopTimes/StopStopTimeDataArray.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.stopStopTimes; - -public class StopStopTimeDataArray implements StopStopTimeData { - - /** - * - */ - private static final long serialVersionUID = 1L; - //Attributes - private double[] stopStopTimeMeans; - private double[] stopStopTimeSquares; - private int[] numTimes; - - //Constructors - public StopStopTimeDataArray(int numSlots) { - stopStopTimeSquares = new double[numSlots]; - stopStopTimeMeans = new double[numSlots]; - numTimes = new int[numSlots]; - resetStopStopTimes(); - } - - //Methods - @Override - public int getNumData(int timeSlot) { - return numTimes[timeSlotWhen StopStopTimes are generated externally, e.g. by a regression. - *

- * See constructor for input format. - *

- */ -public class StopStopTimePreCalcSerializable implements StopStopTime, Serializable { - - private final Map>>> stopStopTimes = new HashMap<>(5000); - private final Scenario scenario; - - public boolean isLogarithmic() { - return logarithmic; - } - - private final boolean logarithmic; - private int nfeCounter = 0; - private int aiobCounter = 0; - private int errorCounter = 0; - - //Constructors - - - /** - * Populates a StopStopTime object with stop to stop travel times and their variances - * recorded at particular times. - * Needs at minimum one record per stop-to-stop combination. - * Times at which records are recorded needn't be regular intervals, because a TreeMap is used. - * - * @param inputFile path to the tab-separated file.Format is fromStopId (String), toStopId (String), time of record (seconds, double), - * travelTime (seconds, double), travelTimeVariance (seconds**2, double). No headings or row numbers. - * @param logarithmic if times are recorded as logarithms (normally distributed residuals) - */ - public StopStopTimePreCalcSerializable(String inputFile, Scenario scenario, boolean logarithmic) { - this.logarithmic = logarithmic; - this.scenario = scenario; - BufferedReader reader = IOUtils.getBufferedReader(inputFile); - String txt = ""; - while (true) { - try { - txt = reader.readLine(); - if (txt == null) - break; - String[] split = txt.split("\t"); -// get the map from this stop id - Map>> toMap = stopStopTimes.get(split[0]); - if (toMap == null) { - toMap = new HashMap<>(); - stopStopTimes.put(split[0], toMap); - } - - Map> timeData = toMap.get(split[1]); - if (timeData == null) { - timeData = new TreeMap<>(); - toMap.put(split[1], timeData); - } - - timeData.put(Integer.parseInt(split[2]), new Tuple<>(Double.parseDouble(split[3]), Double.parseDouble(split[4]))); - - } catch (IOException e) { - e.printStackTrace(); - } catch (ArrayIndexOutOfBoundsException e) { - if (aiobCounter < 10) { - System.err.println("Seems one of the lines in the StopStopTime input file is missing a value. Skipping it."); - } else { - System.err.println("Seems one of the lines in the StopStopTime input file is missing a value. Skipping further warnings..."); - - } - aiobCounter++; - } catch (NumberFormatException e) { - if (nfeCounter < 10) { - System.err.println("Some values in the StopStopTime input file are of the wrong type. Skipping it."); - } else { - System.err.println("Some values in the StopStopTime input file are of the wrong type. Skipping further warnings..."); - } - nfeCounter++; - } - } - System.out.println("\n\n*************************************************************************\n\n"); - System.out.println("STOPSTOPTIMES LOADED, filling in the blanks from the schedule and network"); - System.out.println("\n\n*************************************************************************\n\n"); - - for (TransitLine transitLine : scenario.getTransitSchedule().getTransitLines().values()) { - for (TransitRoute route : transitLine.getRoutes().values()) { - TRANSITSTOPS: - for (int s = 0; s < route.getStops().size() - 1; s++) { - String origin = route.getStops().get(s).getStopFacility().getId().toString(); - String destination = route.getStops().get(s + 1).getStopFacility().getId().toString(); - Map>> toMap = stopStopTimes.get(origin); - if (toMap == null) { - toMap = new HashMap<>(); - stopStopTimes.put(origin, toMap); - } - - Map> timeData = toMap.get(destination); - if (timeData == null) { - timeData = new TreeMap<>(); - toMap.put(destination, timeData); - - try { - List stops; - stops = scenario.getTransitSchedule().getTransitLines().get(transitLine.getId()).getRoutes().get(route.getId()).getStops(); - if (stops == null) - throw new NullPointerException(); - Link fromLink = null; - Link toLink = null; - for (TransitRouteStop tss : stops) { - if (tss.getStopFacility().getId().toString().equals(origin)) { - fromLink = scenario.getNetwork().getLinks().get(tss.getStopFacility().getLinkId()); - } - if (tss.getStopFacility().getId().toString().equals(destination)) { - toLink = scenario.getNetwork().getLinks().get(tss.getStopFacility().getLinkId()); - } - } - if (fromLink == null || toLink == null) - throw new NullPointerException(); - NetworkRoute networkRoute = scenario.getTransitSchedule().getTransitLines().get(transitLine.getId()) - .getRoutes().get(route.getId()).getRoute(); - NetworkRoute subRoute = networkRoute.getSubRoute(fromLink.getId(), toLink.getId()); - List> linkIds = new ArrayList<>(); - linkIds.addAll(subRoute.getLinkIds()); - linkIds.add(toLink.getId()); - double freeSpeedTravelTime = 0; - for (Id id : linkIds) { - Link link = scenario.getNetwork().getLinks().get(id); - freeSpeedTravelTime += link.getLength() / link.getFreespeed(); - } - if (logarithmic) - timeData.put(0, new Tuple(Math.log(freeSpeedTravelTime), 0.005)); - else - timeData.put(0, new Tuple(freeSpeedTravelTime, 0.0)); - - } catch (NullPointerException ne) { - System.err.printf("Couldnt create STOP-STOP entry for for from: %s, to: %s, route: %s, line: %s\n", - origin, destination, route.getId().toString(), transitLine.getId().toString()); - continue TRANSITSTOPS; - } - - } else { - //value already exists (assuming singular stop-stop network routes) - continue TRANSITSTOPS; - } - - } - } - } - } - - - /** - * Retrieves the interpolated travel time for a combination of stops at a particular time, or the first/last variance observation if one cannot be interpolated. - *

- * Returns the error value of infinity for a compbination that doesn't appear in the map - * - * @param stopOId - * @param stopDId - * @param time - * @return the travel time, or Double.POSITIVE_INFINITY - */ - public double getStopStopTime(Id stopOId, Id stopDId, double time) { - Map>> toMap = stopStopTimes.get(stopOId.toString()); - - if (toMap == null) { - return errorValue(stopOId, stopDId); - } - - TreeMap> timedObservations = (TreeMap>) toMap.get(stopDId.toString()); - - if (timedObservations == null) { - return errorValue(stopOId, stopDId); - } - - Map.Entry> ceilingEntry = timedObservations.ceilingEntry((int) time); - Map.Entry> floorEntry = timedObservations.floorEntry((int) time); - if (ceilingEntry == null) { - if (floorEntry == null) { - return errorValue(stopOId, stopDId); - } else { - return floorEntry.getValue().getFirst(); - } - } else { - if (floorEntry == null) { - return ceilingEntry.getValue().getFirst(); - } else { - // I have both, so can interpolate a travel time - double x1 = floorEntry.getKey(); - double x2 = ceilingEntry.getKey(); - double y1 = floorEntry.getValue().getFirst(); - double y2 = ceilingEntry.getValue().getFirst(); - double m = (y2 - y1) / (x2 - x1); - double x = time - x1; - return y1 + m * x; - } - } - } - - private double errorValue(Id stopOId, Id stopDId) { - if (errorCounter < 10) { - System.err.println("No StopStop data for origin stop " + stopOId.toString() + ", destination stop " + stopDId.toString() + ". Returning estimation..."); - } else if (errorCounter == 10) { - System.err.println("No StopStop data for origin stop " + stopOId.toString() + ". Skipping further warnings..."); - } - errorCounter++; - - return Double.POSITIVE_INFINITY; - } - - /** - * Retrieves the interpolated travel time variance for a combination of stops at a particular time, or the first/last variance observation if one cannot be interpolated. - *

- * Returns the error value of infinity for a compbination that doesn't appear in the map - * - * @param stopOId - * @param stopDId - * @param time seconds till the start of the sim - * @return the travel time, or Double.POSITIVE_INFINITY - */ - public double getStopStopTimeVariance(Id stopOId, Id stopDId, double time) { - Map>> toMap = stopStopTimes.get(stopOId.toString()); - - if (toMap == null) { - return errorValue(stopOId, stopDId); - } - - TreeMap> timedObservations = (TreeMap>) toMap.get(stopDId.toString()); - - if (timedObservations == null) { - return errorValue(stopOId, stopDId); - } - - Map.Entry> ceilingEntry = timedObservations.ceilingEntry((int) time); - Map.Entry> floorEntry = timedObservations.floorEntry((int) time); - if (ceilingEntry == null) { - if (floorEntry == null) { - return 0; - } else { - return floorEntry.getValue().getSecond(); - } - } else { - if (floorEntry == null) { - return ceilingEntry.getValue().getSecond(); - } else { - // I have both, so can interpolate a travel time - double x1 = floorEntry.getKey(); - double x2 = ceilingEntry.getKey(); - double y1 = floorEntry.getValue().getSecond(); - double y2 = ceilingEntry.getValue().getSecond(); - double m = (y2 - y1) / (x2 - x1); - double x = time - x1; - return y1 + m * x; - } - } - } - - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancy.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancy.java deleted file mode 100644 index 22168b8ce75..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancy.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.vehicleOccupancy; - -import org.matsim.api.core.v01.Id; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -public interface VehicleOccupancy { - - //Methods - public double getVehicleOccupancy(Id stopOId, Id lineId, Id routeId, double time); - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancyCalculator.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancyCalculator.java deleted file mode 100644 index 9cae7720b1b..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancyCalculator.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.vehicleOccupancy; - -import java.util.HashMap; -import java.util.Map; - -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.events.handler.PersonEntersVehicleEventHandler; -import org.matsim.api.core.v01.events.handler.PersonLeavesVehicleEventHandler; -import org.matsim.api.core.v01.events.handler.TransitDriverStartsEventHandler; -import org.matsim.core.api.experimental.events.VehicleDepartsAtFacilityEvent; -import org.matsim.core.api.experimental.events.handler.VehicleDepartsAtFacilityEventHandler; -import org.matsim.core.config.Config; -import org.matsim.core.trafficmonitoring.TimeBinUtils; -import org.matsim.core.utils.collections.Tuple; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.vehicles.Vehicle; -import org.matsim.vehicles.VehicleCapacity; -import org.matsim.vehicles.Vehicles; - -public class VehicleOccupancyCalculator implements VehicleDepartsAtFacilityEventHandler, PersonEntersVehicleEventHandler, PersonLeavesVehicleEventHandler, TransitDriverStartsEventHandler { - - private final Map, Id>, Map, VehicleOccupancyData>> vehicleOccupancy = new HashMap, Id>, Map, VehicleOccupancyData>>(1000); - private double timeSlot; - private int totalTime; - private Map, Integer> ptVehicles = new HashMap, Integer>(); - private Map, Integer> capacities = new HashMap, Integer>(); - private Map, Tuple, Id>> linesRoutesOfVehicle = new HashMap, Tuple, Id>>(); - private final Vehicles vehicles; - - //Constructors - public VehicleOccupancyCalculator(final TransitSchedule transitSchedule, final Vehicles vehicles, final Config config) { - this(transitSchedule, vehicles, config.travelTimeCalculator().getTraveltimeBinSize(), (int) (config.qsim().getEndTime().seconds()-config.qsim().getStartTime().seconds())); - } - public VehicleOccupancyCalculator(final TransitSchedule transitSchedule, final Vehicles vehicles, final double timeSlot, final int totalTime) { - this.timeSlot = timeSlot; - this.totalTime = totalTime; - for(TransitLine line:transitSchedule.getTransitLines().values()) - for(TransitRoute route:line.getRoutes().values()) { - Map, VehicleOccupancyData> routeMap = new HashMap, VehicleOccupancyData>(100); - vehicleOccupancy.put(new Tuple, Id>(line.getId(), route.getId()), routeMap); - for(int s=0; s stopOId, Id lineId, Id routeId, double time) { - return VehicleOccupancyCalculator.this.getVehicleOccupancy(stopOId, lineId, routeId, time); - } - }; - } - private double getVehicleOccupancy(Id stopOId, Id lineId, Id routeId, double time) { - return vehicleOccupancy.get(new Tuple, Id>(lineId, routeId)).get(stopOId).getVehicleOccupancy(TimeBinUtils.getTimeBinIndex(time, timeSlot, totalTime)); - } - @Override - public void reset(int iteration) { - for(Map, VehicleOccupancyData> map:vehicleOccupancy.values()) - for(VehicleOccupancyData vehicleOcupancyData:map.values()) - vehicleOcupancyData.resetVehicleOccupancies(); - this.ptVehicles.clear(); - } - @Override - public void handleEvent(VehicleDepartsAtFacilityEvent event) { - Integer num = ptVehicles.get(event.getVehicleId()); - if(num!=null) { - VehicleOccupancyData vehicleOccupancyData = vehicleOccupancy.get(linesRoutesOfVehicle.get(event.getVehicleId())).get(event.getFacilityId()); - if(vehicleOccupancyData!=null) - vehicleOccupancyData.addVehicleOccupancy( - TimeBinUtils.getTimeBinIndex(event.getTime(), timeSlot, - TimeBinUtils.getTimeBinCount(totalTime, timeSlot)), - num/(double)capacities.get(event.getVehicleId())); - } - } - @Override - public void handleEvent(PersonLeavesVehicleEvent event) { - Integer num = this.ptVehicles.get(event.getVehicleId()); - if(num!=null) - this.ptVehicles.put(event.getVehicleId(), num-1); - } - @Override - public void handleEvent(PersonEntersVehicleEvent event) { - Integer num = this.ptVehicles.get(event.getVehicleId()); - if(num!=null) - this.ptVehicles.put(event.getVehicleId(), num+1); - } - @Override - public void handleEvent(TransitDriverStartsEvent event) { - this.ptVehicles.put(event.getVehicleId(), 0); - VehicleCapacity vehicleCapacity = vehicles.getVehicles().get(event.getVehicleId()).getType().getCapacity(); - this.capacities.put(event.getVehicleId(), vehicleCapacity.getSeats()+vehicleCapacity.getStandingRoom()); - linesRoutesOfVehicle.put(event.getVehicleId(), new Tuple, Id>(event.getTransitLineId(), event.getTransitRouteId())); - } - - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancyData.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancyData.java deleted file mode 100644 index 59e155a79e9..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancyData.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.vehicleOccupancy; - -public interface VehicleOccupancyData { - - double getVehicleOccupancy(int i); - void addVehicleOccupancy(final int timeSlot, final double vehicleOccupancy); - void resetVehicleOccupancies(); - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancyDataArray.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancyDataArray.java deleted file mode 100644 index 29c405c1772..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/vehicleOccupancy/VehicleOccupancyDataArray.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.vehicleOccupancy; - -public class VehicleOccupancyDataArray implements VehicleOccupancyData { - - //Attributes - private double[] vehicleOccupancies; - private int[] numTimes; - private int lastPosition; - - //Constructors - public VehicleOccupancyDataArray(int numSlots) { - vehicleOccupancies = new double[numSlots]; - numTimes = new int[numSlots]; - resetVehicleOccupancies(); - } - - //Methods - @Override - public double getVehicleOccupancy(int timeSlot) { - if(timeSlot>lastPosition) - return 1; - else - while(vehicleOccupancies[timeSlot]==-1) - timeSlot++; - return vehicleOccupancies[timeSlot]; - } - @Override - public synchronized void addVehicleOccupancy(int timeSlot, double vehicleOccupancy) { - if(lastPosition lineId, Id routeId, Id stopId, double time); - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeCalculator.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeCalculator.java deleted file mode 100644 index 3cec2e82f67..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeCalculator.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.matsim.contrib.eventsBasedPTRouter.waitTimes; - -import com.google.inject.Provider; -import com.google.inject.Provides; -import org.matsim.api.core.v01.Id; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - - -public interface WaitTimeCalculator extends Provider { - double getRouteStopWaitTime(Id lineId, Id routeId, Id stopId, double time); - - @Override - @Provides - WaitTime get(); -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeCalculatorImpl.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeCalculatorImpl.java deleted file mode 100644 index ed80d814c81..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeCalculatorImpl.java +++ /dev/null @@ -1,181 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * WaitTimeCalculator.java - * * - * *********************************************************************** * - * * - * 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.eventsBasedPTRouter.waitTimes; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.PersonDepartureEvent; -import org.matsim.api.core.v01.events.PersonEntersVehicleEvent; -import org.matsim.api.core.v01.events.TransitDriverStartsEvent; -import org.matsim.api.core.v01.events.handler.PersonDepartureEventHandler; -import org.matsim.api.core.v01.events.handler.PersonEntersVehicleEventHandler; -import org.matsim.api.core.v01.events.handler.TransitDriverStartsEventHandler; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; -import org.matsim.core.api.experimental.events.handler.VehicleArrivesAtFacilityEventHandler; -import org.matsim.core.config.Config; -import org.matsim.core.trafficmonitoring.TimeBinUtils; -import org.matsim.core.utils.collections.Tuple; -import org.matsim.pt.transitSchedule.api.Departure; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitRouteStop; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.vehicles.Vehicle; - -import com.google.inject.Inject; -import com.google.inject.Provider; -import com.google.inject.Singleton; - -/** - * Save waiting times of agents while mobsim is running - * - * @author sergioo - */ - -@Singleton -public class WaitTimeCalculatorImpl implements WaitTimeCalculator, PersonDepartureEventHandler, PersonEntersVehicleEventHandler, TransitDriverStartsEventHandler, VehicleArrivesAtFacilityEventHandler, Provider { - - //Attributes - private final double timeSlot; - private final int totalTime; - private final Map, Id>, Map, WaitTimeData>> waitTimes = new HashMap, Id>, Map, WaitTimeData>>(1000); - private final Map, Id>, Map, double[]>> scheduledWaitTimes = new HashMap, Id>, Map, double[]>>(1000); - private final Map, Double> agentsWaitingData = new HashMap, Double>(); - private Map, Tuple, Id>> linesRoutesOfVehicle = new HashMap, Tuple, Id>>(); - private Map, Id> stopOfVehicle = new HashMap, Id>(); - - //Constructors - @Inject - public WaitTimeCalculatorImpl(final TransitSchedule transitSchedule, final Config config, EventsManager eventsManager) { - this(transitSchedule, config.travelTimeCalculator().getTraveltimeBinSize(), (int) (config.qsim().getEndTime().seconds()-config.qsim().getStartTime().seconds())); - eventsManager.addHandler(this); - } - public WaitTimeCalculatorImpl(final TransitSchedule transitSchedule, final double timeSlot, final int totalTime) { - this.timeSlot = timeSlot; - this.totalTime = totalTime; - for(TransitLine line:transitSchedule.getTransitLines().values()) - for(TransitRoute route:line.getRoutes().values()) { - double[] sortedDepartures = new double[route.getDepartures().size()]; - int d=0; - for(Departure departure:route.getDepartures().values()) - sortedDepartures[d++] = departure.getDepartureTime(); - Arrays.sort(sortedDepartures); - Map, WaitTimeData> stopsMap = new HashMap, WaitTimeData>(100); - Map, double[]> stopsScheduledMap = new HashMap, double[]>(100); - for(TransitRouteStop stop:route.getStops()) { - stopsMap.put(stop.getStopFacility().getId(), new WaitTimeDataArray(TimeBinUtils.getTimeBinCount(totalTime, timeSlot))); - double[] cacheWaitTimes = new double[TimeBinUtils.getTimeBinCount(totalTime, timeSlot)]; - for(int i=0; i24*3600) - endTime-=24*3600; - cacheWaitTimes[i] = Double.NaN; - SORTED_DEPARTURES: - for(double departure:sortedDepartures) { - double arrivalTime = departure+stop.getArrivalOffset().or(stop::getDepartureOffset).seconds(); - if(arrivalTime>=endTime) { - cacheWaitTimes[i] = arrivalTime-endTime; - break SORTED_DEPARTURES; - } - } - if(Double.isNaN(cacheWaitTimes[i])) - cacheWaitTimes[i] = sortedDepartures[0]+24*3600+stop.getArrivalOffset().or(stop::getDepartureOffset).seconds()-endTime; - } - stopsScheduledMap.put(stop.getStopFacility().getId(), cacheWaitTimes); - } - Tuple, Id> key = new Tuple, Id>(line.getId(), route.getId()); - waitTimes.put(key, stopsMap); - scheduledWaitTimes.put(key, stopsScheduledMap); - } - } - - //Methods - @Override - public WaitTime get() { - return new WaitTime() { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public double getRouteStopWaitTime(Id lineId, Id routeId, Id stopId, double time) { - return WaitTimeCalculatorImpl.this.getRouteStopWaitTime(lineId, routeId, stopId, time); - } - }; - } - @Override - public double getRouteStopWaitTime(Id lineId, Id routeId, Id stopId, double time) { - Tuple, Id> key = new Tuple, Id>(lineId, routeId); - WaitTimeData waitTimeData = waitTimes.get(key).get(stopId); - int timeBinIndex = TimeBinUtils.getTimeBinIndex(time, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)); - if(waitTimeData.getNumData(timeBinIndex)==0) { - double[] waitTimes = scheduledWaitTimes.get(key).get(stopId); - return waitTimes[timeBinIndex, WaitTimeData> routeData:waitTimes.values()) - for(WaitTimeData waitTimeData:routeData.values()) - waitTimeData.resetWaitTimes(); - agentsWaitingData.clear(); - linesRoutesOfVehicle.clear(); - stopOfVehicle.clear(); - } - @Override - public void handleEvent(PersonDepartureEvent event) { - if(event.getLegMode().equals("pt") && agentsWaitingData.get(event.getPersonId())==null) - agentsWaitingData.put(event.getPersonId(), event.getTime()); - else if(agentsWaitingData.get(event.getPersonId())!=null) - new RuntimeException("Departing with old data"); - } - @Override - public void handleEvent(PersonEntersVehicleEvent event) { - Double startWaitingTime = agentsWaitingData.get(event.getPersonId()); - if(startWaitingTime!=null) { - Tuple, Id> lineRoute = linesRoutesOfVehicle.get(event.getVehicleId()); - WaitTimeData data = waitTimes.get(lineRoute).get(stopOfVehicle.get(event.getVehicleId())); - data.addWaitTime((int) (startWaitingTime/timeSlot), event.getTime()-startWaitingTime); - agentsWaitingData.remove(event.getPersonId()); - } - } - - @Override - public void handleEvent(VehicleArrivesAtFacilityEvent event) { - if(linesRoutesOfVehicle.get(event.getVehicleId())!=null) - stopOfVehicle.put(event.getVehicleId(), event.getFacilityId()); - } - - @Override - public void handleEvent(TransitDriverStartsEvent event) { - linesRoutesOfVehicle.put(event.getVehicleId(), new Tuple, Id>(event.getTransitLineId(), event.getTransitRouteId())); - } - -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeCalculatorSerializable.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeCalculatorSerializable.java deleted file mode 100644 index 17a93bd0410..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeCalculatorSerializable.java +++ /dev/null @@ -1,216 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * WaitTimeCalculator.java - * * - * *********************************************************************** * - * * - * 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.eventsBasedPTRouter.waitTimes; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.PersonDepartureEvent; -import org.matsim.api.core.v01.events.PersonEntersVehicleEvent; -import org.matsim.api.core.v01.events.TransitDriverStartsEvent; -import org.matsim.api.core.v01.events.handler.PersonDepartureEventHandler; -import org.matsim.api.core.v01.events.handler.PersonEntersVehicleEventHandler; -import org.matsim.api.core.v01.events.handler.TransitDriverStartsEventHandler; -import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; -import org.matsim.core.api.experimental.events.handler.VehicleArrivesAtFacilityEventHandler; -import org.matsim.core.config.Config; -import org.matsim.core.trafficmonitoring.TimeBinUtils; -import org.matsim.core.utils.collections.Tuple; -import org.matsim.pt.transitSchedule.api.Departure; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitRouteStop; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -import com.google.inject.Provider; -import com.google.inject.Provides; - -/** - * Save waiting times of agents while mobsim is running - * - * @author sergioo - */ - -public class WaitTimeCalculatorSerializable implements - WaitTimeCalculator, PersonDepartureEventHandler, - PersonEntersVehicleEventHandler, TransitDriverStartsEventHandler, - VehicleArrivesAtFacilityEventHandler, Serializable, - Provider { - - /** - * - */ - private static final long serialVersionUID = 1L; - private static int scheduleCalls; - private static int waitTimeCalls; - //Attributes - private final double timeSlot; - private final int totalTime; - private final Map, Map> waitTimes = new HashMap, Map>(1000); - private final Map, Map> scheduledWaitTimes = new HashMap, Map>(1000); - private final Map agentsWaitingData = new HashMap(); - private Map> linesRoutesOfVehicle = new HashMap>(); - private Map stopOfVehicle = new HashMap(); - - public static void printCallStatisticsAndReset() { - Logger logger = LogManager.getLogger(WaitTimeCalculatorSerializable.class); - logger.warn("scheduled wait time calls vs unscheduled: " + scheduleCalls + " : " + waitTimeCalls); - scheduleCalls = 0; - waitTimeCalls = 0; - } - - //Constructors - public WaitTimeCalculatorSerializable(final TransitSchedule transitSchedule, final Config config) { - this(transitSchedule, config.travelTimeCalculator().getTraveltimeBinSize(), (int) (config.qsim().getEndTime().seconds() - config.qsim().getStartTime().seconds())); - } - - public WaitTimeCalculatorSerializable(final TransitSchedule transitSchedule, final double timeSlot, final int totalTime) { - this.timeSlot = timeSlot; - this.totalTime = totalTime; - for (TransitLine line : transitSchedule.getTransitLines().values()) - for (TransitRoute route : line.getRoutes().values()) { - double[] sortedDepartures = new double[route.getDepartures().size()]; - int d = 0; - for (Departure departure : route.getDepartures().values()) - sortedDepartures[d++] = departure.getDepartureTime(); - Arrays.sort(sortedDepartures); - Map stopsMap = new HashMap(100); - Map stopsScheduledMap = new HashMap(100); - for (TransitRouteStop stop : route.getStops()) { - stopsMap.put(stop.getStopFacility().getId().toString(), new WaitTimeDataArray(TimeBinUtils.getTimeBinCount(totalTime , timeSlot))); - double[] cacheWaitTimes = new double[TimeBinUtils.getTimeBinCount(totalTime , timeSlot)]; - for (int i = 0; i < cacheWaitTimes.length; i++) { - double endTime = timeSlot * (i + 1); - if (endTime > 24 * 3600) - endTime -= 24 * 3600; - cacheWaitTimes[i] = Double.NaN; - SORTED_DEPARTURES: - for (double departure : sortedDepartures) { - double arrivalTime = departure + stop.getArrivalOffset().or(stop::getDepartureOffset).seconds(); - if (arrivalTime >= endTime) { - cacheWaitTimes[i] = arrivalTime - endTime; - break SORTED_DEPARTURES; - } - } - if (Double.isNaN(cacheWaitTimes[i])) - cacheWaitTimes[i] = sortedDepartures[0] + 24 * 3600 + stop.getArrivalOffset().or(stop::getDepartureOffset).seconds() - endTime; - } - stopsScheduledMap.put(stop.getStopFacility().getId().toString(), cacheWaitTimes); - } - Tuple key = new Tuple(line.getId().toString(), route.getId().toString()); - waitTimes.put(key, stopsMap); - scheduledWaitTimes.put(key, stopsScheduledMap); - } - } - - //Methods - public WaitTime getWaitTimes() { - return new WaitTime() { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public double getRouteStopWaitTime(Id lineId, Id routeId, Id stopId, double time) { - return WaitTimeCalculatorSerializable.this.getRouteStopWaitTime(lineId, routeId, stopId, time); - } - }; - } - - @Override - public double getRouteStopWaitTime(Id lineId, Id routeId, Id stopId, double time) { - Tuple key = new Tuple(lineId.toString(), routeId.toString()); - waitTimeCalls++; - WaitTimeData waitTimeData = waitTimes.get(key).get(stopId.toString()); - int timeBinIndex = TimeBinUtils.getTimeBinIndex(time, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)); - if (waitTimeData.getNumData(timeBinIndex) == 0) { - scheduleCalls++; - double[] waitTimes = scheduledWaitTimes.get(key).get(stopId.toString()); - return waitTimes[timeBinIndex < waitTimes.length ? timeBinIndex : (waitTimes.length - 1)]; - } else { - return waitTimeData.getWaitTime(timeBinIndex); - } - } - - @Override - public void reset(int iteration) { - for (Map routeData : waitTimes.values()) - for (WaitTimeData waitTimeData : routeData.values()) - waitTimeData.resetWaitTimes(); - agentsWaitingData.clear(); - linesRoutesOfVehicle.clear(); - stopOfVehicle.clear(); - } - - @Override - public void handleEvent(PersonDepartureEvent event) { - if (event.getLegMode().equals("pt") && agentsWaitingData.get(event.getPersonId().toString()) == null) - agentsWaitingData.put(event.getPersonId().toString(), event.getTime()); - else if (agentsWaitingData.get(event.getPersonId().toString()) != null) - new RuntimeException("Departing with old data"); - } - - @Override - public void handleEvent(PersonEntersVehicleEvent event) { - Double startWaitingTime = agentsWaitingData.get(event.getPersonId().toString()); - if (startWaitingTime != null) { - Tuple lineRoute = linesRoutesOfVehicle.get(event.getVehicleId().toString()); - WaitTimeData data = waitTimes.get(lineRoute).get(stopOfVehicle.get(event.getVehicleId().toString())); - data.addWaitTime(TimeBinUtils.getTimeBinIndex(startWaitingTime, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)), - event.getTime() - startWaitingTime); - agentsWaitingData.remove(event.getPersonId().toString()); - } - } - - @Override - public void handleEvent(VehicleArrivesAtFacilityEvent event) { - if (linesRoutesOfVehicle.get(event.getVehicleId().toString()) != null) - stopOfVehicle.put(event.getVehicleId().toString(), event.getFacilityId().toString()); - } - - @Override - public void handleEvent(TransitDriverStartsEvent event) { - linesRoutesOfVehicle.put(event.getVehicleId().toString(), new Tuple(event.getTransitLineId().toString(), event.getTransitRouteId().toString())); - } - - @Override - @Provides - public WaitTime get() { - return new WaitTime() { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public double getRouteStopWaitTime(Id lineId, Id routeId, Id stopId, double time) { - return WaitTimeCalculatorSerializable.this.getRouteStopWaitTime(lineId, routeId, stopId, time); - } - }; - } -} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeDataArray.java b/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeDataArray.java deleted file mode 100644 index 43064e2f913..00000000000 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeDataArray.java +++ /dev/null @@ -1,67 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * WaitTimeCalculator.java - * * - * *********************************************************************** * - * * - * 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.eventsBasedPTRouter.waitTimes; - -/** - * Array implementation of the structure for saving wait times - * - * @author sergioo - */ - -public class WaitTimeDataArray implements WaitTimeData { - - /** - * - */ - private static final long serialVersionUID = 1L; - //Attributes - private double[] waitTimes; - private int[] numTimes; - - //Constructors - public WaitTimeDataArray(int numSlots) { - waitTimes = new double[numSlots]; - numTimes = new int[numSlots]; - resetWaitTimes(); - } - - //Methods - @Override - public void resetWaitTimes() { - for(int i=0; i, Id>, Map, WaitTimeData>> waitTimes = new HashMap, Id>, Map, WaitTimeData>>(1000); - private final Map, Id>, Map, double[]>> scheduledWaitTimes = new HashMap, Id>, Map, double[]>>(1000); - private final Map, Double> agentsWaitingData = new HashMap, Double>(); - private final Map, Integer> agentsCurrentLeg = new HashMap, Integer>(); - private final Population population; - - //Constructors - @Inject - public WaitTimeStuckCalculator(final Population population, final TransitSchedule transitSchedule, final Config config, final EventsManager eventsManager) { - this(population, transitSchedule, config.travelTimeCalculator().getTraveltimeBinSize(), (int) (config.qsim().getEndTime().seconds()-config.qsim().getStartTime().seconds())); - eventsManager.addHandler(this); - } - public WaitTimeStuckCalculator(final Population population, final TransitSchedule transitSchedule, final double timeSlot, final int totalTime) { - this.population = population; - this.timeSlot = timeSlot; - this.totalTime = totalTime; - for(TransitLine line:transitSchedule.getTransitLines().values()) - for(TransitRoute route:line.getRoutes().values()) { - double[] sortedDepartures = new double[route.getDepartures().size()]; - int d=0; - for(Departure departure:route.getDepartures().values()) - sortedDepartures[d++] = departure.getDepartureTime(); - Arrays.sort(sortedDepartures); - Map, WaitTimeData> stopsMap = new HashMap, WaitTimeData>(100); - Map, double[]> stopsScheduledMap = new HashMap, double[]>(100); - for(TransitRouteStop stop:route.getStops()) { - stopsMap.put(stop.getStopFacility().getId(), new WaitTimeDataArray(TimeBinUtils.getTimeBinCount(totalTime, timeSlot))); - double[] cacheWaitTimes = new double[TimeBinUtils.getTimeBinCount(totalTime, timeSlot)]; - for(int i=0; i24*3600) - endTime-=24*3600; - cacheWaitTimes[i] = Double.NaN; - SORTED_DEPARTURES: - for(double departure:sortedDepartures) { - double arrivalTime = departure+stop.getArrivalOffset().or(stop::getDepartureOffset).seconds(); - if(arrivalTime>=endTime) { - cacheWaitTimes[i] = arrivalTime-endTime; - break SORTED_DEPARTURES; - } - } - if(Double.isNaN(cacheWaitTimes[i])) - cacheWaitTimes[i] = sortedDepartures[0]+24*3600+stop.getArrivalOffset().or(stop::getDepartureOffset).seconds()-endTime; - } - stopsScheduledMap.put(stop.getStopFacility().getId(), cacheWaitTimes); - } - Tuple, Id> key = new Tuple, Id>(line.getId(), route.getId()); - waitTimes.put(key, stopsMap); - scheduledWaitTimes.put(key, stopsScheduledMap); - } - } - - //Methods - public double getRouteStopWaitTime(Id lineId, Id routeId, Id stopId, double time) { - Tuple, Id> key = new Tuple, Id>(lineId, routeId); - WaitTimeData waitTimeData = waitTimes.get(key).get(stopId); - int timeBinIndex = TimeBinUtils.getTimeBinIndex(time, timeSlot, TimeBinUtils.getTimeBinCount(totalTime, timeSlot)); - if(waitTimeData.getNumData(timeBinIndex)==0) { - double[] waitTimes = scheduledWaitTimes.get(key).get(stopId); - return waitTimes[timeBinIndex, WaitTimeData> routeData:waitTimes.values()) - for(WaitTimeData waitTimeData:routeData.values()) - waitTimeData.resetWaitTimes(); - agentsWaitingData.clear(); - agentsCurrentLeg.clear(); - } - @Override - public void handleEvent(PersonDepartureEvent event) { - Integer currentLeg = agentsCurrentLeg.get(event.getPersonId()); - if(currentLeg == null) - currentLeg = 0; - else - currentLeg++; - agentsCurrentLeg.put(event.getPersonId(), currentLeg); - if(event.getLegMode().equals("pt") && agentsWaitingData.get(event.getPersonId())==null) - agentsWaitingData.put(event.getPersonId(), event.getTime()); - else if(agentsWaitingData.get(event.getPersonId())!=null) - new RuntimeException("Departing with old data"); - } - @Override - public void handleEvent(PersonEntersVehicleEvent event) { - Double startWaitingTime = agentsWaitingData.get(event.getPersonId()); - if(startWaitingTime!=null) { - int legs = 0, currentLeg = agentsCurrentLeg.get(event.getPersonId()); - PLAN_ELEMENTS: - for(PlanElement planElement:population.getPersons().get(event.getPersonId()).getSelectedPlan().getPlanElements()) - if(planElement instanceof Leg) { - if(currentLeg==legs) { - Route route = (((Leg)planElement).getRoute()); - TransitPassengerRoute eRoute = (TransitPassengerRoute) new DefaultTransitPassengerRouteFactory(). - createRoute(route.getStartLinkId(), route.getEndLinkId()); - eRoute.setStartLinkId(route.getStartLinkId()); - eRoute.setEndLinkId(route.getEndLinkId()); - eRoute.setRouteDescription(route.getRouteDescription()); - WaitTimeData data = waitTimes.get(new Tuple, Id>(eRoute.getLineId(), - eRoute.getRouteId())).get(eRoute.getAccessStopId()); - data.addWaitTime(TimeBinUtils.getTimeBinIndex(startWaitingTime, timeSlot, totalTime), event.getTime()-startWaitingTime); - agentsWaitingData.remove(event.getPersonId()); - break PLAN_ELEMENTS; - } - else - legs++; - } - } - } - - @Override - public void handleEvent(PersonStuckEvent event) { - Double startWaitingTime = agentsWaitingData.get(event.getPersonId()); - if(startWaitingTime!=null) { - int legs = 0, currentLeg = agentsCurrentLeg.get(event.getPersonId()); - PLAN_ELEMENTS: - for(PlanElement planElement:population.getPersons().get(event.getPersonId()).getSelectedPlan().getPlanElements()) - if(planElement instanceof Leg) { - if(currentLeg==legs) { - Route route = ((Leg)planElement).getRoute(); - TransitPassengerRoute eRoute = (TransitPassengerRoute) new DefaultTransitPassengerRouteFactory(). - createRoute(route.getStartLinkId(), route.getEndLinkId()); - eRoute.setStartLinkId(route.getStartLinkId()); - eRoute.setEndLinkId(route.getEndLinkId()); - eRoute.setRouteDescription(route.getRouteDescription()); - WaitTimeData data = waitTimes.get(new Tuple, Id>(eRoute.getLineId(), - eRoute.getRouteId())).get(eRoute.getAccessStopId()); - if(data!=null) - data.addWaitTime(TimeBinUtils.getTimeBinIndex(startWaitingTime, timeSlot, totalTime), event.getTime()-startWaitingTime); - agentsWaitingData.remove(event.getPersonId()); - break PLAN_ELEMENTS; - } - else - legs++; - } - } - } - - @Override - public WaitTime get() { - return new WaitTime() { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public double getRouteStopWaitTime(Id lineId, Id routeId, Id stopId, double time) { - return WaitTimeStuckCalculator.this.getRouteStopWaitTime(lineId, routeId, stopId, time); - } - - }; - } -} - diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierUtils.java b/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierUtils.java deleted file mode 100644 index a2f2c0d4cdb..00000000000 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierUtils.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * *********************************************************************** * - * project: org.matsim.* - * *********************************************************************** * - * * - * copyright : (C) 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.freight.carrier; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.TransportMode; -import org.matsim.vehicles.Vehicle; - -import java.util.ArrayList; -import java.util.List; - -public class CarrierUtils{ - - @SuppressWarnings("unused") - private static final Logger log = LogManager.getLogger(CarrierUtils.class); - - public static Carrier createCarrier( Id id ){ - return new CarrierImpl(id); - } - - /** - * Adds an carrierVehicle to the CarrierCapabilities of the Carrier. - * @param carrier - * @param carrierVehicle - */ - public static void addCarrierVehicle(Carrier carrier, CarrierVehicle carrierVehicle){ - carrier.getCarrierCapabilities().getCarrierVehicles().put(carrierVehicle.getId(), carrierVehicle); - } - - public static CarrierVehicle getCarrierVehicle(Carrier carrier, Id vehicleId){ - CarrierVehicle veh = carrier.getCarrierCapabilities().getCarrierVehicles().get(vehicleId); - if(veh != null){ - return veh; - } - log.error("Vehicle with Id does not exists", new IllegalStateException("vehicle with id " + vehicleId + " is missing in Carrier: " + carrier.getId())); - return null; - } - - /** - * Adds an {@link CarrierService} to the {@link Carrier}. - * @param carrier - * @param carrierService - */ - public static void addService(Carrier carrier, CarrierService carrierService){ - carrier.getServices().put(carrierService.getId(), carrierService); - } - - public static CarrierService getService(Carrier carrier, Id serviceId){ - CarrierService service = carrier.getServices().get(serviceId); - if(service != null){ - return service; - } - log.error("Service with Id does not exists", new IllegalStateException("Service with id " + serviceId + " is missing in Carrier: " + carrier.getId())); - return null; - } - - /** - * Adds an {@link CarrierShipment} to the {@link Carrier}. - * @param carrier - * @param carrierShipment - */ - public static void addShipment(Carrier carrier, CarrierShipment carrierShipment){ - carrier.getShipments().put(carrierShipment.getId(), carrierShipment); - } - - public static CarrierShipment getShipment(Carrier carrier, Id serviceId){ - CarrierShipment shipment = carrier.getShipments().get(serviceId); - if(shipment != null){ - return shipment; - } - log.error("Shipment with Id does not exists", new IllegalStateException("Shipment with id " + serviceId + " is missing in Carrier: " + carrier.getId())); - return null; - } - - - - public static CarrierPlan copyPlan( CarrierPlan plan2copy ) { - List tours = new ArrayList<>(); - for (ScheduledTour sTour : plan2copy.getScheduledTours()) { - double depTime = sTour.getDeparture(); - CarrierVehicle vehicle = sTour.getVehicle(); - Tour tour = sTour.getTour().duplicate(); - tours.add(ScheduledTour.newInstance(tour, vehicle, depTime)); - } - CarrierPlan copiedPlan = new CarrierPlan(plan2copy.getCarrier(), tours); - double initialScoreOfCopiedPlan = plan2copy.getScore(); - copiedPlan.setScore(initialScoreOfCopiedPlan); - return copiedPlan; - - } - - private static final String CARRIER_MODE = "carrierMode" ; - public static String getCarrierMode( Carrier carrier ) { - String result = (String) carrier.getAttributes().getAttribute( CARRIER_MODE ); - if ( result == null ){ - return TransportMode.car ; - } else { - return result ; - } - } - public static void setCarrierMode( Carrier carrier, String carrierMode ) { - carrier.getAttributes().putAttribute( CARRIER_MODE, carrierMode ) ; - } - - private static final String JSPRIT_ITERATIONS="jspritIterations" ; - public static int getJspritIterations( Carrier carrier ) { - Integer result = (Integer) carrier.getAttributes().getAttribute( JSPRIT_ITERATIONS ); - if (result == null){ - log.error("Requested attribute jspritIterations does not exists. Will return " + Integer.MIN_VALUE); - return Integer.MIN_VALUE; - } else { - return result ; - } - } - - public static void setJspritIterations( Carrier carrier, int jspritIterations ) { - carrier.getAttributes().putAttribute( JSPRIT_ITERATIONS , jspritIterations ) ; - } - - -} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventsReaders.java b/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventsReaders.java deleted file mode 100644 index c268d7d1184..00000000000 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventsReaders.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * *********************************************************************** * - * project: org.matsim.* - * *********************************************************************** * - * * - * copyright : (C) 2023 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.freight.events; - -import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.events.MatsimEventsReader; - -import java.util.Map; - -/** - * Creates an {@link MatsimEventsReader} that also handles the carrier specific events. - *

- * This is a quickfix for teaching and thus _not_ complete. Needs to get completed and secured by unit-testing later (KMT, feb'23) - * - * @author kturner (Kai Martins-Turner) - */ -public class CarrierEventsReaders { - - public static Map createCustomEventMappers() { - return Map.of( - CarrierTourStartEvent.EVENT_TYPE, CarrierTourStartEvent::convert, // - CarrierTourEndEvent.EVENT_TYPE, CarrierTourEndEvent::convert - // more will follow later, KMT feb'23 - ); - } - - public static MatsimEventsReader createEventsReader(EventsManager eventsManager) { - MatsimEventsReader reader = new MatsimEventsReader(eventsManager); - createCustomEventMappers().forEach(reader::addCustomEventMapper); - return reader; - } -} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/HasCarrierId.java b/contribs/freight/src/main/java/org/matsim/contrib/freight/events/HasCarrierId.java deleted file mode 100644 index dbf01dd9590..00000000000 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/HasCarrierId.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.matsim.contrib.freight.events; - -import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; - -/** - * @author Kai Martins-Turner (kturner) - */ -public interface HasCarrierId { - String ATTRIBUTE_CARRIER_ID = "carrierId"; - - Id getCarrierId(); -} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/Vehicle2CarrierEventHandler.java b/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/Vehicle2CarrierEventHandler.java deleted file mode 100644 index 0757c8b1333..00000000000 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/Vehicle2CarrierEventHandler.java +++ /dev/null @@ -1,69 +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.freight.events.eventhandler; - -import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.events.CarrierTourEndEvent; -import org.matsim.contrib.freight.events.CarrierTourStartEvent; -import org.matsim.vehicles.Vehicle; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Basic event handler that collects the relation between vehicles and carrier. - * Necessary since link enter and leave events do not contain any information of the carrier. - * For the connection between driver and Vehicle the {@link Vehicle2CarrierEventHandler} can be used. - * - * @author kturner - */ -public final class Vehicle2CarrierEventHandler implements FreightTourStartEventHandler, FreightTourEndEventHandler { - - - // Comment from Janek (in https://github.com/matsim-org/matsim-libs/pull/2128) - // Is this handler ever going to be called concurrently? If not a normal HashMap is probably sufficient - // At least the default events manager guarantees single threaded invocation of your handler. - // --> we can check this. Currently, it was made only analogous to Vehicle2DriverEventHandler kmt sep'22 - private final Map, Id> carrierVehicles = new ConcurrentHashMap<>(); - - @Override - public void reset(int iteration) { - carrierVehicles.clear(); - } - - @Override - public void handleEvent(CarrierTourStartEvent event) { - carrierVehicles.put(event.getVehicleId(), event.getCarrierId()); - } - - @Override - public void handleEvent(CarrierTourEndEvent event) { - carrierVehicles.remove(event.getVehicleId()); - } - - /** - * @param vehicleId the unique vehicle identifier. - * @return person id of the driver - */ - public Id getCarrierOfVehicle(Id vehicleId){ - return carrierVehicles.get(vehicleId); - } -} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/NetworkRouter.java b/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/NetworkRouter.java deleted file mode 100644 index 4d43abb8e73..00000000000 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/NetworkRouter.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Stefan Schroeder. - * eMail: stefan.schroeder@kit.edu - *

- * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v2.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html - *

- * Contributors: - * Stefan Schroeder - initial API and implementation - ******************************************************************************/ -package org.matsim.contrib.freight.jsprit; - -import org.matsim.contrib.freight.carrier.CarrierPlan; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.controler.CarrierTimeAndSpaceTourRouter; - -/** - * Router that routes {@link CarrierPlan}. - * - * @author stefan schröder - * - */ -public class NetworkRouter { - - /** - * Routes the {@link CarrierPlan} with the router defined in {@link NetworkBasedTransportCosts}. - * - *

Note that this changes the plan, i.e. it adds routes to the input-plan. - * - * @param {@link CarrierPlan} - * @param {@link NetworkBasedTransportCosts} - */ - public static void routePlan(CarrierPlan plan, VRPTransportCosts freightTransportCosts){ - if( plan == null) throw new IllegalStateException("plan is missing."); - for( ScheduledTour tour : plan.getScheduledTours()){ - new CarrierTimeAndSpaceTourRouter( freightTransportCosts.getRouter(), freightTransportCosts.getNetwork(), freightTransportCosts.getTravelTime()).route(tour ); - } - } - -} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/Carrier.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/Carrier.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/Carrier.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/Carrier.java index 52812bfbac7..e4363accdf8 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/Carrier.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/Carrier.java @@ -19,15 +19,15 @@ * */ -package org.matsim.contrib.freight.carrier; - -import java.util.List; -import java.util.Map; +package org.matsim.freight.carriers; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.HasPlansAndId; import org.matsim.utils.objectattributes.attributable.Attributable; +import java.util.List; +import java.util.Map; + /** * A carrier. * diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierCapabilities.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierCapabilities.java similarity index 99% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierCapabilities.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierCapabilities.java index 08808a2db6c..fa14ddfd9bb 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierCapabilities.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierCapabilities.java @@ -19,14 +19,14 @@ * */ -package org.matsim.contrib.freight.carrier; - -import java.util.*; +package org.matsim.freight.carriers; import org.matsim.api.core.v01.Id; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; +import java.util.*; + /** * This contains the capabilities/resources a carrier has/can deploy. * diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierConstants.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierConstants.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierConstants.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierConstants.java index 4382b2b5bd9..fac638f18bb 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierConstants.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierConstants.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; public class CarrierConstants { diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierImpl.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierImpl.java similarity index 96% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierImpl.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierImpl.java index 706010e95f5..9d8a439af32 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierImpl.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierImpl.java @@ -19,17 +19,17 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; + +import org.matsim.api.core.v01.Id; +import org.matsim.utils.objectattributes.attributable.Attributes; +import org.matsim.utils.objectattributes.attributable.AttributesImpl; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.matsim.api.core.v01.Id; -import org.matsim.utils.objectattributes.attributable.Attributes; -import org.matsim.utils.objectattributes.attributable.AttributesImpl; - /** * This is a carrier that has capabilities and resources, jobs and plans to fulfill its obligations. *

@@ -40,7 +40,7 @@ public final class CarrierImpl implements Carrier { @Deprecated // refactoring device, please inline public static Carrier newInstance( Id carrierId ){ - return CarrierUtils.createCarrier( carrierId ) ; + return CarriersUtils.createCarrier( carrierId ) ; } private final Id id; @@ -116,7 +116,7 @@ public boolean addPlan(CarrierPlan p) { @Override public CarrierPlan createCopyOfSelectedPlanAndMakeSelected() { - CarrierPlan newPlan = CarrierUtils.copyPlan(this.selectedPlan ) ; + CarrierPlan newPlan = CarriersUtils.copyPlan(this.selectedPlan ) ; this.setSelectedPlan( newPlan ) ; return newPlan ; } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlan.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlan.java similarity index 94% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlan.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlan.java index b63e0556eb8..9c51aac159e 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlan.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlan.java @@ -19,15 +19,15 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; -import java.util.Collection; import org.matsim.api.core.v01.population.BasicPlan; -import org.matsim.contrib.freight.controler.FreightUtils; import org.matsim.utils.objectattributes.attributable.Attributable; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesImpl; +import java.util.Collection; + /** * * A specific plan of a carrier, and its score. @@ -83,7 +83,7 @@ public void setScore(Double score) { * @return score from jsprit. */ public Double getJspritScore(){ - return FreightUtils.getJspritScore(this); + return CarriersUtils.getJspritScore(this); } /** @@ -91,7 +91,7 @@ public Double getJspritScore(){ * This is _not_ the score from the MATSim simulation. */ public void setJspritScore(Double score){ - FreightUtils.setJspritScore(this, score); + CarriersUtils.setJspritScore(this, score); } public Collection getScheduledTours() { diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanReaderV1.java similarity index 96% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanReaderV1.java index ea924762842..4e13ad599b6 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanReaderV1.java @@ -19,14 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Stack; +package org.matsim.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -41,6 +34,8 @@ import org.matsim.vehicles.VehicleType; import org.xml.sax.Attributes; +import java.util.*; + /** * A reader that reads carriers and their plans. * @@ -101,7 +96,7 @@ public void startTag(String name, Attributes attributes, Stack context) switch( name ){ case CARRIER:{ String id = attributes.getValue( ID ); - currentCarrier = CarrierUtils.createCarrier( Id.create( id, Carrier.class ) ); + currentCarrier = CarriersUtils.createCarrier( Id.create( id, Carrier.class ) ); break; } case SHIPMENTS:{ @@ -137,7 +132,7 @@ public void startTag(String name, Attributes attributes, Stack context) if( deliveryServiceTime != null ) shipmentBuilder.setDeliveryServiceTime( getDouble( deliveryServiceTime ) ); CarrierShipment shipment = shipmentBuilder.build(); currentShipments.put( attributes.getValue( ID ), shipment ); - CarrierUtils.addShipment(currentCarrier, shipment); + CarriersUtils.addShipment(currentCarrier, shipment); // currentCarrier.getShipments().put( shipment.getId(), shipment ); break ; } @@ -168,7 +163,7 @@ public void startTag(String name, Attributes attributes, Stack context) if( startTime != null ) vehicleBuilder.setEarliestStart( getDouble( startTime ) ); if( endTime != null ) vehicleBuilder.setLatestEnd( getDouble( endTime ) ); CarrierVehicle vehicle = vehicleBuilder.build(); - CarrierUtils.addCarrierVehicle(currentCarrier, vehicle); + CarriersUtils.addCarrierVehicle(currentCarrier, vehicle); vehicles.put( vId, vehicle ); break; } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanWriter.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanWriter.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanWriter.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanWriter.java index 4a20ad55610..3d7922d9489 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanWriter.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanWriter.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import com.google.inject.Inject; import org.matsim.utils.objectattributes.AttributeConverter; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlParserV2.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java similarity index 96% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlParserV2.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java index 42b4ca52eac..fb921395d19 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlParserV2.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java @@ -19,33 +19,30 @@ * */ -package org.matsim.contrib.freight.carrier; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Stack; +package org.matsim.freight.carriers; import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.Builder; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; import org.matsim.core.gbl.Gbl; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.utils.io.MatsimXmlParser; import org.matsim.core.utils.misc.Time; +import org.matsim.freight.carriers.CarrierCapabilities.Builder; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.utils.objectattributes.AttributeConverter; import org.matsim.utils.objectattributes.attributable.AttributesXmlReaderDelegate; -import org.matsim.vehicles.*; +import org.matsim.vehicles.Vehicle; +import org.matsim.vehicles.VehicleType; import org.xml.sax.Attributes; -import static org.matsim.contrib.freight.carrier.CarrierConstants.*; + +import java.util.*; + +import static org.matsim.freight.carriers.CarrierConstants.*; class CarrierPlanXmlParserV2 extends MatsimXmlParser { @@ -104,7 +101,7 @@ public void startTag(String name, Attributes atts, Stack context) { case CARRIER: { String id = atts.getValue(ID); if (id == null) throw new IllegalStateException("carrierId is missing."); - currentCarrier = CarrierUtils.createCarrier(Id.create(id, Carrier.class)); + currentCarrier = CarriersUtils.createCarrier(Id.create(id, Carrier.class)); break; } @@ -132,7 +129,7 @@ public void startTag(String name, Attributes atts, Stack context) { if (serviceTimeString != null) serviceBuilder.setServiceDuration(parseTimeToDouble(serviceTimeString)); currentService = serviceBuilder.build(); serviceMap.put(currentService.getId(), currentService); - CarrierUtils.addService(currentCarrier, currentService); + CarriersUtils.addService(currentCarrier, currentService); break; } @@ -171,7 +168,7 @@ public void startTag(String name, Attributes atts, Stack context) { currentShipment = shipmentBuilder.build(); currentShipments.put(atts.getValue(ID), currentShipment); - CarrierUtils.addShipment(currentCarrier, currentShipment); + CarriersUtils.addShipment(currentCarrier, currentShipment); break; } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlParserV2_1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java similarity index 97% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlParserV2_1.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java index ac34b2fef83..862123d3201 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlParserV2_1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java @@ -19,21 +19,21 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.Builder; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; import org.matsim.core.gbl.Gbl; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.utils.io.MatsimXmlParser; import org.matsim.core.utils.misc.Time; +import org.matsim.freight.carriers.CarrierCapabilities.Builder; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.utils.objectattributes.AttributeConverter; import org.matsim.utils.objectattributes.attributable.AttributesXmlReaderDelegate; import org.matsim.vehicles.Vehicle; @@ -42,7 +42,7 @@ import java.util.*; -import static org.matsim.contrib.freight.carrier.CarrierConstants.*; +import static org.matsim.freight.carriers.CarrierConstants.*; class CarrierPlanXmlParserV2_1 extends MatsimXmlParser { @@ -100,7 +100,7 @@ public void startTag(String name, Attributes atts, Stack context) { case CARRIER: { String id = atts.getValue(ID); if (id == null) throw new IllegalStateException("carrierId is missing."); - currentCarrier = CarrierUtils.createCarrier(Id.create(id, Carrier.class)); + currentCarrier = CarriersUtils.createCarrier(Id.create(id, Carrier.class)); break; } //services @@ -127,7 +127,7 @@ public void startTag(String name, Attributes atts, Stack context) { if (serviceTimeString != null) serviceBuilder.setServiceDuration(parseTimeToDouble(serviceTimeString)); currentService = serviceBuilder.build(); serviceMap.put(currentService.getId(), currentService); - CarrierUtils.addService(currentCarrier, currentService); + CarriersUtils.addService(currentCarrier, currentService); break; } @@ -166,7 +166,7 @@ public void startTag(String name, Attributes atts, Stack context) { currentShipment = shipmentBuilder.build(); currentShipments.put(atts.getValue(ID), currentShipment); - CarrierUtils.addShipment(currentCarrier, currentShipment); + CarriersUtils.addShipment(currentCarrier, currentShipment); break; } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlReader.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java similarity index 99% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlReader.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java index 9a97bf55522..5019604572d 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlReader.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV1.java similarity index 95% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV1.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV1.java index edfb26cefeb..510ea9b1ac3 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV1.java @@ -19,27 +19,23 @@ * */ -package org.matsim.contrib.freight.carrier; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; +package org.matsim.freight.carriers; import com.graphhopper.jsprit.core.problem.job.Shipment; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.freight.carrier.Tour.Leg; -import org.matsim.contrib.freight.carrier.Tour.ShipmentBasedActivity; -import org.matsim.contrib.freight.carrier.Tour.TourElement; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.utils.io.MatsimXmlWriter; import org.matsim.core.utils.misc.Time; +import java.io.BufferedWriter; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + /** * A writer that writes carriers and their plans in a xml-file. * @@ -181,8 +177,8 @@ private void writePlans(Carrier carrier, BufferedWriter writer) writer.write("\t\t\t\t\t\n"); - for (TourElement tourElement : tour.getTour().getTourElements()) { - if (tourElement instanceof Leg leg) { + for (Tour.TourElement tourElement : tour.getTour().getTourElements()) { + if (tourElement instanceof Tour.Leg leg) { writer.write("\t\t\t\t\t\n"); } } - if (tourElement instanceof ShipmentBasedActivity act) { + if (tourElement instanceof Tour.ShipmentBasedActivity act) { writer.write("\t\t\t\t\t id, Id locationLinkId){ return new Builder(id,locationLinkId); } - + private final Id id; private final Id locationLinkId; private String name = "service"; - + private double serviceTime = 0.0; private TimeWindow timeWindow = TimeWindow.newInstance(0.0, Integer.MAX_VALUE); private int capacityDemand = 0; - + private Builder(Id id, Id locationLinkId) { super(); this.id = id; this.locationLinkId = locationLinkId; } - + public Builder setName(String name){ this.name = name; return this; } - + /** * By default it is [0.0,Integer.MaxValue]. - * + * * @param serviceDuration * @return */ @@ -65,13 +65,13 @@ public Builder setServiceDuration(double serviceDuration){ this.serviceTime = serviceDuration; return this; } - + /** * Sets a time-window for the service. - * + * *

Note that the time-window restricts the start-time of the service (i.e. serviceActivity). If one works with hard time-windows (which means that * time-windows must be met) than the service is allowed to start between startTimeWindow.getStart() and startTimeWindow.getEnd(). - * + * * @param startTimeWindow * @return */ @@ -79,7 +79,7 @@ public Builder setServiceStartTimeWindow(TimeWindow startTimeWindow){ this.timeWindow = startTimeWindow; return this; } - + public CarrierService build(){ return new CarrierService(this); } @@ -88,16 +88,16 @@ public Builder setCapacityDemand(int value) { this.capacityDemand = value; return this; } - + } - - + + private final Id id; private final Id locationId; - + private final String name; - + private final double serviceDuration; private final TimeWindow timeWindow; @@ -130,7 +130,7 @@ public double getServiceDuration() { public TimeWindow getServiceStartTimeWindow(){ return timeWindow; } - + public int getCapacityDemand() { return demand; } @@ -180,6 +180,6 @@ public boolean equals(Object obj) { } else return id.equals(other.id); } - - + + } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierShipment.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java similarity index 99% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierShipment.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java index 07bee15376d..1298f3eb5b2 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierShipment.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicle.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicle.java similarity index 99% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicle.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicle.java index 314c3e56a2f..917052a65fe 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicle.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicle.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleType.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java similarity index 97% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleType.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java index 89cae4f6f63..8f5a5ea31e7 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleType.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.matsim.api.core.v01.Id; import org.matsim.vehicles.VehicleType; @@ -36,7 +36,7 @@ */ public class CarrierVehicleType { // this is now really only a name space for the builder method. There are two options where this could go: - // (1) into CarrierUtils; then it could keep its freight specific syntax + // (1) into CarriersUtils; then it could keep its freight specific syntax // (2) into VehicleUtils; then it would need to lose its freight specific syntax // However, note that when moving it, the class here still needs to be available since otherwise a lot of outside code will break. // kai, sep'19 diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoader.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeLoader.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoader.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeLoader.java index d71e1562ed7..c9fbe45d4ad 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoader.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeLoader.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReader.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java similarity index 99% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReader.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java index c8f55f0344e..ce87229d7ee 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReader.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderV1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderV1.java similarity index 99% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderV1.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderV1.java index fcc30581b16..61718d49850 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderV1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderV1.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriter.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeWriter.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriter.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeWriter.java index ec8a6a86a88..4fbd8d68bbb 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriter.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeWriter.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.matsim.api.core.v01.Id; import org.matsim.core.api.internal.MatsimWriter; @@ -32,7 +32,7 @@ /** * A writer that writes carriers and their plans in a xml-file. - * + * * @author sschroeder * */ diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriterV1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeWriterV1.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriterV1.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeWriterV1.java index f65029abd09..823123e916a 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriterV1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeWriterV1.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypes.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypes.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypes.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypes.java index a2e8399cfaa..e9900cdc6cb 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypes.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypes.java @@ -19,14 +19,14 @@ * */ -package org.matsim.contrib.freight.carrier; - -import java.util.HashMap; -import java.util.Map; +package org.matsim.freight.carriers; import org.matsim.api.core.v01.Id; import org.matsim.vehicles.VehicleType; +import java.util.HashMap; +import java.util.Map; + /** * VehicleTypeContainer mapping all vehicleTypes. * diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/Carriers.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/Carriers.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java index ca801c90f90..8746def11e9 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/Carriers.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java @@ -19,17 +19,16 @@ * */ -package org.matsim.contrib.freight.carrier; - -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.Map; +package org.matsim.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; - import org.matsim.api.core.v01.Id; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + /** * A container that maps carriers. * diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/FreightUtils.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java similarity index 73% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/FreightUtils.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java index c56598c5968..4eb7bc7fabf 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/FreightUtils.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java @@ -1,22 +1,25 @@ -/* *********************************************************************** * - * 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.freight.controler; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; import com.graphhopper.jsprit.analysis.toolbox.StopWatch; import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; @@ -28,17 +31,14 @@ 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.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Plan; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.Tour.ServiceActivity; -import org.matsim.contrib.freight.carrier.Tour.TourElement; -import org.matsim.contrib.freight.jsprit.MatsimJspritFactory; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts; -import org.matsim.contrib.freight.jsprit.NetworkRouter; import org.matsim.core.config.ConfigUtils; import org.matsim.core.utils.io.IOUtils; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.freight.carriers.jsprit.NetworkRouter; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; @@ -49,26 +49,125 @@ import java.util.concurrent.ForkJoinPool; import java.util.stream.Collectors; -/** - * Utils for the work with the freight contrib - * - * @author kturner - * - */ -public class FreightUtils { +public class CarriersUtils { static final String CARRIER_VEHICLE = "carrierVehicle"; + @SuppressWarnings("unused") + private static final Logger log = LogManager.getLogger(CarriersUtils.class); /** - * From the outside, rather use {@link FreightUtils#getCarriers(Scenario)} . + * From the outside, rather use {@link CarriersUtils#getCarriers(Scenario)} . * This string constant will eventually become private. */ private static final String CARRIERS = "carriers"; private static final String CARRIER_VEHICLE_TYPES = "carrierVehicleTypes"; - private static final Logger log = LogManager.getLogger(FreightUtils.class); private static final String ATTR_SKILLS = "skills"; private static final String ATTR_JSPRIT_SCORE = "jspritScore"; + public static Carrier createCarrier( Id id ){ + return new CarrierImpl(id); + } + + /** + * Adds an carrierVehicle to the CarrierCapabilities of the Carrier. + * @param carrier + * @param carrierVehicle + */ + public static void addCarrierVehicle(Carrier carrier, CarrierVehicle carrierVehicle){ + carrier.getCarrierCapabilities().getCarrierVehicles().put(carrierVehicle.getId(), carrierVehicle); + } + + public static CarrierVehicle getCarrierVehicle(Carrier carrier, Id vehicleId){ + CarrierVehicle veh = carrier.getCarrierCapabilities().getCarrierVehicles().get(vehicleId); + if(veh != null){ + return veh; + } + log.error("Vehicle with Id does not exists", new IllegalStateException("vehicle with id " + vehicleId + " is missing in Carrier: " + carrier.getId())); + return null; + } + + /** + * Adds an {@link CarrierService} to the {@link Carrier}. + * @param carrier + * @param carrierService + */ + public static void addService(Carrier carrier, CarrierService carrierService){ + carrier.getServices().put(carrierService.getId(), carrierService); + } + + public static CarrierService getService(Carrier carrier, Id serviceId){ + CarrierService service = carrier.getServices().get(serviceId); + if(service != null){ + return service; + } + log.error("Service with Id does not exists", new IllegalStateException("Service with id " + serviceId + " is missing in Carrier: " + carrier.getId())); + return null; + } + + /** + * Adds an {@link CarrierShipment} to the {@link Carrier}. + * @param carrier + * @param carrierShipment + */ + public static void addShipment(Carrier carrier, CarrierShipment carrierShipment){ + carrier.getShipments().put(carrierShipment.getId(), carrierShipment); + } + + public static CarrierShipment getShipment(Carrier carrier, Id serviceId){ + CarrierShipment shipment = carrier.getShipments().get(serviceId); + if(shipment != null){ + return shipment; + } + log.error("Shipment with Id does not exists", new IllegalStateException("Shipment with id " + serviceId + " is missing in Carrier: " + carrier.getId())); + return null; + } + + + + public static CarrierPlan copyPlan( CarrierPlan plan2copy ) { + List tours = new ArrayList<>(); + for (ScheduledTour sTour : plan2copy.getScheduledTours()) { + double depTime = sTour.getDeparture(); + CarrierVehicle vehicle = sTour.getVehicle(); + Tour tour = sTour.getTour().duplicate(); + tours.add(ScheduledTour.newInstance(tour, vehicle, depTime)); + } + CarrierPlan copiedPlan = new CarrierPlan(plan2copy.getCarrier(), tours); + double initialScoreOfCopiedPlan = plan2copy.getScore(); + copiedPlan.setScore(initialScoreOfCopiedPlan); + return copiedPlan; + + } + + private static final String CARRIER_MODE = "carrierMode" ; + public static String getCarrierMode( Carrier carrier ) { + String result = (String) carrier.getAttributes().getAttribute( CARRIER_MODE ); + if ( result == null ){ + return TransportMode.car ; + } else { + return result ; + } + } + public static void setCarrierMode( Carrier carrier, String carrierMode ) { + carrier.getAttributes().putAttribute( CARRIER_MODE, carrierMode ) ; + } + + private static final String JSPRIT_ITERATIONS="jspritIterations" ; + public static int getJspritIterations( Carrier carrier ) { + Integer result = (Integer) carrier.getAttributes().getAttribute( JSPRIT_ITERATIONS ); + if (result == null){ + log.error("Requested attribute jspritIterations does not exists. Will return " + Integer.MIN_VALUE); + return Integer.MIN_VALUE; + } else { + return result ; + } + } + + public static void setJspritIterations( Carrier carrier, int jspritIterations ) { + carrier.getAttributes().putAttribute( JSPRIT_ITERATIONS , jspritIterations ) ; + } + + /** * Runs jsprit and so solves the VehicleRoutingProblem (VRP) for all {@link Carriers}, doing the following steps: * - creating NetbasedCosts based on the network @@ -80,12 +179,12 @@ public class FreightUtils { * @throws ExecutionException, InterruptedException */ public static void runJsprit(Scenario scenario) throws ExecutionException, InterruptedException{ - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule( scenario.getConfig(), FreightConfigGroup.class ); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule( scenario.getConfig(), FreightCarriersConfigGroup.class ); final NetworkBasedTransportCosts netBasedCosts = NetworkBasedTransportCosts.Builder.newInstance( - scenario.getNetwork(), FreightUtils.getCarrierVehicleTypes(scenario).getVehicleTypes().values() ).build() ; + scenario.getNetwork(), getCarrierVehicleTypes(scenario).getVehicleTypes().values() ).build() ; - Carriers carriers = FreightUtils.getCarriers(scenario); + Carriers carriers = getCarriers(scenario); HashMap, Integer> carrierActivityCounterMap = new HashMap<>(); @@ -109,10 +208,10 @@ public static void runJsprit(Scenario scenario) throws ExecutionException, Inter log.info("Start tour planning for " + carrier.getId() + " which has " + serviceCount + " services"); VehicleRoutingProblem problem = MatsimJspritFactory.createRoutingProblemBuilder(carrier, scenario.getNetwork()).setRoutingCost(netBasedCosts).build(); - VehicleRoutingAlgorithm algorithm = MatsimJspritFactory.loadOrCreateVehicleRoutingAlgorithm(scenario, freightConfigGroup, netBasedCosts, problem); + VehicleRoutingAlgorithm algorithm = MatsimJspritFactory.loadOrCreateVehicleRoutingAlgorithm(scenario, freightCarriersConfigGroup, netBasedCosts, problem); algorithm.getAlgorithmListeners().addListener(new StopWatch(), VehicleRoutingAlgorithmListeners.Priority.HIGH); - int jspritIterations = CarrierUtils.getJspritIterations(carrier); + int jspritIterations = getJspritIterations(carrier); try { if (jspritIterations > 0) { algorithm.setMaxIterations(jspritIterations); @@ -159,7 +258,7 @@ public static void runJsprit(Scenario scenario) throws ExecutionException, Inter public static Carriers createShipmentVRPCarrierFromServiceVRPSolution(Carriers carriers) { Carriers carriersWithShipments = new Carriers(); for (Carrier carrier : carriers.getCarriers().values()) { - Carrier carrierWS = CarrierUtils.createCarrier(carrier.getId()); + Carrier carrierWS = createCarrier(carrier.getId()); if (carrier.getShipments().size() > 0) { copyShipments(carrierWS, carrier); } @@ -180,7 +279,7 @@ public static Carriers getOrCreateCarriers(Scenario scenario){ return addOrGetCarriers( scenario ); } - public static Carriers addOrGetCarriers( Scenario scenario ) { + public static Carriers addOrGetCarriers(Scenario scenario ) { // I have separated getOrCreateCarriers and getCarriers, since when the // controler is started, it is better to fail if the carriers are not found. // kai, oct'19 @@ -197,7 +296,7 @@ public static Carriers getCarriers(Scenario scenario) { // not found. kai, oct'19 if ( scenario.getScenarioElement( CARRIERS ) == null ) { throw new RuntimeException( "cannot retrieve carriers from scenario; typical ways to resolve that problem are to call " + - "FreightUtils.getOrCreateCarriers(...) or FreightUtils.loadCarriersAccordingToFreightConfig(...) early enough\n") ; + "CarrierControlerUtils.getOrCreateCarriers(...) or CarrierControlerUtils.loadCarriersAccordingToFreightConfig(...) early enough\n") ; } return (Carriers) scenario.getScenarioElement(CARRIERS); } @@ -217,18 +316,17 @@ public static CarrierVehicleTypes getCarrierVehicleTypes(Scenario scenario) { * @param scenario */ public static void loadCarriersAccordingToFreightConfig(Scenario scenario) { - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(scenario.getConfig(), FreightConfigGroup.class); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(scenario.getConfig(), FreightCarriersConfigGroup.class); CarrierVehicleTypes vehTypes = getCarrierVehicleTypes(scenario); - new CarrierVehicleTypeReader( vehTypes ).readURL( IOUtils.extendUrl(scenario.getConfig().getContext(), freightConfigGroup.getCarriersVehicleTypesFile()) ); + new CarrierVehicleTypeReader( vehTypes ).readURL( IOUtils.extendUrl(scenario.getConfig().getContext(), freightCarriersConfigGroup.getCarriersVehicleTypesFile()) ); Carriers carriers = addOrGetCarriers( scenario ); // also registers with scenario - new CarrierPlanXmlReader( carriers, vehTypes ).readURL( IOUtils.extendUrl(scenario.getConfig().getContext(), freightConfigGroup.getCarriersFile() ) ); + new CarrierPlanXmlReader( carriers, vehTypes ).readURL( IOUtils.extendUrl(scenario.getConfig().getContext(), freightCarriersConfigGroup.getCarriersFile() ) ); // new CarrierVehicleTypeLoader( carriers ).loadVehicleTypes( vehTypes ); } - /** * Copy all shipments from the existing carrier to the new carrier with * shipments. @@ -239,7 +337,7 @@ public static void loadCarriersAccordingToFreightConfig(Scenario scenario) { private static void copyShipments(Carrier carrierWS, Carrier carrier) { for (CarrierShipment carrierShipment : carrier.getShipments().values()) { log.debug("Copy CarrierShipment: " + carrierShipment.toString()); - CarrierUtils.addShipment(carrierWS, carrierShipment); + addShipment(carrierWS, carrierShipment); } } @@ -266,8 +364,8 @@ private static void createShipmentsFromServices(Carrier carrierWS, Carrier carri } for (ScheduledTour tour : tours) { Id depotForTour = tour.getVehicle().getLinkId(); - for (TourElement te : tour.getTour().getTourElements()) { - if (te instanceof ServiceActivity act) { + for (Tour.TourElement te : tour.getTour().getTourElements()) { + if (te instanceof Tour.ServiceActivity act) { depotServiceIsDeliveredFrom.put(act.getService().getId(), depotForTour); } } @@ -285,7 +383,7 @@ private static void createShipmentsFromServices(Carrier carrierWS, Carrier carri // Limited to end of delivery timeWindow (pickup later than the latest delivery is not useful). .setPickupTimeWindow(TimeWindow.newInstance(0.0, carrierService.getServiceStartTimeWindow().getEnd())) .build(); - CarrierUtils.addShipment(carrierWS, carrierShipment); + addShipment(carrierWS, carrierShipment); } } @@ -381,7 +479,6 @@ public static List getSkills(CarrierShipment shipment) { return Collections.unmodifiableList(convertSkillsAttributeToList(shipment.getAttributes())); } - /** * Adds a skill to the {@link CarrierService}. * @@ -428,8 +525,6 @@ public static List getSkills(CarrierService service) { return Collections.unmodifiableList(convertSkillsAttributeToList(service.getAttributes())); } - - /** * A general method to add a skill to any {@link Attributes} object. * @@ -493,10 +588,12 @@ private static void setSkills(Attributes attributes, Set skills) { attributes.putAttribute(ATTR_SKILLS, skillString.toString()); } } - public static Vehicle getVehicle( Plan plan ) { + + public static Vehicle getVehicle(Plan plan ) { return (Vehicle) plan.getAttributes().getAttribute( CARRIER_VEHICLE ); } - public static void putVehicle( Plan plan, Vehicle vehicle ){ + + public static void putVehicle(Plan plan, Vehicle vehicle ){ plan.getAttributes().putAttribute( CARRIER_VEHICLE, vehicle ); } @@ -508,11 +605,8 @@ public static Double getJspritScore (CarrierPlan plan) { return (Double) plan.getAttributes().getAttribute(ATTR_JSPRIT_SCORE); } - public static void writeCarriers( Carriers carriers, String filename ) { + public static void writeCarriers(Carriers carriers, String filename ) { new CarrierPlanWriter( carriers ).write( filename ); } - public static CarrierStrategyManager createDefaultCarrierStrategyManager() { - return new CarrierStrategyManagerImpl(); - } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/FreightConfigGroup.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/FreightCarriersConfigGroup.java similarity index 83% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/FreightConfigGroup.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/FreightCarriersConfigGroup.java index a8bc1db3e98..1aed1a936f2 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/FreightConfigGroup.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/FreightCarriersConfigGroup.java @@ -1,33 +1,36 @@ -/* *********************************************************************** * - * project: org.matsim.* - * *********************************************************************** * - * * - * copyright : (C) 2007 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.freight; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; +import jakarta.validation.constraints.Positive; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ReflectiveConfigGroup; -import jakarta.validation.constraints.Positive; import java.net.URL; import java.util.Map; -public class FreightConfigGroup extends ReflectiveConfigGroup { +public class FreightCarriersConfigGroup extends ReflectiveConfigGroup { - public static final String GROUPNAME="freight" ; + public static final String GROUPNAME="freightCarriers" ; private String carriersFile; static final String CARRIERS_FILE = "carriersFile"; @@ -55,7 +58,7 @@ public enum UseDistanceConstraintForTourPlanning {noDistanceConstraint, basedOnE private UseDistanceConstraintForTourPlanning useDistanceConstraintForTourPlanning = UseDistanceConstraintForTourPlanning.noDistanceConstraint; private static final String USE_DISTANCE_CONSTRAINT_DESC = "Use distance constraint within the tour planning phase. This does NOT ensure that the tours in MATSim will respect this limitation"; - public FreightConfigGroup() { + public FreightCarriersConfigGroup() { super(GROUPNAME); } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/ScheduledTour.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/ScheduledTour.java similarity index 97% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/ScheduledTour.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/ScheduledTour.java index f8769b4070f..6a133ebc71c 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/ScheduledTour.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/ScheduledTour.java @@ -19,24 +19,24 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; /** * A concrete assignment of a tour, a vehicle and a departure time. - * + * * @author sschroeder, mzilske * */ public class ScheduledTour { - + /** * Returns a new instance of ScheduledTour. - * - *

Look at the builder. It might be easier to build a scheduled tour. + * + *

Look at the builder. It might be easier to build a scheduled tour. * You get the builder this way: ScheduledTour.Builder.newInstance(carrierVehicle). - * + * * @param tour * @param vehicle * @param departureTime @@ -46,7 +46,7 @@ public class ScheduledTour { public static ScheduledTour newInstance(Tour tour, CarrierVehicle vehicle, double departureTime){ return new ScheduledTour(tour,vehicle,departureTime); } - + private final Tour tour; private final CarrierVehicle vehicle; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/TimeWindow.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/TimeWindow.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java index c198aa2ed79..167dc424028 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/TimeWindow.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.matsim.core.utils.misc.Time; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/Tour.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java similarity index 99% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/Tour.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java index b1cadaef2cc..9b0e9d91696 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/Tour.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java similarity index 90% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierAgent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java index cfe0cea13dc..d3e08e9afbb 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java @@ -19,36 +19,27 @@ * */ -package org.matsim.contrib.freight.controler; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +package org.matsim.freight.carriers.controler; 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.Identifiable; -import org.matsim.api.core.v01.events.*; -import org.matsim.api.core.v01.population.Activity; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Person; -import org.matsim.api.core.v01.population.Plan; -import org.matsim.api.core.v01.population.Route; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.Tour.TourActivity; -import org.matsim.contrib.freight.carrier.Tour.TourElement; -import org.matsim.contrib.freight.events.CarrierEventCreator; +import org.matsim.api.core.v01.events.Event; +import org.matsim.api.core.v01.population.*; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.gbl.Gbl; import org.matsim.core.population.PopulationUtils; import org.matsim.core.scoring.ScoringFunction; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.Tour.TourActivity; +import org.matsim.freight.carriers.Tour.TourElement; +import org.matsim.freight.carriers.events.CarrierEventCreator; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleUtils; +import java.util.*; + /** * This keeps track of the carrier during simulation. * @@ -123,7 +114,7 @@ List createFreightDriverPlans() { // to "prepareForSim" for carriers. Did not check any further. kai, jul'22 //this returns TransportMode.car if the attribute is null - Leg leg = PopulationUtils.createLeg(CarrierUtils.getCarrierMode(carrier)); + Leg leg = PopulationUtils.createLeg(CarriersUtils.getCarrierMode(carrier)); //TODO we might need to set the route to null if the mode is a drt mode leg.setRoute(route); @@ -145,7 +136,7 @@ List createFreightDriverPlans() { plan.addActivity(endActivity); driverPerson.addPlan(plan); plan.setPerson(driverPerson); - FreightUtils.putVehicle( plan, vehicle ); + CarriersUtils.putVehicle( plan, vehicle ); routes.add(plan); carrierDriverAgents.put(driverId, carrierDriverAgent); } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierAgentTracker.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgentTracker.java similarity index 95% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierAgentTracker.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgentTracker.java index b93698f9034..09c4036d92f 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierAgentTracker.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgentTracker.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.controler; +package org.matsim.freight.carriers.controler; import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; @@ -27,13 +27,13 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.*; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.events.CarrierEventCreator; -import org.matsim.contrib.freight.events.CarrierEventCreatorUtils; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.events.algorithms.Vehicle2DriverEventHandler; import org.matsim.core.events.handler.BasicEventHandler; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.events.CarrierEventCreator; +import org.matsim.freight.carriers.events.CarrierEventCreatorUtils; import java.util.*; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierControlerListener.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierControlerListener.java similarity index 62% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierControlerListener.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierControlerListener.java index afbc91c7c8a..f8a103bcbe5 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierControlerListener.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierControlerListener.java @@ -1,28 +1,27 @@ /* - * *********************************************************************** * -// * * project: org.matsim.* - * * ${file_name} - * * * - * * *********************************************************************** * - * * * - * * copyright : (C) ${year} by the members listed in the COPYING, * - * * LICENSE and WARRANTY file. * - * * email : info at matsim dot org * - * * * - * * *********************************************************************** * - * * * - * * This program is free software; you can redistribute it and/or modify * - * * it under the terms of the GNU General Public License as published by * - * * the Free Software Foundation; either version 2 of the License, or * - * * (at your option) any later version. * - * * See also COPYING, LICENSE and WARRANTY file * - * * * - * * *********************************************************************** + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.controler; +package org.matsim.freight.carriers.controler; +import jakarta.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; @@ -30,9 +29,9 @@ import org.matsim.core.controler.events.ScoringEvent; import org.matsim.core.controler.listener.ReplanningListener; import org.matsim.core.controler.listener.ScoringListener; +import org.matsim.freight.carriers.CarriersUtils; import javax.annotation.Nullable; -import jakarta.inject.Inject; /** * Controls the workflow of the simulation. @@ -79,7 +78,7 @@ public class CarrierControlerListener implements ScoringListener, ReplanningList if ( strategyManager==null ) { throw new RuntimeException( "You need to set CarrierStrategyManager to something meaningful to run iterations." ); } - strategyManager.run( FreightUtils.getCarriers( scenario ).getCarriers().values() , event.getIteration(), event.getReplanningContext() ); + strategyManager.run( CarriersUtils.getCarriers( scenario ).getCarriers().values() , event.getIteration(), event.getReplanningContext() ); } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierControlerUtils.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierControlerUtils.java new file mode 100644 index 00000000000..fe19207bfcc --- /dev/null +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierControlerUtils.java @@ -0,0 +1,35 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.controler; + +/** + * Utils class for (package-private) content of freight.carriers.controler - package; + * + * @author kturner + * + */ +public class CarrierControlerUtils { + + public static CarrierStrategyManager createDefaultCarrierStrategyManager() { + return new CarrierStrategyManagerImpl(); + } +} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierDriverAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java similarity index 87% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierDriverAgent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java index 2a39409b5f9..5a0889c8dc2 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierDriverAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java @@ -1,4 +1,25 @@ -package org.matsim.contrib.freight.controler; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.controler; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -11,13 +32,13 @@ import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Route; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.events.CarrierEventCreator; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.scoring.ScoringFunction; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.events.CarrierEventCreator; import org.matsim.vehicles.Vehicle; import java.util.ArrayList; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierModule.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierModule.java similarity index 73% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierModule.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierModule.java index 325e82b5fe6..e2b9e1d8354 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierModule.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierModule.java @@ -1,26 +1,25 @@ /* - * *********************************************************************** * - * * project: org.matsim.* - * * CarrierModule.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 * - * * * - * * *********************************************************************** + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.controler; +package org.matsim.freight.carriers.controler; import com.google.inject.Inject; import com.google.inject.Provider; @@ -29,8 +28,6 @@ import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.*; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.AbstractModule; @@ -39,6 +36,7 @@ import org.matsim.core.mobsim.qsim.AbstractQSimModule; import org.matsim.core.mobsim.qsim.components.QSimComponentsConfigGroup; import org.matsim.core.scoring.ScoringFunction; +import org.matsim.freight.carriers.*; import java.util.List; @@ -46,7 +44,7 @@ public final class CarrierModule extends AbstractModule { @Override public void install() { - FreightConfigGroup freightConfig = ConfigUtils.addOrGetModule( getConfig(), FreightConfigGroup.class ) ; + FreightCarriersConfigGroup freightConfig = ConfigUtils.addOrGetModule( getConfig(), FreightCarriersConfigGroup.class ) ; bind(Carriers.class).toProvider( new CarrierProvider() ).asEagerSingleton(); // needs to be eager since it is still scenario construction. kai, oct'19 // this is probably ok @@ -99,7 +97,7 @@ public final class CarrierModule extends AbstractModule { bind( CarrierStrategyManager.class ).toProvider( () -> null ); // (the null binding means that a zeroth iteration will run. kai, jul'22) - this.addControlerListenerBinding().toInstance((ShutdownListener) event -> writeAdditionalRunOutput( event.getServices().getControlerIO(), event.getServices().getConfig(), FreightUtils.getCarriers( event.getServices().getScenario() ) )); + this.addControlerListenerBinding().toInstance((ShutdownListener) event -> writeAdditionalRunOutput( event.getServices().getControlerIO(), event.getServices().getConfig(), CarriersUtils.getCarriers( event.getServices().getScenario() ) )); } @@ -138,7 +136,7 @@ private static class CarrierScoringFunctionFactoryDummyImpl implements CarrierSc private static void writeAdditionalRunOutput( OutputDirectoryHierarchy controllerIO, Config config, Carriers carriers ) { // ### some final output: ### - String compression = config.controler().getCompressionType().fileEnding; + String compression = config.controller().getCompressionType().fileEnding; new CarrierPlanWriter(carriers).write( controllerIO.getOutputFilename("output_carriers.xml" + compression)); new CarrierVehicleTypeWriter(CarrierVehicleTypes.getVehicleTypes(carriers)).write(controllerIO.getOutputFilename("output_carriersVehicleTypes.xml" + compression)); } @@ -147,7 +145,7 @@ private static void writeAdditionalRunOutput( OutputDirectoryHierarchy controlle private static class CarrierProvider implements Provider { @Inject Scenario scenario; @Override public Carriers get() { - return FreightUtils.getCarriers(scenario); + return CarriersUtils.getCarriers(scenario); } } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierReRouteVehicles.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierReRouteVehicles.java similarity index 68% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierReRouteVehicles.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierReRouteVehicles.java index 27d1153f804..f59ba81c930 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierReRouteVehicles.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierReRouteVehicles.java @@ -1,34 +1,36 @@ -/* *********************************************************************** * - * 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 * - * * - * *********************************************************************** */ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.controler; +package org.matsim.freight.carriers.controler; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.CarrierPlan; -import org.matsim.contrib.freight.carrier.ScheduledTour; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.replanning.ReplanningContext; import org.matsim.core.replanning.modules.GenericPlanStrategyModule; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.TravelTime; +import org.matsim.freight.carriers.CarrierPlan; +import org.matsim.freight.carriers.ScheduledTour; /** * Strategy module to reRoute a carrierPlan. diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierScoringFunctionFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierScoringFunctionFactory.java similarity index 93% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierScoringFunctionFactory.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierScoringFunctionFactory.java index d412280b6cd..c73a41b3008 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierScoringFunctionFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierScoringFunctionFactory.java @@ -19,10 +19,10 @@ * */ -package org.matsim.contrib.freight.controler; +package org.matsim.freight.carriers.controler; -import org.matsim.contrib.freight.carrier.Carrier; import org.matsim.core.scoring.ScoringFunction; +import org.matsim.freight.carriers.Carrier; public interface CarrierScoringFunctionFactory { diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierStrategyManager.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierStrategyManager.java similarity index 93% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierStrategyManager.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierStrategyManager.java index 5fa8140a3ee..f1d6d06e84e 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierStrategyManager.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierStrategyManager.java @@ -19,12 +19,12 @@ * */ -package org.matsim.contrib.freight.controler; +package org.matsim.freight.carriers.controler; import com.google.inject.Provider; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierPlan; import org.matsim.core.replanning.GenericStrategyManager; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierPlan; /** * The current (jul'22) logic of this is:

    diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierStrategyManagerImpl.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierStrategyManagerImpl.java similarity index 54% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierStrategyManagerImpl.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierStrategyManagerImpl.java index 1d9dbd2694c..5bcad45b183 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierStrategyManagerImpl.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierStrategyManagerImpl.java @@ -1,14 +1,34 @@ -package org.matsim.contrib.freight.controler; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.controler; import org.matsim.api.core.v01.population.HasPlansAndId; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierPlan; -import org.matsim.contrib.freight.controler.CarrierStrategyManager; import org.matsim.core.replanning.GenericPlanStrategy; import org.matsim.core.replanning.GenericStrategyManager; import org.matsim.core.replanning.GenericStrategyManagerImpl; import org.matsim.core.replanning.ReplanningContext; import org.matsim.core.replanning.selectors.PlanSelector; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierPlan; import java.util.List; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierTimeAllocationMutator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierTimeAllocationMutator.java similarity index 65% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierTimeAllocationMutator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierTimeAllocationMutator.java index 18fdf8f54c0..3b7fc83af01 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierTimeAllocationMutator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierTimeAllocationMutator.java @@ -1,31 +1,33 @@ -/* *********************************************************************** * - * 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.freight.controler; - -import java.util.ArrayList; -import java.util.Collection; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.controler; -import org.matsim.contrib.freight.carrier.CarrierPlan; -import org.matsim.contrib.freight.carrier.ScheduledTour; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.replanning.ReplanningContext; import org.matsim.core.replanning.modules.GenericPlanStrategyModule; +import org.matsim.freight.carriers.CarrierPlan; +import org.matsim.freight.carriers.ScheduledTour; + +import java.util.ArrayList; +import java.util.Collection; /** * @author nagel diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierTimeAndSpaceTourRouter.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierTimeAndSpaceTourRouter.java similarity index 94% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierTimeAndSpaceTourRouter.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierTimeAndSpaceTourRouter.java index 1bf53c04623..0a6a7399c9f 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierTimeAndSpaceTourRouter.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierTimeAndSpaceTourRouter.java @@ -19,31 +19,31 @@ * */ -package org.matsim.contrib.freight.controler; - -import java.util.ArrayList; -import java.util.List; +package org.matsim.freight.carriers.controler; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.CarrierVehicle; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.Tour.Leg; -import org.matsim.contrib.freight.carrier.Tour.TourActivity; -import org.matsim.contrib.freight.carrier.Tour.TourElement; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.LeastCostPathCalculator.Path; import org.matsim.core.router.util.TravelTime; +import org.matsim.freight.carriers.CarrierVehicle; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.Tour.Leg; +import org.matsim.freight.carriers.Tour.TourActivity; +import org.matsim.freight.carriers.Tour.TourElement; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesImpl; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; +import java.util.ArrayList; +import java.util.List; + /** * Router routing scheduledTours. * diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierVehicleReRouter.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierVehicleReRouter.java similarity index 95% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierVehicleReRouter.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierVehicleReRouter.java index 6ce15469347..4a75e5c607d 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/CarrierVehicleReRouter.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierVehicleReRouter.java @@ -19,9 +19,7 @@ * */ -package org.matsim.contrib.freight.controler; - -import java.util.Collection; +package org.matsim.freight.carriers.controler; import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; import com.graphhopper.jsprit.core.algorithm.state.StateManager; @@ -37,17 +35,18 @@ import com.graphhopper.jsprit.io.algorithm.AlgorithmConfig; import com.graphhopper.jsprit.io.algorithm.AlgorithmConfigXmlReader; import com.graphhopper.jsprit.io.algorithm.VehicleRoutingAlgorithms; - import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierPlan; -import org.matsim.contrib.freight.carrier.CarrierVehicleTypes; -import org.matsim.contrib.freight.jsprit.MatsimJspritFactory; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts; -import org.matsim.contrib.freight.jsprit.VehicleTypeDependentRoadPricingCalculator; import org.matsim.core.replanning.ReplanningContext; import org.matsim.core.replanning.modules.GenericPlanStrategyModule; import org.matsim.core.router.util.TravelTime; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierPlan; +import org.matsim.freight.carriers.CarrierVehicleTypes; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.freight.carriers.jsprit.VehicleTypeDependentRoadPricingCalculator; + +import java.util.Collection; class CarrierVehicleReRouter implements GenericPlanStrategyModule{ diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/FreightActivity.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightActivity.java similarity index 97% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/FreightActivity.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightActivity.java index cabfe8b35e1..42cd58ae587 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/FreightActivity.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightActivity.java @@ -19,29 +19,29 @@ * */ -package org.matsim.contrib.freight.controler; +package org.matsim.freight.carriers.controler; 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.Activity; -import org.matsim.contrib.freight.carrier.TimeWindow; import org.matsim.core.utils.misc.OptionalTime; import org.matsim.facilities.ActivityFacility; +import org.matsim.freight.carriers.TimeWindow; import org.matsim.utils.objectattributes.attributable.Attributes; public class FreightActivity implements Activity { private final Activity act; - + private final TimeWindow timeWindow; - + public FreightActivity(Activity act, TimeWindow timeWindow) { super(); this.act = act; this.timeWindow = timeWindow; } - + public TimeWindow getTimeWindow(){ return timeWindow; } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/FreightAgentSource.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java similarity index 63% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/FreightAgentSource.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java index 18c39f8f2b7..71a577d8200 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/FreightAgentSource.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java @@ -1,30 +1,25 @@ /* - * *********************************************************************** * - * * project: org.matsim.* - * * ${file_name} - * * * - * * *********************************************************************** * - * * * - * * copyright : (C) ${year} by the members listed in the COPYING, * - * * LICENSE and WARRANTY file. * - * * email : info at matsim dot org * - * * * - * * *********************************************************************** * - * * * - * * This program is free software; you can redistribute it and/or modify * - * * it under the terms of the GNU General Public License as published by * - * * the Free Software Foundation; either version 2 of the License, or * - * * (at your option) any later version. * - * * See also COPYING, LICENSE and WARRANTY file * - * * * - * * *********************************************************************** + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.controler; - -import java.util.ArrayList; -import java.util.Collection; +package org.matsim.freight.carriers.controler; import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; @@ -36,8 +31,12 @@ import org.matsim.core.mobsim.qsim.QSim; import org.matsim.core.mobsim.qsim.agents.AgentFactory; import org.matsim.core.mobsim.qsim.qnetsimengine.QVehicleImpl; +import org.matsim.freight.carriers.CarriersUtils; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleUtils; + +import java.util.ArrayList; +import java.util.Collection; /** * Created by IntelliJ IDEA. User: zilske Date: 10/31/11 Time: 5:59 PM To change * this template use File | Settings | File Templates. @@ -74,14 +73,14 @@ public final class FreightAgentSource implements AgentSource { MobsimAgent agent = this.agentFactory.createMobsimAgentFromPerson( freightDriverPlan.getPerson() ); Vehicle vehicle; - if( FreightUtils.getVehicle( freightDriverPlan ) == null ){ + if( CarriersUtils.getVehicle( freightDriverPlan ) == null ){ vehicle = VehicleUtils.getFactory().createVehicle( Id.create( agent.getId(), Vehicle.class ), VehicleUtils.getDefaultVehicleType() ); log.warn( "vehicle for agent " + freightDriverPlan.getPerson().getId() + " is missing. set default vehicle where maxVelocity is solely defined by link.speed." ); - } else if( FreightUtils.getVehicle( freightDriverPlan ).getType() == null ){ + } else if( CarriersUtils.getVehicle( freightDriverPlan ).getType() == null ){ vehicle = VehicleUtils.getFactory().createVehicle( Id.create( agent.getId(), Vehicle.class ), VehicleUtils.getDefaultVehicleType() ); log.warn( "vehicleType for agent " + freightDriverPlan.getPerson().getId() + " is missing. set default vehicleType where maxVelocity is solely defined by link.speed." ); } else { - vehicle = FreightUtils.getVehicle( freightDriverPlan ); + vehicle = CarriersUtils.getVehicle( freightDriverPlan ); } log.warn( "inserting vehicleId=" + vehicle.getId() + " into mobsim." ); diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/WithinDayActivityReScheduling.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/WithinDayActivityReScheduling.java similarity index 96% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/controler/WithinDayActivityReScheduling.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/controler/WithinDayActivityReScheduling.java index eff76a7613f..285939a7174 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/controler/WithinDayActivityReScheduling.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/WithinDayActivityReScheduling.java @@ -19,20 +19,15 @@ * */ -package org.matsim.contrib.freight.controler; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; +package org.matsim.freight.carriers.controler; +import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.contrib.freight.carrier.Tour.Start; -import org.matsim.contrib.freight.carrier.Tour.TourActivity; import org.matsim.core.mobsim.framework.Mobsim; import org.matsim.core.mobsim.framework.MobsimAgent; import org.matsim.core.mobsim.framework.PlanAgent; @@ -40,8 +35,12 @@ import org.matsim.core.mobsim.framework.listeners.MobsimBeforeSimStepListener; import org.matsim.core.mobsim.framework.listeners.MobsimListener; import org.matsim.core.mobsim.qsim.agents.WithinDayAgentUtils; +import org.matsim.freight.carriers.Tour.Start; +import org.matsim.freight.carriers.Tour.TourActivity; -import com.google.inject.Inject; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; /* * Physically enforces beginnings of time windows for freight activities, i.e. freight agents diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/AbstractCarrierEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/AbstractCarrierEvent.java similarity index 55% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/AbstractCarrierEvent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/AbstractCarrierEvent.java index eade49a4dd5..1380144b9b4 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/AbstractCarrierEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/AbstractCarrierEvent.java @@ -1,11 +1,32 @@ -package org.matsim.contrib.freight.events; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.events.HasLinkId; import org.matsim.api.core.v01.events.HasVehicleId; import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.freight.carrier.Carrier; +import org.matsim.freight.carriers.Carrier; import org.matsim.vehicles.Vehicle; import java.util.Map; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventAttributes.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventAttributes.java similarity index 97% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventAttributes.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventAttributes.java index 2fc71288457..db7fb1a2738 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventAttributes.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventAttributes.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; /** * Some constants, that are used for the Attributes of different FreightEvents. diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventCreator.java similarity index 92% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventCreator.java index 3271eceaa5f..06c2abff700 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventCreator.java @@ -19,13 +19,13 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.population.Activity; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.ScheduledTour; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.ScheduledTour; import org.matsim.vehicles.Vehicle; public interface CarrierEventCreator { diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventCreatorUtils.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventCreatorUtils.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventCreatorUtils.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventCreatorUtils.java index d3ce308c6ef..df84c797ac5 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierEventCreatorUtils.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventCreatorUtils.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import java.util.ArrayList; import java.util.Collection; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventsReaders.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventsReaders.java new file mode 100644 index 00000000000..23c9176a0ff --- /dev/null +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierEventsReaders.java @@ -0,0 +1,56 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.events; + +import org.matsim.core.api.experimental.events.EventsManager; +import org.matsim.core.events.MatsimEventsReader; + +import java.util.Map; + +/** + * Creates an {@link MatsimEventsReader} that also handles the carrier specific events. + *

    + * This is a quickfix for teaching and thus _not_ complete. Needs to get completed and secured by unit-testing later (KMT, feb'23) + * + * @author kturner (Kai Martins-Turner) + */ +public class CarrierEventsReaders { + + public static Map createCustomEventMappers() { + return Map.of( + CarrierServiceStartEvent.EVENT_TYPE, CarrierServiceStartEvent::convert, + CarrierServiceEndEvent.EVENT_TYPE, CarrierServiceEndEvent::convert, + CarrierShipmentDeliveryStartEvent.EVENT_TYPE, CarrierShipmentDeliveryStartEvent::convert, + CarrierShipmentDeliveryEndEvent.EVENT_TYPE, CarrierShipmentDeliveryEndEvent::convert, + CarrierShipmentPickupStartEvent.EVENT_TYPE, CarrierShipmentPickupStartEvent::convert, + CarrierShipmentPickupEndEvent.EVENT_TYPE, CarrierShipmentPickupEndEvent::convert, + CarrierTourStartEvent.EVENT_TYPE, CarrierTourStartEvent::convert, // + CarrierTourEndEvent.EVENT_TYPE, CarrierTourEndEvent::convert + ); + } + + public static MatsimEventsReader createEventsReader(EventsManager eventsManager) { + MatsimEventsReader reader = new MatsimEventsReader(eventsManager); + createCustomEventMappers().forEach(reader::addCustomEventMapper); + return reader; + } +} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceEndEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEvent.java similarity index 66% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceEndEvent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEvent.java index e1527edc9b0..bfd8ad7d68c 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceEndEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEvent.java @@ -19,16 +19,16 @@ * */ -package org.matsim.contrib.freight.events; - -import java.util.Map; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierService; +import org.matsim.api.core.v01.events.GenericEvent; +import org.matsim.api.core.v01.network.Link; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierService; import org.matsim.vehicles.Vehicle; -import static org.matsim.contrib.freight.events.CarrierEventAttributes.*; +import java.util.Map; /** * An event, that informs that a Freight {@link CarrierService} activity has ended. @@ -63,8 +63,21 @@ public double getServiceDuration() { @Override public Map getAttributes() { Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_SERVICE_ID, serviceId.toString()); - attr.put(ATTRIBUTE_SERVICE_DURATION, String.valueOf(serviceDuration)); + attr.put(CarrierEventAttributes.ATTRIBUTE_SERVICE_ID, serviceId.toString()); + attr.put(CarrierEventAttributes.ATTRIBUTE_SERVICE_DURATION, String.valueOf(serviceDuration)); return attr; } + + public static CarrierServiceEndEvent convert(GenericEvent event) { + Map attributes = event.getAttributes(); + double time = Double.parseDouble(attributes.get(ATTRIBUTE_TIME)); + Id carrierId = Id.create(attributes.get(ATTRIBUTE_CARRIER_ID), Carrier.class); + Id carrierServiceId = Id.create(attributes.get(CarrierEventAttributes.ATTRIBUTE_SERVICE_ID), CarrierService.class); + Id locationLinkId = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); + CarrierService service = CarrierService.Builder.newInstance(carrierServiceId, locationLinkId) + .setServiceDuration(Double.parseDouble(attributes.get(CarrierEventAttributes.ATTRIBUTE_SERVICE_DURATION))) + .build(); + Id vehicleId = Id.create(attributes.get(ATTRIBUTE_VEHICLE), Vehicle.class); + return new CarrierServiceEndEvent(time, carrierId, service, vehicleId); + } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceEndEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEventCreator.java similarity index 80% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceEndEventCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEventCreator.java index 6ef0929f021..be6d484ceaf 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceEndEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEventCreator.java @@ -19,17 +19,16 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityEndEvent; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.population.Activity; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.Tour.ServiceActivity; -import org.matsim.contrib.freight.carrier.Tour.TourElement; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.Tour; import org.matsim.vehicles.Vehicle; /*package-private*/ final class CarrierServiceEndEventCreator implements CarrierEventCreator { @@ -37,8 +36,8 @@ @Override public Event createEvent(Event event, Carrier carrier, Activity activity, ScheduledTour scheduledTour, int activityCounter, Id vehicleId) { if(event instanceof ActivityEndEvent endEvent && CarrierConstants.SERVICE.equals(endEvent.getActType())) { - TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); - if(element instanceof ServiceActivity serviceActivity) { + Tour.TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); + if(element instanceof Tour.ServiceActivity serviceActivity) { return new CarrierServiceEndEvent(event.getTime(), carrier.getId(), serviceActivity.getService(), vehicleId); } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceStartEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEvent.java similarity index 64% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceStartEvent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEvent.java index 719bfc96978..1b866d5ce5b 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceStartEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEvent.java @@ -19,17 +19,17 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierService; +import org.matsim.api.core.v01.events.GenericEvent; +import org.matsim.api.core.v01.network.Link; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierService; import org.matsim.vehicles.Vehicle; import java.util.Map; -import static org.matsim.contrib.freight.events.CarrierEventAttributes.*; - /** * An event, that informs that a Freight {@link CarrierService} activity has started. * @@ -72,9 +72,23 @@ public int getCapacityDemand() { @Override public Map getAttributes() { Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_SERVICE_ID, serviceId.toString()); - attr.put(ATTRIBUTE_SERVICE_DURATION, String.valueOf(serviceDuration)); - attr.put(ATTRIBUTE_CAPACITYDEMAND, String.valueOf(capacityDemand)); + attr.put(CarrierEventAttributes.ATTRIBUTE_SERVICE_ID, serviceId.toString()); + attr.put(CarrierEventAttributes.ATTRIBUTE_SERVICE_DURATION, String.valueOf(serviceDuration)); + attr.put(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND, String.valueOf(capacityDemand)); return attr; } + + public static CarrierServiceStartEvent convert(GenericEvent event) { + Map attributes = event.getAttributes(); + double time = Double.parseDouble(attributes.get(ATTRIBUTE_TIME)); + Id carrierId = Id.create(attributes.get(ATTRIBUTE_CARRIER_ID), Carrier.class); + Id carrierServiceId = Id.create(attributes.get(CarrierEventAttributes.ATTRIBUTE_SERVICE_ID), CarrierService.class); + Id locationLinkId = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); + CarrierService service = CarrierService.Builder.newInstance(carrierServiceId, locationLinkId) + .setServiceDuration(Double.parseDouble(attributes.get(CarrierEventAttributes.ATTRIBUTE_SERVICE_DURATION))) + .setCapacityDemand(Integer.parseInt(attributes.get(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND))) + .build(); + Id vehicleId = Id.create(attributes.get(ATTRIBUTE_VEHICLE), Vehicle.class); + return new CarrierServiceStartEvent(time, carrierId, service, vehicleId); + } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceStartEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEventCreator.java similarity index 80% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceStartEventCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEventCreator.java index 370dd7e02c8..78b3bf3a276 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierServiceStartEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEventCreator.java @@ -19,17 +19,16 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityStartEvent; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.population.Activity; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.Tour.ServiceActivity; -import org.matsim.contrib.freight.carrier.Tour.TourElement; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.Tour; import org.matsim.vehicles.Vehicle; /*package-private*/ final class CarrierServiceStartEventCreator implements CarrierEventCreator { @@ -37,8 +36,8 @@ @Override public Event createEvent(Event event, Carrier carrier, Activity activity, ScheduledTour scheduledTour, int activityCounter, Id vehicleId) { if( event instanceof ActivityStartEvent startEvent && CarrierConstants.SERVICE.equals(startEvent.getActType()) ){ - TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); - if( element instanceof ServiceActivity serviceActivity ) { + Tour.TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); + if( element instanceof Tour.ServiceActivity serviceActivity ) { return new CarrierServiceStartEvent(event.getTime(), carrier.getId(), serviceActivity.getService(), vehicleId); } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryEndEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEvent.java similarity index 62% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryEndEvent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEvent.java index 9e702f3359d..c02717031fa 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryEndEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEvent.java @@ -19,17 +19,17 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierShipment; +import org.matsim.api.core.v01.events.GenericEvent; +import org.matsim.api.core.v01.network.Link; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierShipment; import org.matsim.vehicles.Vehicle; import java.util.Map; -import static org.matsim.contrib.freight.events.CarrierEventAttributes.*; - /** * An event, that informs that a Freight {@link CarrierShipment} delivery-activity has ended. * @@ -70,10 +70,24 @@ public int getCapacityDemand() { public Map getAttributes() { Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_SHIPMENT_ID, this.shipmentId.toString()); - attr.put(ATTRIBUTE_DROPOFF_DURATION, String.valueOf(this.deliveryDuration)); - attr.put(ATTRIBUTE_CAPACITYDEMAND, String.valueOf(capacityDemand)); + attr.put(CarrierEventAttributes.ATTRIBUTE_SHIPMENT_ID, this.shipmentId.toString()); + attr.put(CarrierEventAttributes.ATTRIBUTE_DROPOFF_DURATION, String.valueOf(this.deliveryDuration)); + attr.put(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND, String.valueOf(capacityDemand)); return attr; } + public static CarrierShipmentDeliveryEndEvent convert(GenericEvent event) { + var attributes = event.getAttributes(); + double time = Double.parseDouble(attributes.get(ATTRIBUTE_TIME)); + Id carrierId = Id.create(attributes.get(ATTRIBUTE_CARRIER_ID), Carrier.class); + Id shipmentId = Id.create(attributes.get(CarrierEventAttributes.ATTRIBUTE_SHIPMENT_ID), CarrierShipment.class); + Id shipmentTo = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); + int size = Integer.parseInt(attributes.get(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND)); + CarrierShipment shipment = CarrierShipment.Builder.newInstance(shipmentId, null, shipmentTo, size) + .setDeliveryServiceTime(Double.parseDouble(attributes.get(CarrierEventAttributes.ATTRIBUTE_DROPOFF_DURATION))) + .build(); + Id vehicleId = Id.createVehicleId(attributes.get(ATTRIBUTE_VEHICLE)); + return new CarrierShipmentDeliveryEndEvent(time, carrierId, shipment, vehicleId); + } + } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryEndEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEventCreator.java similarity index 81% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryEndEventCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEventCreator.java index 37e4035e94b..e1a9cfb643a 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryEndEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEventCreator.java @@ -19,17 +19,16 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityEndEvent; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.population.Activity; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.Tour.Delivery; -import org.matsim.contrib.freight.carrier.Tour.TourElement; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.Tour; import org.matsim.vehicles.Vehicle; /*package-private*/ final class CarrierShipmentDeliveryEndEventCreator implements CarrierEventCreator { @@ -37,8 +36,8 @@ @Override public Event createEvent(Event event, Carrier carrier, Activity activity, ScheduledTour scheduledTour, int activityCounter, Id vehicleId) { if(event instanceof ActivityEndEvent endEvent && CarrierConstants.DELIVERY.equals(endEvent.getActType()) ) { - TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); - if (element instanceof Delivery deliveryActivity) { + Tour.TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); + if (element instanceof Tour.Delivery deliveryActivity) { return new CarrierShipmentDeliveryEndEvent(event.getTime(), carrier.getId(), deliveryActivity.getShipment(), vehicleId ); } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryStartEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEvent.java similarity index 69% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryStartEvent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEvent.java index 6e097bbe64d..43cf21fc752 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryStartEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEvent.java @@ -19,16 +19,18 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierShipment; +import org.matsim.api.core.v01.events.GenericEvent; +import org.matsim.api.core.v01.network.Link; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierShipment; import org.matsim.vehicles.Vehicle; import java.util.Map; -import static org.matsim.contrib.freight.events.CarrierEventAttributes.*; +import static org.matsim.freight.carriers.events.CarrierEventAttributes.*; /** * An event, that informs that a Freight {@link CarrierShipment} delivery-activity has started. @@ -75,4 +77,18 @@ public Map getAttributes() { return attr; } + public static CarrierShipmentDeliveryStartEvent convert(GenericEvent event) { + var attributes = event.getAttributes(); + double time = Double.parseDouble(attributes.get(ATTRIBUTE_TIME)); + Id carrierId = Id.create(attributes.get(ATTRIBUTE_CARRIER_ID), Carrier.class); + Id shipmentId = Id.create(attributes.get(ATTRIBUTE_SHIPMENT_ID), CarrierShipment.class); + Id shipmentTo = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); + int size = Integer.parseInt(attributes.get(ATTRIBUTE_CAPACITYDEMAND)); + CarrierShipment shipment = CarrierShipment.Builder.newInstance(shipmentId, null, shipmentTo, size) + .setDeliveryServiceTime(Double.parseDouble(attributes.get(ATTRIBUTE_DROPOFF_DURATION))) + .build(); + Id vehicleId = Id.createVehicleId(attributes.get(ATTRIBUTE_VEHICLE)); + return new CarrierShipmentDeliveryStartEvent(time, carrierId, shipment, vehicleId); + } + } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryStartEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEventCreator.java similarity index 81% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryStartEventCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEventCreator.java index 8031c885ea4..5c008867117 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentDeliveryStartEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEventCreator.java @@ -19,17 +19,16 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityStartEvent; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.population.Activity; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.Tour.Delivery; -import org.matsim.contrib.freight.carrier.Tour.TourElement; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.Tour; import org.matsim.vehicles.Vehicle; /*package-private*/ final class CarrierShipmentDeliveryStartEventCreator implements CarrierEventCreator { @@ -37,8 +36,8 @@ @Override public Event createEvent(Event event, Carrier carrier, Activity activity, ScheduledTour scheduledTour, int activityCounter, Id vehicleId) { if(event instanceof ActivityStartEvent startEvent && CarrierConstants.DELIVERY.equals(startEvent.getActType()) ) { - TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); - if (element instanceof Delivery deliveryActivity) { + Tour.TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); + if (element instanceof Tour.Delivery deliveryActivity) { return new CarrierShipmentDeliveryStartEvent(event.getTime(), carrier.getId(), deliveryActivity.getShipment(), vehicleId ); } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupEndEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEvent.java similarity index 67% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupEndEvent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEvent.java index 664dbfa45c7..90e1fd137b7 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupEndEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEvent.java @@ -19,16 +19,18 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierShipment; +import org.matsim.api.core.v01.events.GenericEvent; +import org.matsim.api.core.v01.network.Link; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierShipment; import org.matsim.vehicles.Vehicle; import java.util.Map; -import static org.matsim.contrib.freight.events.CarrierEventAttributes.*; +import static org.matsim.freight.carriers.events.CarrierEventAttributes.*; /** * An event, that informs that a Freight {@link CarrierShipment} pickup-activity has ended. @@ -69,4 +71,18 @@ public Map getAttributes() { attr.put(ATTRIBUTE_CAPACITYDEMAND, String.valueOf(capacityDemand)); return attr; } + + public static CarrierShipmentPickupEndEvent convert(GenericEvent event) { + Map attributes = event.getAttributes(); + double time = Double.parseDouble(attributes.get(ATTRIBUTE_TIME)); + Id carrierId = Id.create(attributes.get(ATTRIBUTE_CARRIER_ID), Carrier.class); + Id shipmentId = Id.create(attributes.get(ATTRIBUTE_SHIPMENT_ID), CarrierShipment.class); + Id shipmentFrom = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); + int shipmentSize = Integer.parseInt(attributes.get(ATTRIBUTE_CAPACITYDEMAND)); + CarrierShipment shipment = CarrierShipment.Builder.newInstance(shipmentId, shipmentFrom, null, shipmentSize) + .setPickupServiceTime(Double.parseDouble(attributes.get(ATTRIBUTE_PICKUP_DURATION))) + .build(); + Id vehicleId = Id.createVehicleId(attributes.get(ATTRIBUTE_VEHICLE)); + return new CarrierShipmentPickupEndEvent(time, carrierId, shipment, vehicleId); + } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupEndEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEventCreator.java similarity index 81% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupEndEventCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEventCreator.java index 9b3847191db..9da464e5c66 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupEndEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEventCreator.java @@ -19,17 +19,16 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityEndEvent; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.population.Activity; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.Tour.Pickup; -import org.matsim.contrib.freight.carrier.Tour.TourElement; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.Tour; import org.matsim.vehicles.Vehicle; /*package-private*/ final class CarrierShipmentPickupEndEventCreator implements CarrierEventCreator { @@ -37,8 +36,8 @@ @Override public Event createEvent(Event event, Carrier carrier, Activity activity, ScheduledTour scheduledTour, int activityCounter, Id vehicleId) { if(event instanceof ActivityEndEvent endEvent && CarrierConstants.PICKUP.equals((endEvent).getActType()) ) { - TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); - if (element instanceof Pickup pickupActivity) { + Tour.TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); + if (element instanceof Tour.Pickup pickupActivity) { return new CarrierShipmentPickupEndEvent(event.getTime(), carrier.getId(), pickupActivity.getShipment(), vehicleId ); } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupStartEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEvent.java similarity index 61% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupStartEvent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEvent.java index 7285434d134..ab36e627190 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupStartEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEvent.java @@ -19,17 +19,17 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierShipment; +import org.matsim.api.core.v01.events.GenericEvent; +import org.matsim.api.core.v01.network.Link; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierShipment; import org.matsim.vehicles.Vehicle; import java.util.Map; -import static org.matsim.contrib.freight.events.CarrierEventAttributes.*; - /** * An event, that informs that a Freight {@link CarrierShipment} pickup-activity has started. * @@ -64,9 +64,23 @@ public Id getShipmentId() { public Map getAttributes() { Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_SHIPMENT_ID, this.shipmentId.toString()); - attr.put(ATTRIBUTE_PICKUP_DURATION, String.valueOf(this.pickupDuration)); - attr.put(ATTRIBUTE_CAPACITYDEMAND, String.valueOf(capacityDemand)); + attr.put(CarrierEventAttributes.ATTRIBUTE_SHIPMENT_ID, this.shipmentId.toString()); + attr.put(CarrierEventAttributes.ATTRIBUTE_PICKUP_DURATION, String.valueOf(this.pickupDuration)); + attr.put(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND, String.valueOf(capacityDemand)); return attr; } + + public static CarrierShipmentPickupStartEvent convert(GenericEvent event) { + Map attributes = event.getAttributes(); + double time = Double.parseDouble(attributes.get(ATTRIBUTE_TIME)); + Id carrierId = Id.create(attributes.get(ATTRIBUTE_CARRIER_ID), Carrier.class); + Id shipmentId = Id.create(attributes.get(CarrierEventAttributes.ATTRIBUTE_SHIPMENT_ID), CarrierShipment.class); + Id shipmentFrom = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); + int shipmentSize = Integer.parseInt(attributes.get(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND)); + CarrierShipment shipment = CarrierShipment.Builder.newInstance(shipmentId, shipmentFrom, null, shipmentSize) + .setPickupServiceTime(Double.parseDouble(attributes.get(CarrierEventAttributes.ATTRIBUTE_PICKUP_DURATION))) + .build(); + Id vehicleId = Id.createVehicleId(attributes.get(ATTRIBUTE_VEHICLE)); + return new CarrierShipmentPickupStartEvent(time, carrierId, shipment, vehicleId); + } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupStartEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEventCreator.java similarity index 81% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupStartEventCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEventCreator.java index 63ef107b14f..c7e2604151b 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierShipmentPickupStartEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEventCreator.java @@ -19,17 +19,16 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityStartEvent; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.population.Activity; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.Tour.Pickup; -import org.matsim.contrib.freight.carrier.Tour.TourElement; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.Tour; import org.matsim.vehicles.Vehicle; /*package-private*/ final class CarrierShipmentPickupStartEventCreator implements CarrierEventCreator { @@ -37,8 +36,8 @@ @Override public Event createEvent(Event event, Carrier carrier, Activity activity, ScheduledTour scheduledTour, int activityCounter, Id vehicleId) { if(event instanceof ActivityStartEvent startEvent && CarrierConstants.PICKUP.equals((startEvent).getActType()) ) { - TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); - if (element instanceof Pickup pickupActivity) { + Tour.TourElement element = scheduledTour.getTour().getTourElements().get(activityCounter); + if (element instanceof Tour.Pickup pickupActivity) { return new CarrierShipmentPickupStartEvent(event.getTime(), carrier.getId(), pickupActivity.getShipment(), vehicleId ); } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourEndEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourEndEvent.java similarity index 89% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourEndEvent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourEndEvent.java index b382e09e908..82e133f2166 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourEndEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourEndEvent.java @@ -19,18 +19,16 @@ * */ -package org.matsim.contrib.freight.events; - -import java.util.Map; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.GenericEvent; import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.Tour; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.Tour; import org.matsim.vehicles.Vehicle; -import static org.matsim.contrib.freight.events.CarrierEventAttributes.ATTRIBUTE_TOUR_ID; +import java.util.Map; /** * An event, that informs when a Freight {@link Tour} has ended. @@ -62,7 +60,7 @@ public Id getTourId() { @Override public Map getAttributes() { Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_TOUR_ID, this.tourId.toString()); + attr.put(CarrierEventAttributes.ATTRIBUTE_TOUR_ID, this.tourId.toString()); return attr; } @@ -72,7 +70,7 @@ public static CarrierTourEndEvent convert(GenericEvent event) { Id carrierId = Id.create(attributes.get(ATTRIBUTE_CARRIER_ID), Carrier.class); Id vehicleId = Id.create(attributes.get(ATTRIBUTE_VEHICLE), Vehicle.class); Id linkId = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); - Id tourId = Id.create(attributes.get(ATTRIBUTE_TOUR_ID), Tour.class); + Id tourId = Id.create(attributes.get(CarrierEventAttributes.ATTRIBUTE_TOUR_ID), Tour.class); return new CarrierTourEndEvent(time, carrierId, linkId, vehicleId, tourId); } } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourEndEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourEndEventCreator.java similarity index 91% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourEndEventCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourEndEventCreator.java index dce286a5259..b0777fa7d86 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourEndEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourEndEventCreator.java @@ -19,15 +19,15 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityStartEvent; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.population.Activity; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.carrier.ScheduledTour; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.ScheduledTour; import org.matsim.vehicles.Vehicle; /*package-private*/ final class CarrierTourEndEventCreator implements CarrierEventCreator { diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourStartEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEvent.java similarity index 93% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourStartEvent.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEvent.java index b3313c39a5b..9c64e8213b2 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourStartEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEvent.java @@ -19,18 +19,18 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.GenericEvent; import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.Tour; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.Tour; import org.matsim.vehicles.Vehicle; import java.util.Map; -import static org.matsim.contrib.freight.events.CarrierEventAttributes.ATTRIBUTE_TOUR_ID; +import static org.matsim.freight.carriers.events.CarrierEventAttributes.ATTRIBUTE_TOUR_ID; /** * An event, that informs when a Freight {@link Tour} has started. diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourStartEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java similarity index 95% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourStartEventCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java index a9cf3ad5fe3..eb015551dd0 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/CarrierTourStartEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.events; +package org.matsim.freight.carriers.events; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityEndEvent; @@ -27,9 +27,9 @@ import org.matsim.api.core.v01.events.PersonEntersVehicleEvent; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.carrier.ScheduledTour; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.ScheduledTour; import org.matsim.vehicles.Vehicle; import java.util.TreeMap; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/HasCarrierId.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/HasCarrierId.java new file mode 100644 index 00000000000..556524ffe5b --- /dev/null +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/HasCarrierId.java @@ -0,0 +1,34 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.events; + +import org.matsim.api.core.v01.Id; +import org.matsim.freight.carriers.Carrier; + +/** + * @author Kai Martins-Turner (kturner) + */ +public interface HasCarrierId { + String ATTRIBUTE_CARRIER_ID = "carrierId"; + + Id getCarrierId(); +} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightServiceEndEventHandler.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierServiceEndEventHandler.java similarity index 88% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightServiceEndEventHandler.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierServiceEndEventHandler.java index 48cf81c212e..11ccfde0372 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightServiceEndEventHandler.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierServiceEndEventHandler.java @@ -19,13 +19,13 @@ * */ -package org.matsim.contrib.freight.events.eventhandler; +package org.matsim.freight.carriers.events.eventhandler; -import org.matsim.contrib.freight.events.CarrierServiceEndEvent; import org.matsim.core.events.handler.EventHandler; +import org.matsim.freight.carriers.events.CarrierServiceEndEvent; -public interface FreightServiceEndEventHandler extends EventHandler{ +public interface CarrierServiceEndEventHandler extends EventHandler{ void handleEvent( CarrierServiceEndEvent event ); } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightServiceStartEventHandler.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierServiceStartEventHandler.java similarity index 88% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightServiceStartEventHandler.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierServiceStartEventHandler.java index 2e2b609e68c..a8ea55c13e8 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightServiceStartEventHandler.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierServiceStartEventHandler.java @@ -19,13 +19,13 @@ * */ -package org.matsim.contrib.freight.events.eventhandler; +package org.matsim.freight.carriers.events.eventhandler; -import org.matsim.contrib.freight.events.CarrierServiceStartEvent; import org.matsim.core.events.handler.EventHandler; +import org.matsim.freight.carriers.events.CarrierServiceStartEvent; -public interface FreightServiceStartEventHandler extends EventHandler { +public interface CarrierServiceStartEventHandler extends EventHandler { void handleEvent( CarrierServiceStartEvent event ); diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightShipmentDeliveryEventHandler.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentDeliveryEndEventHandler.java similarity index 87% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightShipmentDeliveryEventHandler.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentDeliveryEndEventHandler.java index c3560daf9c5..b2cc8ff31dc 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightShipmentDeliveryEventHandler.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentDeliveryEndEventHandler.java @@ -19,10 +19,10 @@ * */ -package org.matsim.contrib.freight.events.eventhandler; +package org.matsim.freight.carriers.events.eventhandler; -import org.matsim.contrib.freight.events.CarrierShipmentDeliveryEndEvent; import org.matsim.core.events.handler.EventHandler; +import org.matsim.freight.carriers.events.CarrierShipmentDeliveryEndEvent; /** * Interface to listen to shipmentDeliveredEvents. @@ -30,7 +30,7 @@ * @author sschroeder * */ -public interface FreightShipmentDeliveryEventHandler extends EventHandler { +public interface CarrierShipmentDeliveryEndEventHandler extends EventHandler { void handleEvent(CarrierShipmentDeliveryEndEvent event); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentDeliveryStartEventHandler.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentDeliveryStartEventHandler.java new file mode 100644 index 00000000000..df8a7b9785a --- /dev/null +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentDeliveryStartEventHandler.java @@ -0,0 +1,37 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.events.eventhandler; + +import org.matsim.core.events.handler.EventHandler; +import org.matsim.freight.carriers.events.CarrierShipmentDeliveryStartEvent; + +/** + * Interface to listen to shipmentDeliveredEvents. + * + * @author sschroeder + * + */ +public interface CarrierShipmentDeliveryStartEventHandler extends EventHandler { + + void handleEvent(CarrierShipmentDeliveryStartEvent event); + +} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightShipmentPickupEventHandler.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentPickupEndEventHandler.java similarity index 87% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightShipmentPickupEventHandler.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentPickupEndEventHandler.java index 43f0671150e..4c7282c29c7 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightShipmentPickupEventHandler.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentPickupEndEventHandler.java @@ -19,10 +19,10 @@ * */ -package org.matsim.contrib.freight.events.eventhandler; +package org.matsim.freight.carriers.events.eventhandler; -import org.matsim.contrib.freight.events.CarrierShipmentPickupEndEvent; import org.matsim.core.events.handler.EventHandler; +import org.matsim.freight.carriers.events.CarrierShipmentPickupEndEvent; /** * Interface to listen to shipmentPickedUpEvents. @@ -30,6 +30,6 @@ * @author sschroeder * */ -public interface FreightShipmentPickupEventHandler extends EventHandler { +public interface CarrierShipmentPickupEndEventHandler extends EventHandler { void handleEvent(CarrierShipmentPickupEndEvent event); } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentPickupStartEventHandler.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentPickupStartEventHandler.java new file mode 100644 index 00000000000..79c2426f023 --- /dev/null +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierShipmentPickupStartEventHandler.java @@ -0,0 +1,35 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.events.eventhandler; + +import org.matsim.core.events.handler.EventHandler; +import org.matsim.freight.carriers.events.CarrierShipmentPickupStartEvent; + +/** + * Interface to listen to shipmentPickedUpEvents. + * + * @author sschroeder + * + */ +public interface CarrierShipmentPickupStartEventHandler extends EventHandler { + void handleEvent(CarrierShipmentPickupStartEvent event); +} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightTourEndEventHandler.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierTourEndEventHandler.java similarity index 88% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightTourEndEventHandler.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierTourEndEventHandler.java index 68f84017089..2d30ce4d70c 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightTourEndEventHandler.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierTourEndEventHandler.java @@ -19,13 +19,13 @@ * */ -package org.matsim.contrib.freight.events.eventhandler; +package org.matsim.freight.carriers.events.eventhandler; -import org.matsim.contrib.freight.events.CarrierTourEndEvent; import org.matsim.core.events.handler.EventHandler; +import org.matsim.freight.carriers.events.CarrierTourEndEvent; -public interface FreightTourEndEventHandler extends EventHandler { +public interface CarrierTourEndEventHandler extends EventHandler { void handleEvent( CarrierTourEndEvent event ); diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightTourStartEventHandler.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierTourStartEventHandler.java similarity index 88% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightTourStartEventHandler.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierTourStartEventHandler.java index 7be16fe69eb..5f4b26ce4bb 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/events/eventhandler/FreightTourStartEventHandler.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/CarrierTourStartEventHandler.java @@ -19,13 +19,13 @@ * */ -package org.matsim.contrib.freight.events.eventhandler; +package org.matsim.freight.carriers.events.eventhandler; -import org.matsim.contrib.freight.events.CarrierTourStartEvent; import org.matsim.core.events.handler.EventHandler; +import org.matsim.freight.carriers.events.CarrierTourStartEvent; -public interface FreightTourStartEventHandler extends EventHandler { +public interface CarrierTourStartEventHandler extends EventHandler { void handleEvent( CarrierTourStartEvent event ); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/Vehicle2CarrierEventHandler.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/Vehicle2CarrierEventHandler.java new file mode 100644 index 00000000000..bc9236decbf --- /dev/null +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/eventhandler/Vehicle2CarrierEventHandler.java @@ -0,0 +1,70 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.events.eventhandler; + +import org.matsim.api.core.v01.Id; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.events.CarrierTourEndEvent; +import org.matsim.freight.carriers.events.CarrierTourStartEvent; +import org.matsim.vehicles.Vehicle; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Basic event handler that collects the relation between vehicles and carrier. + * Necessary since link enter and leave events do not contain any information of the carrier. + * For the connection between driver and Vehicle the {@link Vehicle2CarrierEventHandler} can be used. + * + * @author kturner + */ +public final class Vehicle2CarrierEventHandler implements CarrierTourStartEventHandler, CarrierTourEndEventHandler { + + + // Comment from Janek (in https://github.com/matsim-org/matsim-libs/pull/2128) + // Is this handler ever going to be called concurrently? If not a normal HashMap is probably sufficient + // At least the default events manager guarantees single threaded invocation of your handler. + // --> we can check this. Currently, it was made only analogous to Vehicle2DriverEventHandler kmt sep'22 + private final Map, Id> carrierVehicles = new ConcurrentHashMap<>(); + + @Override + public void reset(int iteration) { + carrierVehicles.clear(); + } + + @Override + public void handleEvent(CarrierTourStartEvent event) { + carrierVehicles.put(event.getVehicleId(), event.getCarrierId()); + } + + @Override + public void handleEvent(CarrierTourEndEvent event) { + carrierVehicles.remove(event.getVehicleId()); + } + + /** + * @param vehicleId the unique vehicle identifier. + * @return person id of the driver + */ + public Id getCarrierOfVehicle(Id vehicleId){ + return carrierVehicles.get(vehicleId); + } +} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/DistanceConstraint.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/DistanceConstraint.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java index 44e2fea63df..0d6c4725b97 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/DistanceConstraint.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2020 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.jsprit; +package org.matsim.freight.carriers.jsprit; import com.graphhopper.jsprit.core.problem.constraint.HardActivityConstraint; import com.graphhopper.jsprit.core.problem.misc.JobInsertionContext; @@ -31,7 +31,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.CarrierVehicleTypes; +import org.matsim.freight.carriers.CarrierVehicleTypes; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/DistanceUpdater.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceUpdater.java similarity index 96% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/DistanceUpdater.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceUpdater.java index 16ce48e5635..241202e1cb4 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/DistanceUpdater.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceUpdater.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2020 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.jsprit; +package org.matsim.freight.carriers.jsprit; import com.graphhopper.jsprit.core.algorithm.state.StateId; import com.graphhopper.jsprit.core.algorithm.state.StateManager; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/FiFoTravelTime.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/FiFoTravelTime.java similarity index 98% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/FiFoTravelTime.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/FiFoTravelTime.java index f7e93cdedb7..e526819617f 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/FiFoTravelTime.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/FiFoTravelTime.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.jsprit; +package org.matsim.freight.carriers.jsprit; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/MatsimJspritFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java similarity index 91% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/MatsimJspritFactory.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java index 3fe6af08455..0b16a1dbbed 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/MatsimJspritFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java @@ -1,16 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2011 Stefan Schroeder. - * eMail: stefan.schroeder@kit.edu - *

    - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v2.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html - *

    - * Contributors: - * Stefan Schroeder - initial API and implementation - ******************************************************************************/ -package org.matsim.contrib.freight.jsprit; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.jsprit; import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; import com.graphhopper.jsprit.core.algorithm.box.Jsprit; @@ -43,13 +51,8 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.TimeWindow; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.Tour.Leg; -import org.matsim.contrib.freight.carrier.Tour.TourElement; -import org.matsim.contrib.freight.controler.FreightUtils; import org.matsim.core.utils.io.IOUtils; +import org.matsim.freight.carriers.*; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; @@ -78,7 +81,7 @@ public final class MatsimJspritFactory { * * @param jspritShipment to be transformed to MATSim * @return CarrierShipment - * @see CarrierShipment, Shipment + * @see CarrierShipment , Shipment */ static CarrierShipment createCarrierShipment(Shipment jspritShipment) { CarrierShipment carrierShipment = CarrierShipment.Builder @@ -86,13 +89,13 @@ static CarrierShipment createCarrierShipment(Shipment jspritShipment) { Id.createLinkId(jspritShipment.getPickupLocation().getId()), Id.createLinkId(jspritShipment.getDeliveryLocation().getId()), jspritShipment.getSize().get(0)) .setDeliveryServiceTime(jspritShipment.getDeliveryServiceTime()) - .setDeliveryTimeWindow(TimeWindow.newInstance(jspritShipment.getDeliveryTimeWindow().getStart(), + .setDeliveryTimeWindow(org.matsim.freight.carriers.TimeWindow.newInstance(jspritShipment.getDeliveryTimeWindow().getStart(), jspritShipment.getDeliveryTimeWindow().getEnd())) .setPickupServiceTime(jspritShipment.getPickupServiceTime()) - .setPickupTimeWindow(TimeWindow.newInstance(jspritShipment.getPickupTimeWindow().getStart(), + .setPickupTimeWindow(org.matsim.freight.carriers.TimeWindow.newInstance(jspritShipment.getPickupTimeWindow().getStart(), jspritShipment.getPickupTimeWindow().getEnd())) .build(); - FreightUtils.setSkills(carrierShipment, jspritShipment.getRequiredSkills().values()); + CarriersUtils.setSkills(carrierShipment, jspritShipment.getRequiredSkills().values()); return carrierShipment; } @@ -101,7 +104,7 @@ static CarrierShipment createCarrierShipment(Shipment jspritShipment) { * * @param carrierShipment to be transformed to jsprit * @return Shipment - * @see CarrierShipment, Shipment + * @see CarrierShipment , Shipment */ static Shipment createJspritShipment(CarrierShipment carrierShipment) { Shipment.Builder shipmentBuilder = Shipment.Builder.newInstance(carrierShipment.getId().toString()) @@ -116,7 +119,7 @@ static Shipment createJspritShipment(CarrierShipment carrierShipment) { carrierShipment.getPickupTimeWindow().getStart(), carrierShipment.getPickupTimeWindow().getEnd())) .addSizeDimension(0, carrierShipment.getSize()); - for (String skill : FreightUtils.getSkills(carrierShipment)) { + for (String skill : CarriersUtils.getSkills(carrierShipment)) { shipmentBuilder.addRequiredSkill(skill); } return shipmentBuilder.build(); @@ -147,7 +150,7 @@ static Shipment createJspritShipment(CarrierShipment carrierShipment, Coord from carrierShipment.getPickupTimeWindow().getStart(), carrierShipment.getPickupTimeWindow().getEnd())) .addSizeDimension(0, carrierShipment.getSize()); - for (String skill : FreightUtils.getSkills(carrierShipment)) { + for (String skill : CarriersUtils.getSkills(carrierShipment)) { shipmentBuilder.addRequiredSkill(skill); } return shipmentBuilder.build(); @@ -167,7 +170,7 @@ static Service createJspritService(CarrierService carrierService, Coord location .setTimeWindow(com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow.newInstance( carrierService.getServiceStartTimeWindow().getStart(), carrierService.getServiceStartTimeWindow().getEnd())); - for (String skill : FreightUtils.getSkills(carrierService)) { + for (String skill : CarriersUtils.getSkills(carrierService)) { serviceBuilder.addRequiredSkill(skill); } return serviceBuilder.build(); @@ -184,9 +187,9 @@ static CarrierService createCarrierService(Service jspritService) { serviceBuilder.setCapacityDemand(jspritService.getSize().get(0)); serviceBuilder.setServiceDuration(jspritService.getServiceDuration()); serviceBuilder.setServiceStartTimeWindow( - TimeWindow.newInstance(jspritService.getTimeWindow().getStart(), jspritService.getTimeWindow().getEnd())); + org.matsim.freight.carriers.TimeWindow.newInstance(jspritService.getTimeWindow().getStart(), jspritService.getTimeWindow().getEnd())); CarrierService carrierService = serviceBuilder.build(); - FreightUtils.setSkills(carrierService, jspritService.getRequiredSkills().values()); + CarriersUtils.setSkills(carrierService, jspritService.getRequiredSkills().values()); return carrierService; } @@ -211,7 +214,7 @@ static com.graphhopper.jsprit.core.problem.vehicle.Vehicle createJspritVehicle(C vehicleBuilder.setEarliestStart(carrierVehicle.getEarliestStartTime()) .setLatestArrival(carrierVehicle.getLatestEndTime()).setStartLocation(vehicleLocation) .setType(vehicleType); - for (String skill : FreightUtils.getSkills(carrierVehicle.getType())) { + for (String skill : CarriersUtils.getSkills(carrierVehicle.getType())) { vehicleBuilder.addSkill(skill); } @@ -231,7 +234,7 @@ static com.graphhopper.jsprit.core.problem.vehicle.Vehicle createJspritVehicle(C * * @param jspritVehicle to be transformed to CarrierVehicle * @return carrierVehicle - * @see CarrierVehicle, Vehicle + * @see CarrierVehicle , Vehicle */ static CarrierVehicle createCarrierVehicle(com.graphhopper.jsprit.core.problem.vehicle.Vehicle jspritVehicle) { VehicleType matsimVehicleType; @@ -256,7 +259,7 @@ static CarrierVehicle createCarrierVehicle(com.graphhopper.jsprit.core.problem.v CarrierVehicle carrierVehicle = carrierVehicleBuilder.build(); for (String skill : jspritVehicle.getSkills().values()) { - FreightUtils.addSkill(carrierVehicle.getType(), skill); + CarriersUtils.addSkill(carrierVehicle.getType(), skill); } if (jspritVehicle.getEarliestDeparture() != carrierVehicle.getEarliestStartTime()) @@ -370,28 +373,28 @@ static ScheduledTour createScheduledTour(VehicleRoute jspritRoute, Id tour + act.getLocation().getId() + " : " + act.getLocation().getCoordinate()); Service job = (Service) ((JobActivity) act).getJob(); CarrierService carrierService = createCarrierService(job); - matsimFreightTourBuilder.addLeg(new Leg()); + matsimFreightTourBuilder.addLeg(new Tour.Leg()); matsimFreightTourBuilder.scheduleService(carrierService); } else if (act instanceof DeliverShipment) { log.debug("Found DeliveryShipment: " + act.getName() + " at location " + act.getLocation().getId() + " : " + act.getLocation().getCoordinate()); Shipment job = (Shipment) ((JobActivity) act).getJob(); CarrierShipment carrierShipment = createCarrierShipment(job); - matsimFreightTourBuilder.addLeg(new Leg()); + matsimFreightTourBuilder.addLeg(new Tour.Leg()); matsimFreightTourBuilder.scheduleDelivery(carrierShipment); } else if (act instanceof PickupShipment) { log.debug("Found PickupShipment: " + act.getName() + " at location " + act.getLocation().getId() + " : " + act.getLocation().getCoordinate()); Shipment job = (Shipment) ((JobActivity) act).getJob(); CarrierShipment carrierShipment = createCarrierShipment(job); - matsimFreightTourBuilder.addLeg(new Leg()); + matsimFreightTourBuilder.addLeg(new Tour.Leg()); matsimFreightTourBuilder.schedulePickup(carrierShipment); } else throw new IllegalStateException("unknown tourActivity occurred. this cannot be"); } - matsimFreightTourBuilder.addLeg(new Leg()); + matsimFreightTourBuilder.addLeg(new Tour.Leg()); matsimFreightTourBuilder.scheduleEnd(Id.create(jspritRoute.getEnd().getLocation().getId(), Link.class)); - org.matsim.contrib.freight.carrier.Tour matsimVehicleTour = matsimFreightTourBuilder.build(); + Tour matsimVehicleTour = matsimFreightTourBuilder.build(); ScheduledTour sTour = ScheduledTour.newInstance(matsimVehicleTour, carrierVehicle, depTime); if (jspritRoute.getDepartureTime() != sTour.getDeparture()) @@ -429,10 +432,10 @@ public static VehicleRoute createRoute(ScheduledTour scheduledTour, VehicleRouti jspritRouteBuilder.setJobActivityFactory(vehicleRoutingProblem.getJobActivityFactory()); jspritRouteBuilder.setDepartureTime(depTime); - for (TourElement e : tour.getTourElements()) { - if (e instanceof org.matsim.contrib.freight.carrier.Tour.TourActivity) { - if (e instanceof org.matsim.contrib.freight.carrier.Tour.ServiceActivity) { - CarrierService carrierService = ((org.matsim.contrib.freight.carrier.Tour.ServiceActivity) e) + for (Tour.TourElement e : tour.getTourElements()) { + if (e instanceof Tour.TourActivity) { + if (e instanceof Tour.ServiceActivity) { + CarrierService carrierService = ((Tour.ServiceActivity) e) .getService(); Service service = (Service) vehicleRoutingProblem.getJobs().get(carrierService.getId().toString()); if (service == null) @@ -483,7 +486,7 @@ public static VehicleRoutingProblem createRoutingProblem(Carrier carrier, Networ FleetSize fleetSize; CarrierCapabilities carrierCapabilities = carrier.getCarrierCapabilities(); if (carrierCapabilities.getFleetSize() - .equals(org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize.INFINITE)) { + .equals(CarrierCapabilities.FleetSize.INFINITE)) { fleetSize = FleetSize.INFINITE; vrpBuilder.setFleetSize(fleetSize); } else { @@ -587,7 +590,7 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier FleetSize fleetSize; CarrierCapabilities carrierCapabilities = carrier.getCarrierCapabilities(); if (carrierCapabilities.getFleetSize() - .equals(org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize.INFINITE)) { + .equals(CarrierCapabilities.FleetSize.INFINITE)) { fleetSize = FleetSize.INFINITE; vrpBuilder.setFleetSize(fleetSize); } else { @@ -678,14 +681,14 @@ public static VehicleRoutingProblemSolution createSolution(CarrierPlan plan, */ public static Carrier createCarrier(String carrierId, VehicleRoutingProblem vrp) { Id id = Id.create(carrierId, Carrier.class); - Carrier carrier = CarrierUtils.createCarrier(id); + Carrier carrier = CarriersUtils.createCarrier(id); CarrierCapabilities.Builder capabilityBuilder = CarrierCapabilities.Builder.newInstance(); // fleet and vehicles if (vrp.getFleetSize().equals(FleetSize.FINITE)) { - capabilityBuilder.setFleetSize(org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize.FINITE); + capabilityBuilder.setFleetSize(CarrierCapabilities.FleetSize.FINITE); } else - capabilityBuilder.setFleetSize(org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize.INFINITE); + capabilityBuilder.setFleetSize(CarrierCapabilities.FleetSize.INFINITE); for (com.graphhopper.jsprit.core.problem.vehicle.VehicleType type : vrp.getTypes()) { capabilityBuilder.addType(createMatsimVehicleType(type)); } @@ -727,7 +730,7 @@ public static CarrierPlan createPlan(Carrier carrier, VehicleRoutingProblemSolut * set in the freightConfigGroup. */ public static VehicleRoutingAlgorithm loadOrCreateVehicleRoutingAlgorithm(Scenario scenario, - FreightConfigGroup freightConfig, NetworkBasedTransportCosts netBasedCosts, VehicleRoutingProblem problem) { + FreightCarriersConfigGroup freightConfig, NetworkBasedTransportCosts netBasedCosts, VehicleRoutingProblem problem) { VehicleRoutingAlgorithm algorithm; final String vehicleRoutingAlgorithmFile = freightConfig.getVehicleRoutingAlgorithmFile(); @@ -749,7 +752,7 @@ public static VehicleRoutingAlgorithm loadOrCreateVehicleRoutingAlgorithm(Scenar ConstraintManager constraintManager = new ConstraintManager(problem, stateManager); constraintManager.addConstraint( new DistanceConstraint( - FreightUtils.getCarrierVehicleTypes(scenario), netBasedCosts), + CarriersUtils.getCarrierVehicleTypes(scenario), netBasedCosts), ConstraintManager.Priority.CRITICAL); AlgorithmConfig algorithmConfig = new AlgorithmConfig(); AlgorithmConfigXmlReader xmlReader = new AlgorithmConfigXmlReader(algorithmConfig); @@ -773,7 +776,7 @@ public static VehicleRoutingAlgorithm loadOrCreateVehicleRoutingAlgorithm(Scenar ConstraintManager constraintManager = new ConstraintManager(problem, stateManager); constraintManager.addConstraint( new DistanceConstraint( - FreightUtils.getCarrierVehicleTypes(scenario), netBasedCosts), + CarriersUtils.getCarrierVehicleTypes(scenario), netBasedCosts), ConstraintManager.Priority.CRITICAL); algorithm = Jsprit.Builder.newInstance(problem) .setStateAndConstraintManager(stateManager, constraintManager).buildAlgorithm(); diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCosts.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java similarity index 94% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCosts.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java index 6cb52bcc5a2..6ae0c93d705 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCosts.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java @@ -1,16 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2011 Stefan Schroeder. - * eMail: stefan.schroeder@kit.edu - *

    - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v2.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html - *

    - * Contributors: - * Stefan Schroeder - initial API and implementation - ******************************************************************************/ -package org.matsim.contrib.freight.jsprit; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.jsprit; import com.graphhopper.jsprit.core.problem.Location; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; @@ -22,14 +30,14 @@ 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.freight.carrier.CarrierVehicle; -import org.matsim.core.router.FastDijkstraFactory; +import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.LeastCostPathCalculator.Path; import org.matsim.core.router.util.LeastCostPathCalculatorFactory; import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; import org.matsim.core.utils.misc.Counter; +import org.matsim.freight.carriers.CarrierVehicle; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesImpl; import org.matsim.vehicles.VehicleType; @@ -369,7 +377,7 @@ public static Builder newInstance(Network network) { private int timeSliceWidth = Integer.MAX_VALUE; - private LeastCostPathCalculatorFactory leastCostPathCalculatorFactory = (network, travelCosts, travelTimes) -> new FastDijkstraFactory().createPathCalculator(network, travelCosts, travelTime); + private LeastCostPathCalculatorFactory leastCostPathCalculatorFactory = (network, travelCosts, travelTimes) -> new SpeedyALTFactory().createPathCalculator(network, travelCosts, travelTime); private VehicleTypeDependentRoadPricingCalculator roadPricingCalculator = new VehicleTypeDependentRoadPricingCalculator(); @@ -455,7 +463,7 @@ public Builder setFIFO(boolean isFIFO) { * each thread a new LCPA is created with the same LCPA-factory. That is, * memorizing data in the factory-obj might violate thread-safety. *

    - * By default, it use {@link FastDijkstraFactory} + * By default, it use {@link SpeedyALTFactory} * * @param {@link {@link LeastCostPathCalculatorFactory} * @return this builder @@ -548,7 +556,7 @@ public void addVehicleTypeSpecificCosts(String typeId, double fix, double perSec private final VehicleTypeDependentRoadPricingCalculator roadPricingCalc; /** - * by default sets the {@link FastDijkstraFactory} + * by default sets the {@link SpeedyALTFactory} */ private final LeastCostPathCalculatorFactory leastCostPathCalculatorFactory; @@ -592,6 +600,7 @@ public double getTransportTime(Location fromId, Location toId, double departureT } String typeId = vehicle.getType().getTypeId(); int timeSlice = getTimeSlice(departureTime); + departureTime = timeSlice*timeSliceWidth; TransportDataKey transportDataKey = makeKey(fromId.getId(), toId.getId(), timeSlice, typeId); TransportData data = costCache.get(transportDataKey); double transportTime; @@ -680,6 +689,7 @@ public double getTransportCost(Location fromId, Location toId, double departureT LeastCostPathCalculator router = createLeastCostPathCalculator(); int timeSlice = getTimeSlice(departureTime); + departureTime = timeSlice*timeSliceWidth; String typeId = vehicle.getType().getTypeId(); TransportDataKey transportDataKey = makeKey(fromId.getId(), toId.getId(), timeSlice, typeId); TransportData data = costCache.get(transportDataKey); @@ -738,6 +748,7 @@ public double getDistance(Location fromId, Location toId, double departureTime, } String typeId = vehicle.getType().getTypeId(); int timeSlice = getTimeSlice(departureTime); + departureTime = timeSlice*timeSliceWidth; TransportDataKey transportDataKey = makeKey(fromId.getId(), toId.getId(), timeSlice, typeId); TransportData data = costCache.get(transportDataKey); double travelDistance; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCostsFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java similarity index 87% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCostsFactory.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java index 66cac6f5633..3fcc5ca9868 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCostsFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java @@ -19,15 +19,15 @@ * */ -package org.matsim.contrib.freight.jsprit; +package org.matsim.freight.carriers.jsprit; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.TransportMode; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.Carriers; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.router.util.TravelTime; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.Carriers; import org.matsim.vehicles.VehicleType; import java.util.HashSet; @@ -53,8 +53,8 @@ public NetworkBasedTransportCostsFactory(Scenario scenario, Carriers carriers, M @Override public VRPTransportCosts createVRPTransportCosts() { - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, - FreightConfigGroup.class); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, + FreightCarriersConfigGroup.class); Set vehicleTypes = new HashSet<>(); carriers.getCarriers().values().forEach( @@ -63,7 +63,7 @@ public VRPTransportCosts createVRPTransportCosts() { NetworkBasedTransportCosts.Builder netBuilder = NetworkBasedTransportCosts.Builder .newInstance(scenario.getNetwork(), vehicleTypes); - netBuilder.setTimeSliceWidth(freightConfigGroup.getTravelTimeSliceWidth()); + netBuilder.setTimeSliceWidth(freightCarriersConfigGroup.getTravelTimeSliceWidth()); netBuilder.setTravelTime(travelTimes.get(TransportMode.car)); return netBuilder.build(); } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkRouter.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkRouter.java new file mode 100644 index 00000000000..7dac94a1c8c --- /dev/null +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkRouter.java @@ -0,0 +1,50 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.jsprit; + +import org.matsim.freight.carriers.CarrierPlan; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.controler.CarrierTimeAndSpaceTourRouter; + +/** + * Router that routes {@link CarrierPlan}. + * + * @author stefan schröder + * + */ +public class NetworkRouter { + + /** + * Routes the {@link CarrierPlan} with the router defined in {@link NetworkBasedTransportCosts}. + * + *

    Note that this changes the plan, i.e. it adds routes to the input-plan. + * + * @param {@link CarrierPlan} + * @param {@link NetworkBasedTransportCosts} + */ + public static void routePlan(CarrierPlan plan, VRPTransportCosts freightTransportCosts){ + if( plan == null) throw new IllegalStateException("plan is missing."); + for( ScheduledTour tour : plan.getScheduledTours()){ + new CarrierTimeAndSpaceTourRouter( freightTransportCosts.getRouter(), freightTransportCosts.getNetwork(), freightTransportCosts.getTravelTime()).route(tour ); + } + } + +} diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/VRPTransportCosts.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/VRPTransportCosts.java similarity index 97% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/VRPTransportCosts.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/VRPTransportCosts.java index 260bf10bba4..d831d329fc9 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/VRPTransportCosts.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/VRPTransportCosts.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.jsprit; +package org.matsim.freight.carriers.jsprit; import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingTransportCosts; import org.matsim.api.core.v01.network.Network; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/VRPTransportCostsFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/VRPTransportCostsFactory.java similarity index 97% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/VRPTransportCostsFactory.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/VRPTransportCostsFactory.java index 5c7e36b58f5..bb6efbdd9ec 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/VRPTransportCostsFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/VRPTransportCostsFactory.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.jsprit; +package org.matsim.freight.carriers.jsprit; /** * @author steffenaxer diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/VehicleTypeDependentRoadPricingCalculator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/VehicleTypeDependentRoadPricingCalculator.java similarity index 79% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/VehicleTypeDependentRoadPricingCalculator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/VehicleTypeDependentRoadPricingCalculator.java index 84adb4539a4..ed5d3694720 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/VehicleTypeDependentRoadPricingCalculator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/VehicleTypeDependentRoadPricingCalculator.java @@ -1,26 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2011 Stefan Schroeder. - * eMail: stefan.schroeder@kit.edu - *

    - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v2.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html - *

    - * Contributors: - * Stefan Schroeder - initial API and implementation - ******************************************************************************/ -package org.matsim.contrib.freight.jsprit; - -import java.util.*; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.jsprit; import com.graphhopper.jsprit.core.problem.vehicle.VehicleType; - import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.roadpricing.RoadPricingScheme; import org.matsim.contrib.roadpricing.RoadPricingSchemeImpl.Cost; +import java.util.*; + /** * Calculator that manages and calculates vehicle type dependent road pricing schemas. diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/package-info.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/package-info.java similarity index 95% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/package-info.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/package-info.java index ea043d9c4b6..e5d676fe61b 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/package-info.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/package-info.java @@ -21,11 +21,10 @@ /** * Package that plugs freight algorithms (programmed in external package jsprit) into matsim. - * A good starting point for jsprit is + * A good starting point for jsprit is * https://github.com/graphhopper/jsprit. - * + * * @author (of documentation) nagel */ -package org.matsim.contrib.freight; +package org.matsim.freight.carriers; - \ No newline at end of file diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/analysis/CarrierScoreStats.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java similarity index 82% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/analysis/CarrierScoreStats.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java index 12fdd2fdacb..dd289a49b1b 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/analysis/CarrierScoreStats.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java @@ -1,30 +1,28 @@ -/* *********************************************************************** * - * project: org.matsim.* - * ScoreStats.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007 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.freight.usecases.analysis; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.usecases.analysis; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierPlan; -import org.matsim.contrib.freight.carrier.Carriers; import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.controler.events.ShutdownEvent; import org.matsim.core.controler.events.StartupEvent; @@ -33,10 +31,13 @@ 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 org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierPlan; +import org.matsim.freight.carriers.Carriers; import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.Locale; /** @@ -100,8 +101,8 @@ public void notifyStartup(final StartupEvent event) { } catch (IOException e) { throw new UncheckedIOException(e); } - this.minIteration = event.getServices().getConfig().controler().getFirstIteration(); - int maxIter = event.getServices().getConfig().controler().getLastIteration(); + this.minIteration = event.getServices().getConfig().controller().getFirstIteration(); + int maxIter = event.getServices().getConfig().controller().getLastIteration(); int iterations = maxIter - this.minIteration; if (iterations > 5000) iterations = 5000; // limit the history size this.history = new double[4][iterations+1]; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/analysis/LegHistogram.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java similarity index 90% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/analysis/LegHistogram.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java index b1c022cbb27..1db193121ec 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/analysis/LegHistogram.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java @@ -1,36 +1,27 @@ -/* *********************************************************************** * - * project: org.matsim.* - * LegHistogram.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007 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.freight.usecases.analysis; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Font; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintStream; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.usecases.analysis; +import jakarta.inject.Inject; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtils; import org.jfree.chart.JFreeChart; @@ -51,7 +42,14 @@ import org.matsim.api.core.v01.population.Population; import org.matsim.core.utils.misc.Time; -import jakarta.inject.Inject; +import java.awt.*; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; /** * It is a copy of {@link org.matsim.analysis.LegHistogram}. It is modified to include or exclude persons. diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java similarity index 94% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java index 7cc71f79006..6d137ce6f27 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; +package org.matsim.freight.carriers.usecases.chessboard; import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; @@ -31,14 +31,14 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.controler.CarrierScoringFunctionFactory; -import org.matsim.contrib.freight.controler.FreightActivity; -import org.matsim.contrib.freight.jsprit.VehicleTypeDependentRoadPricingCalculator; import org.matsim.core.gbl.Gbl; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.scoring.ScoringFunction; import org.matsim.core.scoring.SumScoringFunction; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.controler.CarrierScoringFunctionFactory; +import org.matsim.freight.carriers.controler.FreightActivity; +import org.matsim.freight.carriers.jsprit.VehicleTypeDependentRoadPricingCalculator; import org.matsim.vehicles.Vehicle; import java.util.HashSet; @@ -185,7 +185,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); if(!employedVehicles.contains(vehicle)){ employedVehicles.add(vehicle); @@ -234,7 +234,7 @@ public SimpleTollScoring( Carrier carrier, Network network, VehicleTypeDependent @Override public void handleEvent(Event event) { if(event instanceof LinkEnterEvent){ - CarrierVehicle carrierVehicle = CarrierUtils.getCarrierVehicle(carrier, ((LinkEnterEvent) event).getVehicleId()); + CarrierVehicle carrierVehicle = CarriersUtils.getCarrierVehicle(carrier, ((LinkEnterEvent) event).getVehicleId()); if(carrierVehicle == null) throw new IllegalStateException("carrier vehicle missing"); double toll = roadPricing.getTollAmount(carrierVehicle.getType().getId(),network.getLinks().get(((LinkEnterEvent) event).getLinkId() ),event.getTime() ); if(toll > 0.) System.out.println("bing: vehicle " + carrierVehicle.getId() + " paid toll " + toll + "" ); diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/CarrierTravelDisutilities.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierTravelDisutilities.java similarity index 94% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/CarrierTravelDisutilities.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierTravelDisutilities.java index 37c45b7e8a8..6f5aa812cdc 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/CarrierTravelDisutilities.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierTravelDisutilities.java @@ -19,20 +19,20 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; +package org.matsim.freight.carriers.usecases.chessboard; 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.contrib.freight.carrier.CarrierVehicleTypes; -import org.matsim.contrib.freight.jsprit.VehicleTypeDependentRoadPricingCalculator; import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; +import org.matsim.freight.carriers.CarrierVehicleTypes; +import org.matsim.freight.carriers.jsprit.VehicleTypeDependentRoadPricingCalculator; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; public final class CarrierTravelDisutilities{ - + public static TravelDisutility createBaseDisutility(final CarrierVehicleTypes vehicleTypes, final TravelTime travelTime){ return new TravelDisutility() { @@ -79,7 +79,7 @@ public double getLinkMinimumTravelDisutility(Link link) { }; } - + } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/FreightScenarioCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java similarity index 91% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/FreightScenarioCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java index 80c5ac16f39..be215bd0d7e 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/FreightScenarioCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java @@ -19,17 +19,17 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; +package org.matsim.freight.carriers.usecases.chessboard; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; import org.matsim.core.config.Config; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; @@ -63,14 +63,14 @@ public static void main(String[] args) { for(int i=1;i<10;i++){ Id homeId = Id.createLinkId("i("+i+",9)R"); - Carrier carrier = CarrierUtils.createCarrier(Id.create(agentCounter,Carrier.class ) ); + Carrier carrier = CarriersUtils.createCarrier(Id.create(agentCounter,Carrier.class ) ); createFleet(homeId, carrier); createCustomers(carrier,scenario.getNetwork()); agentCounter++; carriers.addCarrier(carrier); Id homeIdR = Id.createLinkId("i("+i+",0)"); - Carrier carrier_ = CarrierUtils.createCarrier(Id.create(agentCounter,Carrier.class ) ); + Carrier carrier_ = CarriersUtils.createCarrier(Id.create(agentCounter,Carrier.class ) ); createFleet(homeIdR, carrier_); createCustomers(carrier_,scenario.getNetwork()); agentCounter++; @@ -79,14 +79,14 @@ public static void main(String[] args) { for(int i=1;i<10;i++){ Id homeId = Id.createLinkId("j(0,"+i+")R"); - Carrier carrier = CarrierUtils.createCarrier(Id.create(agentCounter,Carrier.class ) ); + Carrier carrier = CarriersUtils.createCarrier(Id.create(agentCounter,Carrier.class ) ); createFleet(homeId, carrier); createCustomers(carrier,scenario.getNetwork()); agentCounter++; carriers.addCarrier(carrier); Id homeIdR = Id.createLinkId("j(9,"+i+")"); - Carrier carrier_ = CarrierUtils.createCarrier(Id.create(agentCounter,Carrier.class ) ); + Carrier carrier_ = CarriersUtils.createCarrier(Id.create(agentCounter,Carrier.class ) ); createFleet(homeIdR, carrier_); createCustomers(carrier_,scenario.getNetwork()); agentCounter++; @@ -106,7 +106,7 @@ private static void createCustomers(Carrier carrier, Network network) { serviceBuilder.setServiceDuration(5*60); serviceBuilder.setServiceStartTimeWindow(TimeWindow.newInstance(6*60*60, 15*60*60)); CarrierService carrierService = serviceBuilder.build(); - CarrierUtils.addService(carrier, carrierService); + CarriersUtils.addService(carrier, carrierService); } } @@ -150,15 +150,15 @@ private static void createFleet(Id homeId, Carrier carrier) { //light CarrierVehicle carrierVehicle_lightA = createLightVehicle(carrier.getId(), homeId, "a"); - CarrierUtils.addCarrierVehicle(carrier, carrierVehicle_lightA); + CarriersUtils.addCarrierVehicle(carrier, carrierVehicle_lightA); CarrierVehicle carrierVehicle_lightB = createLightVehicle(carrier.getId(), oppositeId, "b"); - CarrierUtils.addCarrierVehicle(carrier, carrierVehicle_lightB); + CarriersUtils.addCarrierVehicle(carrier, carrierVehicle_lightB); //heavy CarrierVehicle carrierVehicle_heavyA = createHeavyVehicle(carrier.getId(), homeId, "a"); - CarrierUtils.addCarrierVehicle(carrier, carrierVehicle_heavyA); + CarriersUtils.addCarrierVehicle(carrier, carrierVehicle_heavyA); CarrierVehicle carrierVehicle_heavyB = createHeavyVehicle(carrier.getId(), oppositeId, "b"); - CarrierUtils.addCarrierVehicle(carrier, carrierVehicle_heavyB); + CarriersUtils.addCarrierVehicle(carrier, carrierVehicle_heavyB); carrier.getCarrierCapabilities().setFleetSize(FleetSize.INFINITE); } diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/InitialCarrierPlanCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/InitialCarrierPlanCreator.java similarity index 96% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/InitialCarrierPlanCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/InitialCarrierPlanCreator.java index 609aa8586b1..cd2e07405f7 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/InitialCarrierPlanCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/InitialCarrierPlanCreator.java @@ -19,9 +19,7 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; - -import java.util.Collection; +package org.matsim.freight.carriers.usecases.chessboard; import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; import com.graphhopper.jsprit.core.algorithm.state.StateManager; @@ -36,16 +34,17 @@ import com.graphhopper.jsprit.io.algorithm.AlgorithmConfig; import com.graphhopper.jsprit.io.algorithm.AlgorithmConfigXmlReader; import com.graphhopper.jsprit.io.algorithm.VehicleRoutingAlgorithms; - import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.jsprit.MatsimJspritFactory; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts; -import org.matsim.contrib.freight.jsprit.NetworkRouter; import org.matsim.core.config.Config; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.freight.carriers.jsprit.NetworkRouter; + +import java.util.Collection; final class InitialCarrierPlanCreator { diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/InnerOuterCityScenarioCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/InnerOuterCityScenarioCreator.java similarity index 97% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/InnerOuterCityScenarioCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/InnerOuterCityScenarioCreator.java index ffe602c1368..d5b48f1df69 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/InnerOuterCityScenarioCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/InnerOuterCityScenarioCreator.java @@ -19,15 +19,15 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; +package org.matsim.freight.carriers.usecases.chessboard; + +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.network.Link; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; - final class InnerOuterCityScenarioCreator { diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/PassengerScenarioCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java similarity index 93% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/PassengerScenarioCreator.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java index dc77dd1f8ef..e19d4b506bb 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/PassengerScenarioCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java @@ -19,22 +19,13 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; - -import java.util.ArrayList; -import java.util.List; +package org.matsim.freight.carriers.usecases.chessboard; 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.Link; -import org.matsim.api.core.v01.population.Activity; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Person; -import org.matsim.api.core.v01.population.Plan; -import org.matsim.api.core.v01.population.Population; -import org.matsim.api.core.v01.population.PopulationFactory; -import org.matsim.api.core.v01.population.PopulationWriter; +import org.matsim.api.core.v01.population.*; import org.matsim.core.config.Config; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.population.routes.NetworkRoute; @@ -45,6 +36,9 @@ import org.matsim.core.router.util.LeastCostPathCalculator.Path; import org.matsim.core.scenario.ScenarioUtils; +import java.util.ArrayList; +import java.util.List; + final class PassengerScenarioCreator { static int agentCounter = 1; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/PlotPlans.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PlotPlans.java similarity index 86% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/PlotPlans.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PlotPlans.java index dbbe3ca8804..838ac5463ae 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/PlotPlans.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PlotPlans.java @@ -19,24 +19,18 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; +package org.matsim.freight.carriers.usecases.chessboard; import com.graphhopper.jsprit.analysis.toolbox.Plotter; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; - 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.CarrierPlanXmlReader; -import org.matsim.contrib.freight.carrier.CarrierVehicleTypeLoader; -import org.matsim.contrib.freight.carrier.CarrierVehicleTypeReader; -import org.matsim.contrib.freight.carrier.CarrierVehicleTypes; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.jsprit.MatsimJspritFactory; import org.matsim.core.config.Config; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; final class PlotPlans { diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunChessboard.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunChessboard.java similarity index 82% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunChessboard.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunChessboard.java index a7f4ceb2f69..e8f7887cfea 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunChessboard.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunChessboard.java @@ -19,18 +19,13 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; +package org.matsim.freight.carriers.usecases.chessboard; import com.google.inject.Provider; +import jakarta.inject.Inject; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.controler.*; -import org.matsim.contrib.freight.usecases.analysis.CarrierScoreStats; -import org.matsim.contrib.freight.usecases.analysis.LegHistogram; -import org.matsim.contrib.freight.usecases.chessboard.CarrierScoringFunctionFactoryImpl.SimpleVehicleEmploymentScoring; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.AbstractModule; @@ -50,8 +45,11 @@ import org.matsim.core.scoring.SumScoringFunction; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.controler.*; +import org.matsim.freight.carriers.usecases.analysis.CarrierScoreStats; +import org.matsim.freight.carriers.usecases.analysis.LegHistogram; -import jakarta.inject.Inject; import java.util.Map; public final class RunChessboard { @@ -60,21 +58,21 @@ public static void main(String[] args){ Config config; if ( args ==null || args.length==0 || args[0]==null ){ config = ConfigUtils.loadConfig( IOUtils.extendUrl( ExamplesUtils.getTestScenarioURL( "freight-chessboard-9x9" ), "config.xml" ) ); - config.controler().setLastIteration( 1 ); - config.controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setLastIteration( 1 ); + config.controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); } else { config = ConfigUtils.loadConfig( args ); } - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule( config, FreightConfigGroup.class ); - freightConfigGroup.setCarriersFile("carrierPlans.xml"); - freightConfigGroup.setCarriersVehicleTypesFile("vehicleTypes.xml"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule( config, FreightCarriersConfigGroup.class ); + freightCarriersConfigGroup.setCarriersFile("carrierPlans.xml"); + freightCarriersConfigGroup.setCarriersVehicleTypesFile("vehicleTypes.xml"); Scenario scenario = ScenarioUtils.loadScenario( config ) ; - FreightUtils.loadCarriersAccordingToFreightConfig( scenario ); + CarriersUtils.loadCarriersAccordingToFreightConfig( scenario ); - Carriers carriers = FreightUtils.addOrGetCarriers( scenario ); - CarrierVehicleTypes types = FreightUtils.getCarrierVehicleTypes( scenario ); + Carriers carriers = CarriersUtils.addOrGetCarriers( scenario ); + CarrierVehicleTypes types = CarriersUtils.getCarrierVehicleTypes( scenario ); Controler controler = new Controler( scenario); @@ -93,7 +91,7 @@ public void install() { final LegHistogram withoutFreight = new LegHistogram(900); addEventHandlerBinding().toInstance(withoutFreight); - addControlerListenerBinding().toInstance( new CarrierScoreStats(carriers, config.controler().getOutputDirectory() +"/carrier_scores", true) ); + addControlerListenerBinding().toInstance( new CarrierScoreStats(carriers, config.controller().getOutputDirectory() +"/carrier_scores", true) ); addControlerListenerBinding().toInstance( new IterationEndsListener() { @Inject private OutputDirectoryHierarchy controlerIO; @@ -124,7 +122,7 @@ private static class MyCarrierScoringFunctionFactory implements CarrierScoringFu @Override public ScoringFunction createScoringFunction(Carrier carrier) { SumScoringFunction sf = new SumScoringFunction(); sf.addScoringFunction( new CarrierScoringFunctionFactoryImpl.SimpleDriversLegScoring(carrier, network) ); - sf.addScoringFunction( new SimpleVehicleEmploymentScoring(carrier) ); + sf.addScoringFunction( new CarrierScoringFunctionFactoryImpl.SimpleVehicleEmploymentScoring(carrier) ); sf.addScoringFunction( new CarrierScoringFunctionFactoryImpl.SimpleDriversActivityScoring() ); return sf; } @@ -141,7 +139,7 @@ private static class MyCarrierPlanStrategyManagerProvider implements Provider strategy = new GenericPlanStrategyImpl<>( new ExpBetaPlanChanger.Factory().build() ); diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerAlongWithCarriers.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java similarity index 84% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerAlongWithCarriers.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java index 2934ba58ca9..36f76f30787 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerAlongWithCarriers.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java @@ -19,19 +19,13 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; +package org.matsim.freight.carriers.usecases.chessboard; import com.google.inject.Provider; +import jakarta.inject.Inject; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.controler.*; -import org.matsim.contrib.freight.usecases.analysis.CarrierScoreStats; -import org.matsim.contrib.freight.usecases.analysis.LegHistogram; -import org.matsim.contrib.freight.usecases.chessboard.CarrierScoringFunctionFactoryImpl.SimpleDriversActivityScoring; -import org.matsim.contrib.freight.usecases.chessboard.CarrierScoringFunctionFactoryImpl.SimpleDriversLegScoring; -import org.matsim.contrib.freight.usecases.chessboard.CarrierScoringFunctionFactoryImpl.SimpleVehicleEmploymentScoring; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; @@ -52,8 +46,11 @@ import org.matsim.core.scoring.SumScoringFunction; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.controler.*; +import org.matsim.freight.carriers.usecases.analysis.CarrierScoreStats; +import org.matsim.freight.carriers.usecases.analysis.LegHistogram; -import jakarta.inject.Inject; import java.net.URL; import java.util.Map; @@ -83,11 +80,11 @@ public void run() { controler.addOverridingModule( new AbstractModule(){ @Override public void install(){ this.bind( CarrierStrategyManager.class ).toProvider( new MyCarrierPlanStrategyManagerFactory(types) ); - this.bind( CarrierScoringFunctionFactory.class ).toInstance( carrier -> { + this.bind( CarrierScoringFunctionFactory.class ).toInstance(carrier -> { SumScoringFunction sf = new SumScoringFunction(); - sf.addScoringFunction( new SimpleDriversLegScoring( carrier, scenario.getNetwork() ) ); - sf.addScoringFunction( new SimpleVehicleEmploymentScoring( carrier ) ); - sf.addScoringFunction( new SimpleDriversActivityScoring() ); + sf.addScoringFunction( new CarrierScoringFunctionFactoryImpl.SimpleDriversLegScoring( carrier, scenario.getNetwork() ) ); + sf.addScoringFunction( new CarrierScoringFunctionFactoryImpl.SimpleVehicleEmploymentScoring( carrier ) ); + sf.addScoringFunction( new CarrierScoringFunctionFactoryImpl.SimpleDriversActivityScoring() ); return sf; } ); } @@ -102,16 +99,16 @@ public void run() { public final Config prepareConfig() { Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(url, "config.xml")); - config.controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); + config.controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); config.global().setRandomSeed(4177); - config.controler().setOutputDirectory("./output/"); + config.controller().setOutputDirectory("./output/"); return config; } public final Scenario prepareScenario(Config config) { Gbl.assertNotNull( config ); Scenario scenario = ScenarioUtils.loadScenario(config); - FreightUtils.addOrGetCarriers(scenario); + CarriersUtils.addOrGetCarriers(scenario); return scenario; } @@ -123,7 +120,7 @@ private static void prepareFreightOutputDataAndStats(Scenario scenario, EventsMa final LegHistogram withoutFreight = new LegHistogram(900); withoutFreight.setPopulation(scenario.getPopulation()); - CarrierScoreStats scores = new CarrierScoreStats(carriers, scenario.getConfig().controler().getOutputDirectory()+ "carrier_scores", true); + CarrierScoreStats scores = new CarrierScoreStats(carriers, scenario.getConfig().controller().getOutputDirectory()+ "carrier_scores", true); eventsManager.addHandler(withoutFreight); eventsManager.addHandler(freightOnly); @@ -156,7 +153,7 @@ public MyCarrierPlanStrategyManagerFactory(CarrierVehicleTypes types) { final TravelDisutility travelDisutility = CarrierTravelDisutilities.createBaseDisutility(types, modeTravelTimes.get(TransportMode.car ) ); final LeastCostPathCalculator router = leastCostPathCalculatorFactory.createPathCalculator(network, travelDisutility, modeTravelTimes.get(TransportMode.car)); - final CarrierStrategyManager carrierStrategyManager = FreightUtils.createDefaultCarrierStrategyManager(); + final CarrierStrategyManager carrierStrategyManager = CarrierControlerUtils.createDefaultCarrierStrategyManager(); carrierStrategyManager.setMaxPlansPerAgent(5); carrierStrategyManager.addStrategy(new GenericPlanStrategyImpl<>(new BestPlanSelector<>()), null, 0.95); diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerPlansFromConfig.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerPlansFromConfig.java similarity index 96% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerPlansFromConfig.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerPlansFromConfig.java index a8f38ac7adc..e2541d937bb 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerPlansFromConfig.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerPlansFromConfig.java @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; +package org.matsim.freight.carriers.usecases.chessboard; import org.matsim.core.controler.Controler; diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerPlansFromScratch.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerPlansFromScratch.java similarity index 77% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerPlansFromScratch.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerPlansFromScratch.java index 8de9c700aab..4e376f29d57 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerPlansFromScratch.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerPlansFromScratch.java @@ -19,11 +19,11 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; +package org.matsim.freight.carriers.usecases.chessboard; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -40,13 +40,13 @@ public static void main(String[] args) { ActivityParams workParams = new ActivityParams("work"); workParams.setTypicalDuration(60 * 60 * 8); - config.planCalcScore().addActivityParams(workParams); + config.scoring().addActivityParams(workParams); ActivityParams homeParams = new ActivityParams("home"); homeParams.setTypicalDuration(16 * 60 * 60); - config.planCalcScore().addActivityParams(homeParams); + config.scoring().addActivityParams(homeParams); config.global().setCoordinateSystem("EPSG:32632"); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(2); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(2); config.network().setInputFile(NETWORK_FILENAME); config.plans().setInputFile(PLANS_FILENAME); @@ -59,15 +59,15 @@ public static void main(String[] args) { reRoute.setWeight(0.5); // reRoute.setDisableAfter(300); - config.strategy().setMaxAgentPlanMemorySize(5); - config.strategy().addStrategySettings(bestScore); - config.strategy().addStrategySettings(reRoute); + config.replanning().setMaxAgentPlanMemorySize(5); + config.replanning().addStrategySettings(bestScore); + config.replanning().addStrategySettings(reRoute); // Controler controler = new Controler(config); - controler.getConfig().controler().setWriteEventsInterval(1); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(1); + controler.getConfig().controller().setCreateGraphs(false); //Select how to react of not empty output directory - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); // controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists); controler.run(); diff --git a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/SelectBestPlanAndOptimizeItsVehicleRouteFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/SelectBestPlanAndOptimizeItsVehicleRouteFactory.java similarity index 94% rename from contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/SelectBestPlanAndOptimizeItsVehicleRouteFactory.java rename to contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/SelectBestPlanAndOptimizeItsVehicleRouteFactory.java index b04a3d526a2..0051af3de81 100644 --- a/contribs/freight/src/main/java/org/matsim/contrib/freight/usecases/chessboard/SelectBestPlanAndOptimizeItsVehicleRouteFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/SelectBestPlanAndOptimizeItsVehicleRouteFactory.java @@ -19,10 +19,7 @@ * */ -package org.matsim.contrib.freight.usecases.chessboard; - -import java.net.URL; -import java.util.Collection; +package org.matsim.freight.carriers.usecases.chessboard; import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; @@ -33,14 +30,7 @@ import com.graphhopper.jsprit.core.problem.vehicle.Vehicle; import com.graphhopper.jsprit.core.util.Solutions; import com.graphhopper.jsprit.io.algorithm.VehicleRoutingAlgorithms; - import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierPlan; -import org.matsim.contrib.freight.carrier.CarrierVehicleTypes; -import org.matsim.contrib.freight.jsprit.MatsimJspritFactory; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts; -import org.matsim.contrib.freight.jsprit.NetworkRouter; import org.matsim.core.replanning.GenericPlanStrategy; import org.matsim.core.replanning.GenericPlanStrategyImpl; import org.matsim.core.replanning.ReplanningContext; @@ -49,6 +39,15 @@ import org.matsim.core.router.util.TravelTime; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierPlan; +import org.matsim.freight.carriers.CarrierVehicleTypes; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.freight.carriers.jsprit.NetworkRouter; + +import java.net.URL; +import java.util.Collection; final class SelectBestPlanAndOptimizeItsVehicleRouteFactory { diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/FreightConfigGroupTest.java b/contribs/freight/src/test/java/org/matsim/contrib/freight/FreightConfigGroupTest.java deleted file mode 100644 index 6dccd19f6b3..00000000000 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/FreightConfigGroupTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.matsim.contrib.freight; - -import org.junit.Assert; -import org.junit.Test; -import org.matsim.contrib.freight.FreightConfigGroup.UseDistanceConstraintForTourPlanning; -import org.matsim.core.config.Config; -import org.matsim.core.config.ConfigReader; -import org.matsim.core.config.ConfigUtils; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.Map; - -/** - * @author mrieser / Simunto - */ -public class FreightConfigGroupTest { - - @Test - public void test_allParametersAreWrittenToXml() { - FreightConfigGroup freight = new FreightConfigGroup(); - Map params = freight.getParams(); - - Assert.assertTrue(params.containsKey(FreightConfigGroup.CARRIERS_FILE)); - Assert.assertTrue(params.containsKey(FreightConfigGroup.CARRIERS_VEHICLE_TYPE)); - Assert.assertTrue(params.containsKey(FreightConfigGroup.VEHICLE_ROUTING_ALGORITHM)); - Assert.assertTrue(params.containsKey(FreightConfigGroup.TRAVEL_TIME_SLICE_WIDTH)); - Assert.assertTrue(params.containsKey(FreightConfigGroup.USE_DISTANCE_CONSTRAINT)); - } - - @Test - public void test_configXmlCanBeParsed() { - FreightConfigGroup freight = new FreightConfigGroup(); - Config config = ConfigUtils.createConfig(freight); - - String xml = "\n" + - "\n" + - "\n" + - " \t\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - - InputStream is = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - - new ConfigReader(config).parse(is); - - Assert.assertEquals("/path/to/carriers.xml", freight.getCarriersFile()); - Assert.assertEquals("/path/to/carriersVehicleTypes.xml", freight.getCarriersVehicleTypesFile()); - Assert.assertEquals("/path/to/carriersRoutingAlgorithm.xml", freight.getVehicleRoutingAlgorithmFile()); - Assert.assertEquals(3600.0, freight.getTravelTimeSliceWidth(), 1e-8); - Assert.assertEquals(UseDistanceConstraintForTourPlanning.basedOnEnergyConsumption, freight.getUseDistanceConstraintForTourPlanning()); - } - -} \ No newline at end of file diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV1Test.java b/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV1Test.java deleted file mode 100644 index 10d1d752c7d..00000000000 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV1Test.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * *********************************************************************** * - * * project: org.matsim.* - * * ${file_name} - * * * - * * *********************************************************************** * - * * * - * * copyright : (C) ${year} 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 * - * * * - * * *********************************************************************** - * - * ${filecomment} - * ${package_declaration} - * - * ${typecomment} - * ${type_declaration} - */ - -package org.matsim.contrib.freight.carrier; - -import org.junit.Rule; -import org.junit.Test; -import org.matsim.api.core.v01.Id; -import org.matsim.testcases.MatsimTestUtils; -import org.matsim.vehicles.VehicleType; -import org.matsim.vehicles.VehicleUtils; - -/** - */ -public class CarrierPlanXmlWriterV1Test { - - @Rule - public MatsimTestUtils testUtils = new MatsimTestUtils(); - - @Test - public void testCarrierPlanWriterWrites() { - - CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); - new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( testUtils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); - VehicleType defaultVehicleType = VehicleUtils.getFactory().createVehicleType( Id.create("default", VehicleType.class ) ); - carrierVehicleTypes.getVehicleTypes().put( defaultVehicleType.getId(), defaultVehicleType ); - - Carriers carriers = new Carriers(); - CarrierPlanReaderV1 carrierPlanReaderV1 = new CarrierPlanReaderV1(carriers, carrierVehicleTypes ); - carrierPlanReaderV1.readFile(testUtils.getClassInputDirectory() + "carrierPlansEquils.xml"); - CarrierPlanXmlWriterV1 planWriter = new CarrierPlanXmlWriterV1(carriers.getCarriers().values()); - planWriter.write(testUtils.getOutputDirectory() + "carrierPlansEquilsWritten.xml"); - } - - -} diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriterTest.java b/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriterTest.java deleted file mode 100644 index 32e53807caf..00000000000 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriterTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.matsim.contrib.freight.carrier; - -import org.junit.Rule; -import org.junit.Test; -import org.matsim.testcases.MatsimTestUtils; - -public class CarrierVehicleTypeWriterTest { - - @Rule - public MatsimTestUtils utils = new MatsimTestUtils() ; - - @Test - public void testTypeWriter(){ - CarrierVehicleTypes types = new CarrierVehicleTypes(); - new CarrierVehicleTypeReader(types).readFile(utils.getClassInputDirectory()+ "vehicleTypes.xml"); - final String outputVehTypeFile = utils.getOutputDirectory()+ "vehicleTypesWritten.xml"; - new CarrierVehicleTypeWriter(types).write(outputVehTypeFile); - types.getVehicleTypes().clear(); - new CarrierVehicleTypeReader(types).readFile(outputVehTypeFile); - } -} diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerAlongWithCarriersIT.java b/contribs/freight/src/test/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerAlongWithCarriersIT.java deleted file mode 100644 index c5dc01247e7..00000000000 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/usecases/chessboard/RunPassengerAlongWithCarriersIT.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.matsim.contrib.freight.usecases.chessboard; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.matsim.core.config.Config; -import org.matsim.testcases.MatsimTestUtils; - -public class RunPassengerAlongWithCarriersIT { - - @Rule - public MatsimTestUtils utils = new MatsimTestUtils() ; - - @Test - public void runChessboard() { - try{ - RunPassengerAlongWithCarriers abc = new RunPassengerAlongWithCarriers(); - // --- - Config config = abc.prepareConfig(); - config.controler().setLastIteration( 1 ); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - // --- - abc.run(); - } catch (Exception ee ) { - ee.printStackTrace(); - Assert.fail("something went wrong: " + ee.getMessage()); - } - } - -} diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierEventsReadersTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierEventsReadersTest.java new file mode 100644 index 00000000000..37a4cabaf82 --- /dev/null +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierEventsReadersTest.java @@ -0,0 +1,251 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 2023 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.freight.carriers; + +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.events.Event; +import org.matsim.api.core.v01.network.Link; +import org.matsim.core.api.experimental.events.EventsManager; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.events.EventsUtils; +import org.matsim.core.events.algorithms.EventWriterXML; +import org.matsim.freight.carriers.events.*; +import org.matsim.freight.carriers.events.eventhandler.*; +import org.matsim.testcases.MatsimTestUtils; +import org.matsim.testcases.utils.EventsCollector; +import org.matsim.vehicles.Vehicle; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; + + +/** + * @author Kai Martins-Turner (kturner) + * @author Niclas Richter (nixlaos) + */ +public class CarrierEventsReadersTest { + + + @Rule + public final MatsimTestUtils utils = new MatsimTestUtils(); + + private final Id linkId = Id.createLinkId("demoLink"); + private final Id linkId2 = Id.createLinkId("demoLink2"); + private final Id carrierId = Id.create("testCarrier", Carrier.class); + private final Id vehicleId = Id.createVehicleId("myVehicle"); + + private final Id tourId = Id.create("myCarrierTour", Tour.class); + private final CarrierService service = CarrierService.Builder.newInstance(Id.create("service42", CarrierService.class), linkId2 ).build(); + private final CarrierShipment shipment = CarrierShipment.Builder.newInstance(Id.create("shipment11", CarrierShipment.class), linkId, linkId2,7 ).build(); + + private final List carrierEvents = List.of( + new CarrierTourStartEvent(10, carrierId, linkId, vehicleId, tourId), + new CarrierTourEndEvent(500, carrierId, linkId, vehicleId, tourId), + new CarrierServiceStartEvent(20, carrierId, service, vehicleId), + new CarrierServiceEndEvent(25, carrierId, service, vehicleId), + new CarrierShipmentPickupStartEvent(100, carrierId, shipment, vehicleId), + new CarrierShipmentPickupEndEvent(115, carrierId, shipment, vehicleId), + new CarrierShipmentDeliveryStartEvent(210, carrierId, shipment, vehicleId), + new CarrierShipmentDeliveryEndEvent(225, carrierId, shipment, vehicleId) + ); + + @Test + public void testWriteReadServiceBasedEvents() { + EventsManager eventsManager1 = EventsUtils.createEventsManager(); + EventsManager eventsManager2 = EventsUtils.createEventsManager(); + EventsCollector collector1 = new EventsCollector(); + EventsCollector collector2 = new EventsCollector(); + + eventsManager1.addHandler(collector1); + eventsManager1.initProcessing(); + CarrierEventsReaders.createEventsReader(eventsManager1) + .readFile(utils.getClassInputDirectory() + "serviceBasedEvents.xml"); + eventsManager1.finishProcessing(); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + EventWriterXML writer = new EventWriterXML(outputStream); + collector1.getEvents().forEach(writer::handleEvent); + writer.closeFile(); + + eventsManager2.addHandler(collector2); + eventsManager2.initProcessing(); + CarrierEventsReaders.createEventsReader(eventsManager2) + .readStream(new ByteArrayInputStream(outputStream.toByteArray()), ControllerConfigGroup.EventsFileFormat.xml); + eventsManager2.finishProcessing(); + + Assert.assertEquals(collector1.getEvents(), collector2.getEvents()); + } + + + @Test + public void testReadServiceBasedEvents() { + + EventsManager eventsManager = EventsUtils.createEventsManager(); + TestEventHandlerTours eventHandlerTours = new TestEventHandlerTours(); + TestEventHandlerServices eventHandlerServices = new TestEventHandlerServices(); + + eventsManager.addHandler(eventHandlerTours); + eventsManager.addHandler(eventHandlerServices); + eventsManager.initProcessing(); + CarrierEventsReaders.createEventsReader(eventsManager) + .readFile(utils.getClassInputDirectory() + "serviceBasedEvents.xml"); + eventsManager.finishProcessing(); + + Assert.assertEquals("Number of tour related carrier events is not correct", 4 , eventHandlerTours.handledEvents.size()); + Assert.assertEquals("Number of service related carrier events is not correct", 14 , eventHandlerServices.handledEvents.size()); + } + + @Test + public void testWriteReadShipmentBasedEvents() { + EventsManager eventsManager1 = EventsUtils.createEventsManager(); + EventsManager eventsManager2 = EventsUtils.createEventsManager(); + EventsCollector collector1 = new EventsCollector(); + EventsCollector collector2 = new EventsCollector(); + + eventsManager1.addHandler(collector1); + eventsManager1.initProcessing(); + CarrierEventsReaders.createEventsReader(eventsManager1) + .readFile(utils.getClassInputDirectory() + "shipmentBasedEvents.xml"); + eventsManager1.finishProcessing(); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + EventWriterXML writer = new EventWriterXML(outputStream); + collector1.getEvents().forEach(writer::handleEvent); + writer.closeFile(); + + eventsManager2.addHandler(collector2); + eventsManager2.initProcessing(); + CarrierEventsReaders.createEventsReader(eventsManager2) + .readStream(new ByteArrayInputStream(outputStream.toByteArray()), ControllerConfigGroup.EventsFileFormat.xml); + eventsManager2.finishProcessing(); + + Assert.assertEquals(collector1.getEvents(), collector2.getEvents()); + } + + @Test + public void testReadShipmentBasedEvents() { + + EventsManager eventsManager = EventsUtils.createEventsManager(); + TestEventHandlerTours eventHandlerTours = new TestEventHandlerTours(); + TestEventHandlerShipments testEventHandlerShipments = new TestEventHandlerShipments(); + + eventsManager.addHandler(eventHandlerTours); + eventsManager.addHandler(testEventHandlerShipments); + eventsManager.initProcessing(); + CarrierEventsReaders.createEventsReader(eventsManager) + .readFile(utils.getClassInputDirectory() + "shipmentBasedEvents.xml"); + eventsManager.finishProcessing(); + + Assert.assertEquals("Number of tour related carrier events is not correct", 2 , eventHandlerTours.handledEvents.size()); + Assert.assertEquals("Number of shipments related carrier events is not correct", 20 , testEventHandlerShipments.handledEvents.size()); + } + + + /** + * This test is testing the reader with some locally created events (see above). + * This test is inspired by the DrtEventsReaderTest from michalm. + */ + @Test + public void testReader() { + var outputStream = new ByteArrayOutputStream(); + EventWriterXML writer = new EventWriterXML(outputStream); + carrierEvents.forEach(writer::handleEvent); + writer.closeFile(); + + EventsManager eventsManager = EventsUtils.createEventsManager(); + TestEventHandlerTours eventHandlerTours = new TestEventHandlerTours(); + TestEventHandlerServices eventHandlerServices = new TestEventHandlerServices(); + TestEventHandlerShipments eventHandlerShipments = new TestEventHandlerShipments(); + + eventsManager.addHandler(eventHandlerTours); + eventsManager.addHandler(eventHandlerServices); + eventsManager.addHandler(eventHandlerShipments); + + eventsManager.initProcessing(); + CarrierEventsReaders.createEventsReader(eventsManager) + .readStream(new ByteArrayInputStream(outputStream.toByteArray()), + ControllerConfigGroup.EventsFileFormat.xml); + eventsManager.finishProcessing(); + + var handledEvents = new ArrayList(); + handledEvents.addAll(eventHandlerTours.handledEvents); + handledEvents.addAll(eventHandlerServices.handledEvents); + handledEvents.addAll(eventHandlerShipments.handledEvents); + + //Please note: This test is sensitive to the order of events as they are added in carrierEvents (input) and the resukts of the handler... + Assert.assertArrayEquals(carrierEvents.toArray(), handledEvents.toArray()); + } + + private static class TestEventHandlerTours + implements CarrierTourStartEventHandler, CarrierTourEndEventHandler { + private final List handledEvents = new ArrayList<>(); + + + @Override public void handleEvent(CarrierTourEndEvent event) { + handledEvents.add(event); + } + + @Override public void handleEvent(CarrierTourStartEvent event) { + handledEvents.add(event); + } + } + + private static class TestEventHandlerServices + implements CarrierServiceStartEventHandler, CarrierServiceEndEventHandler { + private final List handledEvents = new ArrayList<>(); + + @Override public void handleEvent(CarrierServiceEndEvent event) { + handledEvents.add(event); + } + + @Override public void handleEvent(CarrierServiceStartEvent event) { + handledEvents.add(event); + } + + } + + private static class TestEventHandlerShipments + implements CarrierShipmentDeliveryStartEventHandler, CarrierShipmentDeliveryEndEventHandler, CarrierShipmentPickupStartEventHandler, CarrierShipmentPickupEndEventHandler { + private final List handledEvents = new ArrayList<>(); + + + @Override public void handleEvent(CarrierShipmentDeliveryEndEvent event) { + handledEvents.add(event); + } + + @Override public void handleEvent(CarrierShipmentPickupEndEvent event) { + handledEvents.add(event); + } + + @Override public void handleEvent(CarrierShipmentDeliveryStartEvent event) { + handledEvents.add(event); + } + + @Override public void handleEvent(CarrierShipmentPickupStartEvent event) { + handledEvents.add(event); + } + } +} diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierModuleTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierModuleTest.java similarity index 52% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierModuleTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierModuleTest.java index 4a2015aa13b..69938d9c14d 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierModuleTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierModuleTest.java @@ -1,48 +1,51 @@ -/* *********************************************************************** * - * project: org.matsim.* - * *********************************************************************** * - * * - * copyright : (C) 2007 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carrier; +package org.matsim.freight.carriers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.controler.CarrierModule; -import org.matsim.contrib.freight.controler.CarrierStrategyManager; -import org.matsim.contrib.freight.mobsim.DistanceScoringFunctionFactoryForTests; -import org.matsim.contrib.freight.mobsim.StrategyManagerFactoryForTests; -import org.matsim.contrib.freight.controler.CarrierScoringFunctionFactory; -import org.matsim.contrib.freight.controler.FreightUtils; 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.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.controler.CarrierModule; +import org.matsim.freight.carriers.controler.CarrierScoringFunctionFactory; +import org.matsim.freight.carriers.controler.CarrierStrategyManager; +import org.matsim.freight.carriers.mobsim.DistanceScoringFunctionFactoryForTests; +import org.matsim.freight.carriers.mobsim.StrategyManagerFactoryForTests; import org.matsim.testcases.MatsimTestUtils; public class CarrierModuleTest { Controler controler; - FreightConfigGroup freightConfigGroup; + FreightCarriersConfigGroup freightCarriersConfigGroup; @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); @@ -50,28 +53,28 @@ public class CarrierModuleTest { @Before public void setUp(){ Config config = ConfigUtils.createConfig() ; - PlanCalcScoreConfigGroup.ActivityParams workParams = new PlanCalcScoreConfigGroup.ActivityParams("w"); + ScoringConfigGroup.ActivityParams workParams = new ScoringConfigGroup.ActivityParams("w"); workParams.setTypicalDuration(60 * 60 * 8); - config.planCalcScore().addActivityParams(workParams); - PlanCalcScoreConfigGroup.ActivityParams homeParams = new PlanCalcScoreConfigGroup.ActivityParams("h"); + config.scoring().addActivityParams(workParams); + ScoringConfigGroup.ActivityParams homeParams = new ScoringConfigGroup.ActivityParams("h"); homeParams.setTypicalDuration(16 * 60 * 60); - config.planCalcScore().addActivityParams(homeParams); + config.scoring().addActivityParams(homeParams); config.global().setCoordinateSystem("EPSG:32632"); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); config.network().setInputFile( testUtils.getClassInputDirectory() + "network.xml" ); config.plans().setInputFile( testUtils.getClassInputDirectory() + "plans100.xml" ); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - config.controler().setWritePlansInterval(1); - config.controler().setCreateGraphs(false); - freightConfigGroup = ConfigUtils.addOrGetModule( config, FreightConfigGroup.class ) ; - freightConfigGroup.setCarriersFile( testUtils.getClassInputDirectory() + "carrierPlansEquils.xml"); - freightConfigGroup.setCarriersVehicleTypesFile( testUtils.getClassInputDirectory() + "vehicleTypes.xml"); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setWritePlansInterval(1); + config.controller().setCreateGraphs(false); + freightCarriersConfigGroup = ConfigUtils.addOrGetModule( config, FreightCarriersConfigGroup.class ) ; + freightCarriersConfigGroup.setCarriersFile( testUtils.getClassInputDirectory() + "carrierPlansEquils.xml"); + freightCarriersConfigGroup.setCarriersVehicleTypesFile( testUtils.getClassInputDirectory() + "vehicleTypes.xml"); Scenario scenario = ScenarioUtils.loadScenario( config ); - FreightUtils.loadCarriersAccordingToFreightConfig( scenario ); + CarriersUtils.loadCarriersAccordingToFreightConfig( scenario ); controler = new Controler(scenario); } diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java similarity index 75% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1Test.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java index 43b8b89c8a3..10f95ad59cc 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java @@ -1,34 +1,33 @@ /* - * *********************************************************************** * - * * project: org.matsim.* - * * CarrierPlanReaderV1Test.java - * * * - * * *********************************************************************** * - * * * - * * copyright : (C) ${year} by the members listed in the COPYING, * - * * LICENSE and WARRANTY file. * - * * email : info at matsim dot org * - * * * - * * *********************************************************************** * - * * * - * * This program is free software; you can redistribute it and/or modify * - * * it under the terms of the GNU General Public License as published by * - * * the Free Software Foundation; either version 2 of the License, or * - * * (at your option) any later version. * - * * See also COPYING, LICENSE and WARRANTY file * - * * * - * * *********************************************************************** + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carrier; +package org.matsim.freight.carriers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Tour.Leg; import org.matsim.core.population.routes.NetworkRoute; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.Tour.Leg; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java similarity index 76% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2Test.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java index 6b2a8192004..29887701aa4 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java @@ -1,23 +1,47 @@ -package org.matsim.contrib.freight.carrier; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.*; - -import org.junit.*; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; + +import org.junit.Assert; +import org.junit.Before; +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.TransportMode; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; -import org.matsim.contrib.freight.controler.FreightUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.gbl.Gbl; import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.Vehicle; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.*; + public class CarrierPlanXmlReaderV2Test { @Rule @@ -44,15 +68,15 @@ public void test_whenReadingServices_nuOfServicesIsCorrect(){ @Test public void test_whenReadingCarrier_itReadsTypeIdsCorrectly(){ - CarrierVehicle light = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); + CarrierVehicle light = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); Gbl.assertNotNull(light); Assert.assertEquals("light",light.getVehicleTypeId().toString()); - CarrierVehicle medium = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); + CarrierVehicle medium = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); Gbl.assertNotNull(medium); Assert.assertEquals("medium",medium.getVehicleTypeId().toString()); - CarrierVehicle heavy = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); + CarrierVehicle heavy = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); Gbl.assertNotNull(heavy); Assert.assertEquals("heavy",heavy.getVehicleTypeId().toString()); } @@ -139,13 +163,13 @@ private boolean exactlyTheseVehiclesAreInVehicleCollection(List> asL @Test public void test_CarrierHasAttributes(){ - Assert.assertEquals((TransportMode.drt),CarrierUtils.getCarrierMode(testCarrier)); - Assert.assertEquals(50,CarrierUtils.getJspritIterations(testCarrier)); + Assert.assertEquals((TransportMode.drt), CarriersUtils.getCarrierMode(testCarrier)); + Assert.assertEquals(50, CarriersUtils.getJspritIterations(testCarrier)); } @Test public void test_ServicesAndShipmentsHaveAttributes(){ - Object serviceCustomerAtt = testCarrier.getServices().get(Id.create("serv1",CarrierService.class)).getAttributes().getAttribute("customer"); + Object serviceCustomerAtt = testCarrier.getServices().get(Id.create("serv1", CarrierService.class)).getAttributes().getAttribute("customer"); Assert.assertNotNull(serviceCustomerAtt); Assert.assertEquals("someRandomCustomer", serviceCustomerAtt); Object shipmentCustomerAtt = testCarrier.getShipments().get(Id.create("s1",CarrierShipment.class)).getAttributes().getAttribute("customer"); @@ -157,7 +181,7 @@ public void test_ServicesAndShipmentsHaveAttributes(){ public void test_readStream() { Config config = ConfigUtils.createConfig(); Scenario scenario = ScenarioUtils.createScenario(config); - Carriers carriers = FreightUtils.addOrGetCarriers(scenario); + Carriers carriers = CarriersUtils.addOrGetCarriers(scenario); String xml = """ diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2WithDtdTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java similarity index 73% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2WithDtdTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java index 1df7bfc15a0..64a078eecb5 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2WithDtdTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java @@ -1,13 +1,31 @@ -package org.matsim.contrib.freight.carrier; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; + +import org.junit.*; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; import org.matsim.core.gbl.Gbl; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.Vehicle; @@ -40,15 +58,15 @@ public void test_whenReadingServices_nuOfServicesIsCorrect(){ @Test public void test_whenReadingCarrier_itReadsTypeIdsCorrectly(){ - CarrierVehicle light = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); + CarrierVehicle light = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); Gbl.assertNotNull(light); Assert.assertEquals("light",light.getVehicleTypeId().toString()); - CarrierVehicle medium = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); + CarrierVehicle medium = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); Gbl.assertNotNull(medium); Assert.assertEquals("medium",medium.getVehicleTypeId().toString()); - CarrierVehicle heavy = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); + CarrierVehicle heavy = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); Gbl.assertNotNull(heavy); Assert.assertEquals("heavy",heavy.getVehicleTypeId().toString()); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV1Test.java new file mode 100644 index 00000000000..21b0ba0ed8f --- /dev/null +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV1Test.java @@ -0,0 +1,55 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; + +import org.junit.Rule; +import org.junit.Test; +import org.matsim.api.core.v01.Id; +import org.matsim.freight.carriers.*; +import org.matsim.testcases.MatsimTestUtils; +import org.matsim.vehicles.VehicleType; +import org.matsim.vehicles.VehicleUtils; + +/** + */ +public class CarrierPlanXmlWriterV1Test { + + @Rule + public MatsimTestUtils testUtils = new MatsimTestUtils(); + + @Test + public void testCarrierPlanWriterWrites() { + + CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); + new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( testUtils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); + VehicleType defaultVehicleType = VehicleUtils.getFactory().createVehicleType( Id.create("default", VehicleType.class ) ); + carrierVehicleTypes.getVehicleTypes().put( defaultVehicleType.getId(), defaultVehicleType ); + + Carriers carriers = new Carriers(); + CarrierPlanReaderV1 carrierPlanReaderV1 = new CarrierPlanReaderV1(carriers, carrierVehicleTypes ); + carrierPlanReaderV1.readFile(testUtils.getClassInputDirectory() + "carrierPlansEquils.xml"); + CarrierPlanXmlWriterV1 planWriter = new CarrierPlanXmlWriterV1(carriers.getCarriers().values()); + planWriter.write(testUtils.getOutputDirectory() + "carrierPlansEquilsWritten.xml"); + } + + +} diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java similarity index 72% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2Test.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java index 34bb84d4b0d..f8b84d04382 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java @@ -1,11 +1,33 @@ -package org.matsim.contrib.freight.carrier; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.Vehicle; @@ -42,13 +64,13 @@ public void test_whenReadingServices_nuOfServicesIsCorrect(){ @Test public void test_whenReadingCarrier_itReadsTypeIdsCorrectly(){ - CarrierVehicle light = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); + CarrierVehicle light = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); assertEquals("light",light.getVehicleTypeId().toString()); - CarrierVehicle medium = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); + CarrierVehicle medium = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); assertEquals("medium",medium.getVehicleTypeId().toString()); - CarrierVehicle heavy = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); + CarrierVehicle heavy = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); assertEquals("heavy",heavy.getVehicleTypeId().toString()); } @@ -121,8 +143,8 @@ private boolean exactlyTheseVehiclesAreInVehicleCollection(List> asL @Test public void test_CarrierHasAttributes(){ - assertEquals((TransportMode.drt),CarrierUtils.getCarrierMode(testCarrier)); - assertEquals(50,CarrierUtils.getJspritIterations(testCarrier)); + assertEquals((TransportMode.drt), CarriersUtils.getCarrierMode(testCarrier)); + assertEquals(50, CarriersUtils.getJspritIterations(testCarrier)); } @Test diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java similarity index 73% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2_1Test.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java index ca23da29f27..268bae2dd71 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java @@ -1,12 +1,33 @@ -package org.matsim.contrib.freight.carrier; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; -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.testcases.MatsimTestUtils; import org.matsim.vehicles.Vehicle; @@ -43,13 +64,13 @@ public void test_whenReadingServices_nuOfServicesIsCorrect(){ @Test public void test_whenReadingCarrier_itReadsTypeIdsCorrectly(){ - CarrierVehicle light = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); + CarrierVehicle light = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); assertEquals("light",light.getVehicleTypeId().toString()); - CarrierVehicle medium = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); + CarrierVehicle medium = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); assertEquals("medium",medium.getVehicleTypeId().toString()); - CarrierVehicle heavy = CarrierUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); + CarrierVehicle heavy = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); assertEquals("heavy",heavy.getVehicleTypeId().toString()); } @@ -118,7 +139,7 @@ public void test_whenReadingToursOfPlan1_SpritScoreIsCorrect(){ List plans = new ArrayList(testCarrier.getPlans()); CarrierPlan plan1 = plans.get(0); plan1.getAttributes().getAttribute("jspritScore"); - assertEquals(Double.NaN, FreightUtils.getJspritScore(plan1), testUtils.EPSILON); + assertEquals(Double.NaN, CarriersUtils.getJspritScore(plan1), testUtils.EPSILON); } @Test @@ -126,7 +147,7 @@ public void test_whenReadingToursOfPlan2_jSpritScoreIsCorrect(){ List plans = new ArrayList(testCarrier.getPlans()); CarrierPlan plan2 = plans.get(1); plan2.getAttributes().getAttribute("jspritScore"); - assertEquals(80.0, FreightUtils.getJspritScore(plan2), testUtils.EPSILON); + assertEquals(80.0, CarriersUtils.getJspritScore(plan2), testUtils.EPSILON); } @Test @@ -134,7 +155,7 @@ public void test_whenReadingToursOfPlan3_jSpritIsCorrect(){ List plans = new ArrayList(testCarrier.getPlans()); CarrierPlan plan3 = plans.get(2); plan3.getAttributes().getAttribute("jspritScore"); - assertEquals(105.0, FreightUtils.getJspritScore(plan3), testUtils.EPSILON); + assertEquals(105.0, CarriersUtils.getJspritScore(plan3), testUtils.EPSILON); } @@ -146,8 +167,8 @@ private boolean exactlyTheseVehiclesAreInVehicleCollection(List> asL @Test public void test_CarrierHasAttributes(){ - assertEquals((TransportMode.drt),CarrierUtils.getCarrierMode(testCarrier)); - assertEquals(50,CarrierUtils.getJspritIterations(testCarrier)); + assertEquals((TransportMode.drt), CarriersUtils.getCarrierMode(testCarrier)); + assertEquals(50, CarriersUtils.getJspritIterations(testCarrier)); } @Test diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierReadWriteV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java similarity index 62% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierReadWriteV2_1Test.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java index 6e2d521fc40..50453b95881 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierReadWriteV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java @@ -1,7 +1,29 @@ -package org.matsim.contrib.freight.carrier; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; import org.junit.Rule; import org.junit.Test; +import org.matsim.freight.carriers.*; import org.matsim.testcases.MatsimTestUtils; import java.io.FileNotFoundException; diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoaderTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java similarity index 64% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoaderTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java index cc2866cb29f..aa0a0ec281a 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoaderTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java @@ -1,10 +1,32 @@ -package org.matsim.contrib.freight.carrier; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; +import org.matsim.freight.carriers.*; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; @@ -29,7 +51,7 @@ public void setUp() throws Exception{ public void test_whenLoadingTypes_allAssignmentsInLightVehicleAreCorrectly(){ new CarrierVehicleTypeLoader(carriers).loadVehicleTypes(types); Carrier testCarrier = carriers.getCarriers().get(Id.create("testCarrier", Carrier.class)); - CarrierVehicle v = CarrierUtils.getCarrierVehicle(testCarrier,Id.createVehicleId("lightVehicle")); + CarrierVehicle v = CarriersUtils.getCarrierVehicle(testCarrier,Id.createVehicleId("lightVehicle")); VehicleType vehicleTypeLoaded = v.getType(); Assert.assertNotNull(vehicleTypeLoaded); @@ -48,7 +70,7 @@ public void test_whenLoadingTypes_allAssignmentsInLightVehicleAreCorrectly(){ public void test_whenLoadingTypes_allAssignmentsInMediumVehicleAreCorrectly(){ new CarrierVehicleTypeLoader(carriers).loadVehicleTypes(types); Carrier testCarrier = carriers.getCarriers().get(Id.create("testCarrier", Carrier.class)); - CarrierVehicle v = CarrierUtils.getCarrierVehicle(testCarrier,Id.createVehicleId("mediumVehicle")); + CarrierVehicle v = CarriersUtils.getCarrierVehicle(testCarrier,Id.createVehicleId("mediumVehicle")); VehicleType vehicleTypeLoaded = v.getType(); Assert.assertNotNull(vehicleTypeLoaded); diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java similarity index 73% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java index 6de7487a28f..43c73857e44 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java @@ -1,4 +1,25 @@ -package org.matsim.contrib.freight.carrier; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java similarity index 83% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java index fd016cb0331..6516c4933a8 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierVehicleTypeTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java @@ -1,10 +1,32 @@ -package org.matsim.contrib.freight.carrier; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; +import org.matsim.freight.carriers.CarrierVehicleTypes; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.*; import org.matsim.vehicles.EngineInformation.FuelType; @@ -55,7 +77,7 @@ public void setUp() throws Exception{ engineInformation.setFuelConsumption( 0.015 ); VehicleCapacity capacity = smallType.getCapacity() ; capacity.setWeightInTons( 16 ) ; -// VehicleType smallType = CarrierUtils.CarrierVehicleTypeBuilder.newInstance( smallTypeId, mediumType ) +// VehicleType smallType = CarriersUtils.CarrierVehicleTypeBuilder.newInstance( smallTypeId, mediumType ) smallType.setDescription( "Small Vehicle" ).setMaximumVelocity( 10.0 ) ; types.getVehicleTypes().put( smallType.getId(), smallType ); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeWriterTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeWriterTest.java new file mode 100644 index 00000000000..551c5b6eac8 --- /dev/null +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeWriterTest.java @@ -0,0 +1,45 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; + +import org.junit.Rule; +import org.junit.Test; +import org.matsim.freight.carriers.CarrierVehicleTypeReader; +import org.matsim.freight.carriers.CarrierVehicleTypeWriter; +import org.matsim.freight.carriers.CarrierVehicleTypes; +import org.matsim.testcases.MatsimTestUtils; + +public class CarrierVehicleTypeWriterTest { + + @Rule + public MatsimTestUtils utils = new MatsimTestUtils() ; + + @Test + public void testTypeWriter(){ + CarrierVehicleTypes types = new CarrierVehicleTypes(); + new CarrierVehicleTypeReader(types).readFile(utils.getClassInputDirectory()+ "vehicleTypes.xml"); + final String outputVehTypeFile = utils.getOutputDirectory()+ "vehicleTypesWritten.xml"; + new CarrierVehicleTypeWriter(types).write(outputVehTypeFile); + types.getVehicleTypes().clear(); + new CarrierVehicleTypeReader(types).readFile(outputVehTypeFile); + } +} diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierUtilsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarriersUtilsTest.java similarity index 61% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierUtilsTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/CarriersUtilsTest.java index fa847124348..e6224ced05c 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/carrier/CarrierUtilsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarriersUtilsTest.java @@ -1,37 +1,31 @@ /* - * *********************************************************************** * - * * project: org.matsim.* - * * ${file_name} - * * * - * * *********************************************************************** * - * * * - * * copyright : (C) ${year} by the members listed in the COPYING, * - * * LICENSE and WARRANTY file. * - * * email : info at matsim dot org * - * * * - * * *********************************************************************** * - * * * - * * This program is free software; you can redistribute it and/or modify * - * * it under the terms of the GNU General Public License as published by * - * * the Free Software Foundation; either version 2 of the License, or * - * * (at your option) any later version. * - * * See also COPYING, LICENSE and WARRANTY file * - * * * - * * *********************************************************************** + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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 * + * * + * *********************************************************************** * - * ${filecomment} - * ${package_declaration} - * - * ${typecomment} - * ${type_declaration} */ -package org.matsim.contrib.freight.carrier; +package org.matsim.freight.carriers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; +import org.matsim.freight.carriers.*; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleUtils; @@ -40,7 +34,7 @@ /** */ -public class CarrierUtilsTest { +public class CarriersUtilsTest { @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); @@ -53,14 +47,14 @@ public void testAddAndGetVehicleToCarrier() { // carrierVehicle.setType(VehicleUtils.getDefaultVehicleType()); //add Vehicle - CarrierUtils.addCarrierVehicle(carrier, carrierVehicle); + CarriersUtils.addCarrierVehicle(carrier, carrierVehicle); Assert.assertEquals(1, carrier.getCarrierCapabilities().getCarrierVehicles().size()); CarrierVehicle cv = (CarrierVehicle) carrier.getCarrierCapabilities().getCarrierVehicles().values().toArray()[0]; Assert.assertEquals(VehicleUtils.getDefaultVehicleType(), cv.getType()); Assert.assertEquals(Id.createLinkId("link0"), cv.getLinkId() ); //get Vehicle - CarrierVehicle carrierVehicle1 = CarrierUtils.getCarrierVehicle(carrier, testVehicleId ); + CarrierVehicle carrierVehicle1 = CarriersUtils.getCarrierVehicle(carrier, testVehicleId ); Assert.assertEquals(testVehicleId, carrierVehicle1.getId()); Assert.assertEquals(VehicleUtils.getDefaultVehicleType(), carrierVehicle1.getType()); Assert.assertEquals(Id.createLinkId("link0"), carrierVehicle1.getLinkId() ); @@ -74,14 +68,14 @@ public void testAddAndGetServiceToCarrier() { .setName("service1").setCapacityDemand(15).setServiceDuration(30).build(); //add Service - CarrierUtils.addService(carrier, service1); + CarriersUtils.addService(carrier, service1); Assert.assertEquals(1, carrier.getServices().size()); CarrierService cs1a = (CarrierService) carrier.getServices().values().toArray()[0]; Assert.assertEquals(service1, cs1a); Assert.assertEquals(Id.createLinkId("link0"), cs1a.getLocationLinkId()); //get Service - CarrierService cs1b = CarrierUtils.getService(carrier, serviceId ); + CarrierService cs1b = CarriersUtils.getService(carrier, serviceId ); Assert.assertEquals(serviceId, cs1b.getId()); Assert.assertEquals(service1.getId(), cs1b.getId()); Assert.assertEquals(Id.createLinkId("link0"), cs1b.getLocationLinkId()); @@ -95,14 +89,14 @@ public void testAddAndGetShipmentToCarrier() { CarrierShipment service1 = CarrierShipment.Builder.newInstance(shipmentId,Id.createLinkId("link0"), Id.createLinkId("link1"), 20 ).build(); //add Shipment - CarrierUtils.addShipment(carrier, service1); + CarriersUtils.addShipment(carrier, service1); Assert.assertEquals(1, carrier.getShipments().size()); CarrierShipment carrierShipment1a = (CarrierShipment) carrier.getShipments().values().toArray()[0]; Assert.assertEquals(service1, carrierShipment1a); Assert.assertEquals(Id.createLinkId("link0"), carrierShipment1a.getFrom()); //get Shipment - CarrierShipment carrierShipment1b = CarrierUtils.getShipment(carrier, shipmentId ); + CarrierShipment carrierShipment1b = CarriersUtils.getShipment(carrier, shipmentId ); Assert.assertEquals(shipmentId, carrierShipment1b.getId()); Assert.assertEquals(service1.getId(), carrierShipment1b.getId()); Assert.assertEquals(Id.createLinkId("link0"), carrierShipment1b.getFrom()); @@ -113,10 +107,10 @@ public void testAddAndGetShipmentToCarrier() { public void testGetSetJspritIteration(){ Carrier carrier = new CarrierImpl(Id.create("carrier", Carrier.class)); //jspirtIterations is not set. should return Integer.Min_Value (null is not possible because returning (int) - Assert.assertEquals(Integer.MIN_VALUE, CarrierUtils.getJspritIterations(carrier) ); + Assert.assertEquals(Integer.MIN_VALUE, CarriersUtils.getJspritIterations(carrier) ); - CarrierUtils.setJspritIterations(carrier, 125); - Assert.assertEquals(125, CarrierUtils.getJspritIterations(carrier) ); + CarriersUtils.setJspritIterations(carrier, 125); + Assert.assertEquals(125, CarriersUtils.getJspritIterations(carrier) ); } - + } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java new file mode 100644 index 00000000000..9310bf5716c --- /dev/null +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java @@ -0,0 +1,81 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers; + +import org.junit.Assert; +import org.junit.Test; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigReader; +import org.matsim.core.config.ConfigUtils; +import org.matsim.freight.carriers.FreightCarriersConfigGroup.UseDistanceConstraintForTourPlanning; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +/** + * @author mrieser / Simunto + */ +public class FreightCarriersConfigGroupTest { + + @Test + public void test_allParametersAreWrittenToXml() { + FreightCarriersConfigGroup freight = new FreightCarriersConfigGroup(); + Map params = freight.getParams(); + + Assert.assertTrue(params.containsKey(FreightCarriersConfigGroup.CARRIERS_FILE)); + Assert.assertTrue(params.containsKey(FreightCarriersConfigGroup.CARRIERS_VEHICLE_TYPE)); + Assert.assertTrue(params.containsKey(FreightCarriersConfigGroup.VEHICLE_ROUTING_ALGORITHM)); + Assert.assertTrue(params.containsKey(FreightCarriersConfigGroup.TRAVEL_TIME_SLICE_WIDTH)); + Assert.assertTrue(params.containsKey(FreightCarriersConfigGroup.USE_DISTANCE_CONSTRAINT)); + } + + @Test + public void test_configXmlCanBeParsed() { + FreightCarriersConfigGroup freight = new FreightCarriersConfigGroup(); + Config config = ConfigUtils.createConfig(freight); + + String xml = "\n" + + "\n" + + "\n" + + " \t\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + + InputStream is = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); + + new ConfigReader(config).parse(is); + + Assert.assertEquals("/path/to/carriers.xml", freight.getCarriersFile()); + Assert.assertEquals("/path/to/carriersVehicleTypes.xml", freight.getCarriersVehicleTypesFile()); + Assert.assertEquals("/path/to/carriersRoutingAlgorithm.xml", freight.getVehicleRoutingAlgorithmFile()); + Assert.assertEquals(3600.0, freight.getTravelTimeSliceWidth(), 1e-8); + Assert.assertEquals(UseDistanceConstraintForTourPlanning.basedOnEnergyConsumption, freight.getUseDistanceConstraintForTourPlanning()); + } + +} diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/controler/EquilWithCarrierWithPersonsIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/controler/EquilWithCarrierWithPersonsIT.java similarity index 55% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/controler/EquilWithCarrierWithPersonsIT.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/controler/EquilWithCarrierWithPersonsIT.java index c326e650f8f..648a61edff2 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/controler/EquilWithCarrierWithPersonsIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/controler/EquilWithCarrierWithPersonsIT.java @@ -1,24 +1,25 @@ -/* *********************************************************************** * - * project: org.matsim.* - * EquilWithCarrierTest.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.freight.controler; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.controler; import org.junit.Assert; import org.junit.Before; @@ -26,16 +27,16 @@ import org.junit.Test; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.mobsim.DistanceScoringFunctionFactoryForTests; -import org.matsim.contrib.freight.mobsim.StrategyManagerFactoryForTests; 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.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.mobsim.DistanceScoringFunctionFactoryForTests; +import org.matsim.freight.carriers.mobsim.StrategyManagerFactoryForTests; import org.matsim.testcases.MatsimTestUtils; public class EquilWithCarrierWithPersonsIT { @@ -47,13 +48,13 @@ public class EquilWithCarrierWithPersonsIT { static Config commonConfig( MatsimTestUtils testUtils ) { Config config = ConfigUtils.createConfig(); - config.planCalcScore().addActivityParams( new ActivityParams("w").setTypicalDuration(60 * 60 * 8 ) ); - config.planCalcScore().addActivityParams( new ActivityParams("h").setTypicalDuration(16 * 60 * 60 ) ); + config.scoring().addActivityParams( new ActivityParams("w").setTypicalDuration(60 * 60 * 8 ) ); + config.scoring().addActivityParams( new ActivityParams("h").setTypicalDuration(16 * 60 * 60 ) ); config.global().setCoordinateSystem("EPSG:32632"); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(2); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(2); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); config.network().setInputFile( testUtils.getClassInputDirectory() + "network.xml" ); return config; @@ -64,9 +65,9 @@ public void setUp(){ Config config = commonConfig( testUtils ); config.plans().setInputFile( testUtils.getClassInputDirectory() + "plans100.xml" ); - config.strategy().setMaxAgentPlanMemorySize(5); - config.strategy().addStrategySettings( new StrategySettings().setStrategyName("BestScore" ).setWeight(1.0 ) ); - config.strategy().addStrategySettings( new StrategySettings().setStrategyName("ReRoute" ).setWeight(0.0 ).setDisableAfter(300 ) ); + config.replanning().setMaxAgentPlanMemorySize(5); + config.replanning().addStrategySettings( new StrategySettings().setStrategyName("BestScore" ).setWeight(1.0 ) ); + config.replanning().addStrategySettings( new StrategySettings().setStrategyName("ReRoute" ).setWeight(0.0 ).setDisableAfter(300 ) ); Scenario scenario = commonScenario( config, testUtils ); @@ -79,7 +80,7 @@ static Scenario commonScenario( Config config, MatsimTestUtils testUtils ){ CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( testUtils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); - Carriers carriers = FreightUtils.addOrGetCarriers(scenario ); + Carriers carriers = CarriersUtils.addOrGetCarriers(scenario ); new CarrierPlanXmlReader( carriers, carrierVehicleTypes ).readFile( testUtils.getClassInputDirectory() + "carrierPlansEquils.xml" ); return scenario; } diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/controler/EquilWithCarrierWithoutPersonsIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/controler/EquilWithCarrierWithoutPersonsIT.java similarity index 62% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/controler/EquilWithCarrierWithoutPersonsIT.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/controler/EquilWithCarrierWithoutPersonsIT.java index b14d8a8b9df..51a28a88ed0 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/controler/EquilWithCarrierWithoutPersonsIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/controler/EquilWithCarrierWithoutPersonsIT.java @@ -1,41 +1,43 @@ -/* *********************************************************************** * - * project: org.matsim.* - * EquilWithCarrierTest.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.freight.controler; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.controler; 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.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.Tour; -import org.matsim.contrib.freight.mobsim.DistanceScoringFunctionFactoryForTests; -import org.matsim.contrib.freight.mobsim.StrategyManagerFactoryForTests; -import org.matsim.contrib.freight.mobsim.TimeScoringFunctionFactoryForTests; 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.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.Tour; +import org.matsim.freight.carriers.mobsim.DistanceScoringFunctionFactoryForTests; +import org.matsim.freight.carriers.mobsim.StrategyManagerFactoryForTests; +import org.matsim.freight.carriers.mobsim.TimeScoringFunctionFactoryForTests; import org.matsim.testcases.MatsimTestUtils; public class EquilWithCarrierWithoutPersonsIT { @@ -70,7 +72,7 @@ public void testWithoutCarrierRoutes() { Scenario scenario = EquilWithCarrierWithPersonsIT.commonScenario( config, testUtils ); // set the routes to null: - for( Carrier carrier : FreightUtils.getCarriers( scenario ).getCarriers().values() ){ + for( Carrier carrier : CarriersUtils.getCarriers( scenario ).getCarriers().values() ){ for( ScheduledTour tour : carrier.getSelectedPlan().getScheduledTours() ){ for( Tour.TourElement tourElement : tour.getTour().getTourElements() ){ if ( tourElement instanceof Tour.Leg ) { @@ -108,21 +110,21 @@ public void install() { }); controler.run(); - Carrier carrier1 = FreightUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier1", Carrier.class)); + Carrier carrier1 = CarriersUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier1", Carrier.class)); Assert.assertEquals(-170000.0, carrier1.getSelectedPlan().getScore(), 0.0 ); - Carrier carrier2 = FreightUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier2", Carrier.class)); + Carrier carrier2 = CarriersUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier2", Carrier.class)); Assert.assertEquals(-85000.0, carrier2.getSelectedPlan().getScore(), 0.0 ); } @Test public void testScoringInSecondsWoTimeWindowEnforcement(){ setUp(); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule( controler.getConfig(), FreightConfigGroup.class ); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule( controler.getConfig(), FreightCarriersConfigGroup.class ); if ( false ){ - freightConfigGroup.setTimeWindowHandling( FreightConfigGroup.TimeWindowHandling.enforceBeginnings ); + freightCarriersConfigGroup.setTimeWindowHandling( FreightCarriersConfigGroup.TimeWindowHandling.enforceBeginnings ); } else{ - freightConfigGroup.setTimeWindowHandling( FreightConfigGroup.TimeWindowHandling.ignore ); + freightCarriersConfigGroup.setTimeWindowHandling( FreightCarriersConfigGroup.TimeWindowHandling.ignore ); } controler.addOverridingModule( new CarrierModule( ) ); controler.addOverridingModule(new AbstractModule() { @@ -134,10 +136,10 @@ public void install() { }); controler.run(); - Carrier carrier1 = FreightUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier1", Carrier.class)); + Carrier carrier1 = CarriersUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier1", Carrier.class)); Assert.assertEquals(-240.0, carrier1.getSelectedPlan().getScore(), 2.0); - Carrier carrier2 = FreightUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier2", Carrier.class)); + Carrier carrier2 = CarriersUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier2", Carrier.class)); Assert.assertEquals(0.0, carrier2.getSelectedPlan().getScore(), 0.0 ); } @@ -145,11 +147,11 @@ public void install() { @Test public void testScoringInSecondsWTimeWindowEnforcement(){ setUp(); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule( controler.getConfig(), FreightConfigGroup.class ); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule( controler.getConfig(), FreightCarriersConfigGroup.class ); if ( true ){ - freightConfigGroup.setTimeWindowHandling( FreightConfigGroup.TimeWindowHandling.enforceBeginnings ); + freightCarriersConfigGroup.setTimeWindowHandling( FreightCarriersConfigGroup.TimeWindowHandling.enforceBeginnings ); } else{ - freightConfigGroup.setTimeWindowHandling( FreightConfigGroup.TimeWindowHandling.ignore ); + freightCarriersConfigGroup.setTimeWindowHandling( FreightCarriersConfigGroup.TimeWindowHandling.ignore ); } final CarrierModule carrierModule = new CarrierModule( ); controler.addOverridingModule( carrierModule ); @@ -162,10 +164,10 @@ public void install() { }); controler.run(); - Carrier carrier1 = FreightUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier1", Carrier.class)); + Carrier carrier1 = CarriersUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier1", Carrier.class)); Assert.assertEquals(-4873.0, carrier1.getSelectedPlan().getScore(), 2.0); - Carrier carrier2 = FreightUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier2", Carrier.class)); + Carrier carrier2 = CarriersUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier2", Carrier.class)); Assert.assertEquals(0.0, carrier2.getSelectedPlan().getScore(), 0.0 ); } @@ -173,11 +175,11 @@ public void install() { @Test public void testScoringInSecondsWithWithinDayRescheduling(){ setUp(); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule( controler.getConfig(), FreightConfigGroup.class ); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule( controler.getConfig(), FreightCarriersConfigGroup.class ); if ( true ){ - freightConfigGroup.setTimeWindowHandling( FreightConfigGroup.TimeWindowHandling.enforceBeginnings ); + freightCarriersConfigGroup.setTimeWindowHandling( FreightCarriersConfigGroup.TimeWindowHandling.enforceBeginnings ); } else{ - freightConfigGroup.setTimeWindowHandling( FreightConfigGroup.TimeWindowHandling.ignore ); + freightCarriersConfigGroup.setTimeWindowHandling( FreightCarriersConfigGroup.TimeWindowHandling.ignore ); } CarrierModule carrierControler = new CarrierModule(); controler.addOverridingModule(carrierControler); @@ -190,7 +192,7 @@ public void install() { }); controler.run(); - Carrier carrier1 = FreightUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier1", Carrier.class)); + Carrier carrier1 = CarriersUtils.getCarriers(controler.getScenario()).getCarriers().get(Id.create("carrier1", Carrier.class)); Assert.assertEquals(-4871.0, carrier1.getSelectedPlan().getScore(), 2.0); } diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/DistanceConstraintFromVehiclesFileTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java similarity index 86% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/DistanceConstraintFromVehiclesFileTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java index 64104984286..71b63d36035 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/DistanceConstraintFromVehiclesFileTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2020 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.jsprit; +package org.matsim.freight.carriers.jsprit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -28,14 +28,9 @@ import org.junit.Test; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.FreightConfigGroup.UseDistanceConstraintForTourPlanning; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; -import org.matsim.contrib.freight.controler.FreightUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup.CompressionType; +import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.population.routes.NetworkRoute; @@ -43,6 +38,9 @@ import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.FreightCarriersConfigGroup.UseDistanceConstraintForTourPlanning; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; @@ -81,7 +79,7 @@ public class DistanceConstraintFromVehiclesFileTest { public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -91,7 +89,7 @@ public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, CarrierVehicleTypes allVehicleTypes = new CarrierVehicleTypes(); CarrierVehicleTypes vehicleTypes = new CarrierVehicleTypes(); - new CarrierVehicleTypeReader(allVehicleTypes).readFile(ConfigUtils.addOrGetModule(config, FreightConfigGroup.class).getCarriersVehicleTypesFile()); + new CarrierVehicleTypeReader(allVehicleTypes).readFile(ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class).getCarriersVehicleTypesFile()); //Filter for V1 vehicleTypes. for (VehicleType vehicleType : allVehicleTypes.getVehicleTypes().values()) { @@ -102,16 +100,16 @@ public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV1 = CarrierUtils.createCarrier(Id.create("Carrier_Version1", Carrier.class)); + Carrier carrierV1 = CarriersUtils.createCarrier(Id.create("Carrier_Version1", Carrier.class)); carriers.addCarrier(addTwoServicesToCarrier(carrierV1)); createCarriers(carriers, fleetSize, carrierV1, vehicleTypes); scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV1, 25); + CarriersUtils.setJspritIterations(carrierV1, 25); - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); Assert.assertEquals("Not the correct amout of scheduled tours", 1, carrierV1.getSelectedPlan().getScheduledTours().size()); @@ -130,7 +128,7 @@ public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, MatsimTestUtils.EPSILON); Assert.assertEquals("Wrong maximum distance of the tour of this vehicleType", 30000, maxDistance_vehicleType_SmallV1, MatsimTestUtils.EPSILON); - + double distanceTour = 0.0; List elements = carrierV1.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); @@ -154,7 +152,7 @@ public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, @Test public final void CarrierLargeBatteryTest_Version2() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -164,7 +162,7 @@ public final void CarrierLargeBatteryTest_Version2() throws ExecutionException, CarrierVehicleTypes allVehicleTypes = new CarrierVehicleTypes(); CarrierVehicleTypes vehicleTypes = new CarrierVehicleTypes(); - new CarrierVehicleTypeReader(allVehicleTypes).readFile(ConfigUtils.addOrGetModule(config, FreightConfigGroup.class).getCarriersVehicleTypesFile()); + new CarrierVehicleTypeReader(allVehicleTypes).readFile(ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class).getCarriersVehicleTypesFile()); //Filter for V1 vehicleTypes. for (VehicleType vehicleType : allVehicleTypes.getVehicleTypes().values()) { @@ -175,18 +173,18 @@ public final void CarrierLargeBatteryTest_Version2() throws ExecutionException, FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV2 = CarrierUtils.createCarrier(Id.create("Carrier_Version2", Carrier.class)); + Carrier carrierV2 = CarriersUtils.createCarrier(Id.create("Carrier_Version2", Carrier.class)); carriers.addCarrier(addTwoServicesToCarrier(carrierV2)); createCarriers(carriers, fleetSize, carrierV2, vehicleTypes); scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV2, 10); + CarriersUtils.setJspritIterations(carrierV2, 10); + + CarriersUtils.runJsprit(scenario); + - FreightUtils.runJsprit(scenario); - - Assert.assertEquals("Not the correct amout of scheduled tours", 1, carrierV2.getSelectedPlan().getScheduledTours().size()); @@ -230,7 +228,7 @@ public final void CarrierLargeBatteryTest_Version2() throws ExecutionException, @Test public final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -240,7 +238,7 @@ public final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, CarrierVehicleTypes allVehicleTypes = new CarrierVehicleTypes(); CarrierVehicleTypes vehicleTypes = new CarrierVehicleTypes(); - new CarrierVehicleTypeReader(allVehicleTypes).readFile(ConfigUtils.addOrGetModule(config, FreightConfigGroup.class).getCarriersVehicleTypesFile()); + new CarrierVehicleTypeReader(allVehicleTypes).readFile(ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class).getCarriersVehicleTypesFile()); //Filter for V3 vehicleTypes. for (VehicleType vehicleType : allVehicleTypes.getVehicleTypes().values()) { @@ -250,16 +248,16 @@ public final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, } FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV3 = CarrierUtils.createCarrier(Id.create("Carrier_Version3", Carrier.class)); + Carrier carrierV3 = CarriersUtils.createCarrier(Id.create("Carrier_Version3", Carrier.class)); carriers.addCarrier(addTwoServicesToCarrier(carrierV3)); createCarriers(carriers, fleetSize, carrierV3, vehicleTypes); scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV3, 10); + CarriersUtils.setJspritIterations(carrierV3, 10); - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); Assert.assertEquals("Not the correct amout of scheduled tours", 2, carrierV3.getSelectedPlan().getScheduledTours().size()); @@ -311,7 +309,7 @@ public final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, @Test public final void CarrierWithAdditionalDieselVehicleTest_Version4() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -321,7 +319,7 @@ public final void CarrierWithAdditionalDieselVehicleTest_Version4() throws Execu CarrierVehicleTypes allVehicleTypes = new CarrierVehicleTypes(); CarrierVehicleTypes vehicleTypes = new CarrierVehicleTypes(); - new CarrierVehicleTypeReader(allVehicleTypes).readFile(ConfigUtils.addOrGetModule(config, FreightConfigGroup.class).getCarriersVehicleTypesFile()); + new CarrierVehicleTypeReader(allVehicleTypes).readFile(ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class).getCarriersVehicleTypesFile()); //Filter for V4 vehicleTypes including diesel. for (VehicleType vehicleType : allVehicleTypes.getVehicleTypes().values()) { @@ -332,16 +330,16 @@ public final void CarrierWithAdditionalDieselVehicleTest_Version4() throws Execu } FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV4 = CarrierUtils.createCarrier(Id.create("Carrier_Version4", Carrier.class)); + Carrier carrierV4 = CarriersUtils.createCarrier(Id.create("Carrier_Version4", Carrier.class)); carriers.addCarrier(addThreeServicesToCarrier(carrierV4)); createCarriers(carriers, fleetSize, carrierV4, vehicleTypes); scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV4, 10); + CarriersUtils.setJspritIterations(carrierV4, 10); - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); Assert.assertEquals("Not the correct amount of scheduled tours", 2, carrierV4.getSelectedPlan().getScheduledTours().size()); @@ -359,7 +357,7 @@ public final void CarrierWithAdditionalDieselVehicleTest_Version4() throws Execu Assert.assertEquals("Wrong maximum distance of the tour of this vehicleType", 30000, maxDistance_vehicleType_SmallV4, MatsimTestUtils.EPSILON); - + for (ScheduledTour scheduledTour : carrierV4.getSelectedPlan().getScheduledTours()) { String thisTypeId = scheduledTour.getVehicle().getType().getId().toString(); @@ -391,18 +389,18 @@ else if (thisTypeId.equals("DieselVehicle")) */ private void prepareConfig(Config config) { config.network().setInputFile(IOUtils.extendUrl(SCENARIO_URL, "grid9x9.xml").toString()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - new OutputDirectoryHierarchy(config.controler().getOutputDirectory(), config.controler().getRunId(), - config.controler().getOverwriteFileSetting(), CompressionType.gzip); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + new OutputDirectoryHierarchy(config.controller().getOutputDirectory(), config.controller().getRunId(), + config.controller().getOverwriteFileSetting(), CompressionType.gzip); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); config.global().setRandomSeed(4177); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setUseDistanceConstraintForTourPlanning(UseDistanceConstraintForTourPlanning.basedOnEnergyConsumption); - freightConfigGroup.setCarriersVehicleTypesFile(testUtils.getPackageInputDirectory()+"/vehicleTypesForDCTest.xml"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setUseDistanceConstraintForTourPlanning(UseDistanceConstraintForTourPlanning.basedOnEnergyConsumption); + freightCarriersConfigGroup.setCarriersVehicleTypesFile(testUtils.getPackageInputDirectory()+"/vehicleTypesForDCTest.xml"); } private static Carrier addTwoServicesToCarrier(Carrier carrier) { @@ -411,14 +409,14 @@ private static Carrier addTwoServicesToCarrier(Carrier carrier) { .newInstance(Id.create("Service1", CarrierService.class), Id.createLinkId("j(3,8)")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) .setCapacityDemand(40).build(); - CarrierUtils.addService(carrier, service1); + CarriersUtils.addService(carrier, service1); // Service 2 CarrierService service2 = CarrierService.Builder .newInstance(Id.create("Service2", CarrierService.class), Id.createLinkId("j(0,3)R")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) .setCapacityDemand(40).build(); - CarrierUtils.addService(carrier, service2); + CarriersUtils.addService(carrier, service2); return carrier; } @@ -432,7 +430,7 @@ private static Carrier addThreeServicesToCarrier(Carrier carrier) { .newInstance(Id.create("Service3", CarrierService.class), Id.createLinkId("j(9,2)")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) .setCapacityDemand(40).build(); - CarrierUtils.addService(carrier, service3); + CarriersUtils.addService(carrier, service3); return carrier; } @@ -485,7 +483,7 @@ private static void defineCarriers(Carriers carriers, FleetSize fleetSize, Carri singleCarrier.setCarrierCapabilities(CarrierCapabilities.Builder.newInstance().setFleetSize(fleetSize).build()); for (CarrierVehicle carrierVehicle : vehicles) { - CarrierUtils.addCarrierVehicle(singleCarrier, carrierVehicle); + CarriersUtils.addCarrierVehicle(singleCarrier, carrierVehicle); } singleCarrier.getCarrierCapabilities().getVehicleTypes().addAll(vehicleTypes.getVehicleTypes().values()); diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/DistanceConstraintTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java similarity index 90% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/DistanceConstraintTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java index fce789621f8..cff10f42763 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/DistanceConstraintTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2020 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.jsprit; +package org.matsim.freight.carriers.jsprit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -28,14 +28,9 @@ import org.junit.Test; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.FreightConfigGroup.UseDistanceConstraintForTourPlanning; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; -import org.matsim.contrib.freight.controler.FreightUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup.CompressionType; +import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.population.routes.NetworkRoute; @@ -43,6 +38,9 @@ import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.FreightCarriersConfigGroup.UseDistanceConstraintForTourPlanning; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; @@ -83,7 +81,7 @@ public class DistanceConstraintTest { public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -94,7 +92,7 @@ public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV1 = CarrierUtils.createCarrier(Id.create("Carrier_Version1", Carrier.class)); + Carrier carrierV1 = CarriersUtils.createCarrier(Id.create("Carrier_Version1", Carrier.class)); VehicleType vehicleType_LargeV1 = VehicleUtils.createVehicleType(Id.create("LargeBattery_V1", VehicleType.class)); vehicleType_LargeV1.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(100.); VehicleUtils.setHbefaTechnology(vehicleType_LargeV1.getEngineInformation(), "electricity"); @@ -102,7 +100,7 @@ public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, VehicleUtils.setEnergyConsumptionKWhPerMeter(vehicleType_LargeV1.getEngineInformation(), 0.015); vehicleType_LargeV1.getCapacity().setOther(80.); vehicleType_LargeV1.setDescription("Carrier_Version1"); - + VehicleType vehicleType_SmallV1 = VehicleUtils.createVehicleType(Id.create("SmallBattery_V1", VehicleType.class)); vehicleType_SmallV1.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(70.); VehicleUtils.setHbefaTechnology(vehicleType_SmallV1.getEngineInformation(), "electricity"); @@ -119,9 +117,9 @@ public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV1, 25); + CarriersUtils.setJspritIterations(carrierV1, 25); - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); Assert.assertEquals("Not the correct amout of scheduled tours", 1, carrierV1.getSelectedPlan().getScheduledTours().size()); @@ -137,7 +135,7 @@ public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, MatsimTestUtils.EPSILON); Assert.assertEquals("Wrong maximum distance of the tour of this vehicleType", 30000, maxDistance_vehicleType_SmallV1, MatsimTestUtils.EPSILON); - + double distanceTour = 0.0; List elements = carrierV1.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); @@ -161,7 +159,7 @@ public final void CarrierSmallBatteryTest_Version1() throws ExecutionException, @Test public final void CarrierLargeBatteryTest_Version2() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -172,7 +170,7 @@ public final void CarrierLargeBatteryTest_Version2() throws ExecutionException, FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV2 = CarrierUtils.createCarrier(Id.create("Carrier_Version2", Carrier.class)); + Carrier carrierV2 = CarriersUtils.createCarrier(Id.create("Carrier_Version2", Carrier.class)); VehicleType vehicleType_LargeV2 = VehicleUtils.createVehicleType(Id.create("LargeBattery_V2", VehicleType.class)); vehicleType_LargeV2.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(100.); @@ -181,7 +179,7 @@ public final void CarrierLargeBatteryTest_Version2() throws ExecutionException, VehicleUtils.setEnergyConsumptionKWhPerMeter(vehicleType_LargeV2.getEngineInformation(), 0.015); vehicleType_LargeV2.setDescription("Carrier_Version2"); vehicleType_LargeV2.getCapacity().setOther(80.); - + VehicleType vehicleType_SmallV2 = VehicleUtils.createVehicleType(Id.create("SmallBattery_V2", VehicleType.class)); vehicleType_SmallV2.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(70.); VehicleUtils.setHbefaTechnology(vehicleType_SmallV2.getEngineInformation(), "electricity"); @@ -198,11 +196,11 @@ public final void CarrierLargeBatteryTest_Version2() throws ExecutionException, scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV2, 10); + CarriersUtils.setJspritIterations(carrierV2, 10); + + CarriersUtils.runJsprit(scenario); + - FreightUtils.runJsprit(scenario); - - Assert.assertEquals("Not the correct amout of scheduled tours", 1, carrierV2.getSelectedPlan().getScheduledTours().size()); @@ -243,7 +241,7 @@ public final void CarrierLargeBatteryTest_Version2() throws ExecutionException, @Test public final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -253,7 +251,7 @@ public final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, CarrierVehicleTypes vehicleTypes = new CarrierVehicleTypes(); FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV3 = CarrierUtils.createCarrier(Id.create("Carrier_Version3", Carrier.class)); + Carrier carrierV3 = CarriersUtils.createCarrier(Id.create("Carrier_Version3", Carrier.class)); VehicleType vehicleType_LargeV3 = VehicleUtils.createVehicleType(Id.create("LargeBattery_V3", VehicleType.class)); vehicleType_LargeV3.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(100.); @@ -262,7 +260,7 @@ public final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, VehicleUtils.setEnergyConsumptionKWhPerMeter(vehicleType_LargeV3.getEngineInformation(), 0.015); vehicleType_LargeV3.setDescription("Carrier_Version3"); vehicleType_LargeV3.getCapacity().setOther(80.); - + VehicleType vehicleType_SmallV3 = VehicleUtils.createVehicleType(Id.create("SmallBattery_V3", VehicleType.class)); vehicleType_SmallV3.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(40.); VehicleUtils.setHbefaTechnology(vehicleType_SmallV3.getEngineInformation(), "electricity"); @@ -282,9 +280,9 @@ public final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV3, 10); + CarriersUtils.setJspritIterations(carrierV3, 10); - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); Assert.assertEquals("Not the correct amout of scheduled tours", 2, carrierV3.getSelectedPlan().getScheduledTours().size()); @@ -333,7 +331,7 @@ public final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, @Test public final void CarrierWithAdditionalDieselVehicleTest_Version4() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -343,7 +341,7 @@ public final void CarrierWithAdditionalDieselVehicleTest_Version4() throws Execu CarrierVehicleTypes vehicleTypes = new CarrierVehicleTypes(); FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV4 = CarrierUtils.createCarrier(Id.create("Carrier_Version4", Carrier.class)); + Carrier carrierV4 = CarriersUtils.createCarrier(Id.create("Carrier_Version4", Carrier.class)); VehicleType vehicleType_LargeV4 = VehicleUtils.createVehicleType(Id.create("LargeBattery_V4", VehicleType.class)); vehicleType_LargeV4.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(100.); @@ -352,15 +350,15 @@ public final void CarrierWithAdditionalDieselVehicleTest_Version4() throws Execu VehicleUtils.setEnergyConsumptionKWhPerMeter(vehicleType_LargeV4.getEngineInformation(), 0.015); vehicleType_LargeV4.setDescription("Carrier_Version4"); vehicleType_LargeV4.getCapacity().setOther(120.); - + VehicleType vehicleType_SmallV4 = VehicleUtils.createVehicleType(Id.create("SmallBattery_V4", VehicleType.class)); vehicleType_SmallV4.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(70.); VehicleUtils.setHbefaTechnology(vehicleType_SmallV4.getEngineInformation(), "electricity"); VehicleUtils.setEnergyCapacity(vehicleType_SmallV4.getEngineInformation(), 300.); - VehicleUtils.setEnergyConsumptionKWhPerMeter(vehicleType_SmallV4.getEngineInformation(), 0.01); + VehicleUtils.setEnergyConsumptionKWhPerMeter(vehicleType_SmallV4.getEngineInformation(), 0.01); vehicleType_SmallV4.setDescription("Carrier_Version4"); vehicleType_SmallV4.getCapacity().setOther(120.); - + VehicleType vehicleType_Diesel = VehicleUtils.createVehicleType(Id.create("DieselVehicle", VehicleType.class)); vehicleType_Diesel.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(400.); VehicleUtils.setHbefaTechnology(vehicleType_Diesel.getEngineInformation(), "diesel"); @@ -377,9 +375,9 @@ public final void CarrierWithAdditionalDieselVehicleTest_Version4() throws Execu scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV4, 10); + CarriersUtils.setJspritIterations(carrierV4, 10); - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); Assert.assertEquals("Not the correct amout of scheduled tours", 2, carrierV4.getSelectedPlan().getScheduledTours().size()); @@ -394,7 +392,7 @@ public final void CarrierWithAdditionalDieselVehicleTest_Version4() throws Execu Assert.assertEquals("Wrong maximum distance of the tour of this vehicleType", 30000, maxDistance_vehicleType_SmallV4, MatsimTestUtils.EPSILON); - + for (ScheduledTour scheduledTour : carrierV4.getSelectedPlan().getScheduledTours()) { String thisTypeId = scheduledTour.getVehicle().getType().getId().toString(); @@ -432,7 +430,7 @@ else if (thisTypeId.equals("DieselVehicle")) @Test public final void CarrierWithShipmentsMidSizeBatteryTest_Version5() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -443,7 +441,7 @@ public final void CarrierWithShipmentsMidSizeBatteryTest_Version5() throws Execu FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV5 = CarrierUtils.createCarrier(Id.create("Carrier_Version5", Carrier.class)); + Carrier carrierV5 = CarriersUtils.createCarrier(Id.create("Carrier_Version5", Carrier.class)); VehicleType vehicleType_MidSizeV5 = VehicleUtils.createVehicleType(Id.create("MidSizeBattery_V5", VehicleType.class)); vehicleType_MidSizeV5.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(100.); @@ -460,9 +458,9 @@ public final void CarrierWithShipmentsMidSizeBatteryTest_Version5() throws Execu scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV5, 10); + CarriersUtils.setJspritIterations(carrierV5, 10); - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); //We need two tours, due to reloading both shipments must be transported one after the other Assert.assertEquals("Not the correct amout of scheduled tours", 2, @@ -511,7 +509,7 @@ public final void CarrierWithShipmentsMidSizeBatteryTest_Version5() throws Execu @Test public final void CarrierWithShipmentsLargeBatteryTest_Version6() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); prepareConfig(config); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -522,7 +520,7 @@ public final void CarrierWithShipmentsLargeBatteryTest_Version6() throws Executi FleetSize fleetSize = FleetSize.INFINITE; - Carrier carrierV5 = CarrierUtils.createCarrier(Id.create("Carrier_Version5", Carrier.class)); + Carrier carrierV5 = CarriersUtils.createCarrier(Id.create("Carrier_Version5", Carrier.class)); VehicleType vehicleType_LargeV5 = VehicleUtils.createVehicleType(Id.create("LargeBattery_V5", VehicleType.class)); vehicleType_LargeV5.getCostInformation().setCostsPerMeter(0.00055).setCostsPerSecond(0.008).setFixedCost(100.); @@ -539,9 +537,9 @@ public final void CarrierWithShipmentsLargeBatteryTest_Version6() throws Executi scenario.addScenarioElement("carrierVehicleTypes", vehicleTypes); scenario.addScenarioElement("carriers", carriers); - CarrierUtils.setJspritIterations(carrierV5, 10); + CarriersUtils.setJspritIterations(carrierV5, 10); - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); //We need two tours, due to reloading both shipments must be transported one after the other @@ -583,17 +581,17 @@ public final void CarrierWithShipmentsLargeBatteryTest_Version6() throws Executi */ static void prepareConfig(Config config) { config.network().setInputFile(IOUtils.extendUrl(SCENARIO_URL, "grid9x9.xml").toString()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - new OutputDirectoryHierarchy(config.controler().getOutputDirectory(), config.controler().getRunId(), - config.controler().getOverwriteFileSetting(), CompressionType.gzip); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + new OutputDirectoryHierarchy(config.controller().getOutputDirectory(), config.controller().getRunId(), + config.controller().getOverwriteFileSetting(), CompressionType.gzip); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); config.global().setRandomSeed(4177); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setUseDistanceConstraintForTourPlanning(UseDistanceConstraintForTourPlanning.basedOnEnergyConsumption); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setUseDistanceConstraintForTourPlanning(UseDistanceConstraintForTourPlanning.basedOnEnergyConsumption); } private static Carrier addTwoServicesToCarrier(Carrier carrier) { @@ -602,14 +600,14 @@ private static Carrier addTwoServicesToCarrier(Carrier carrier) { .newInstance(Id.create("Service1", CarrierService.class), Id.createLinkId("j(3,8)")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) .setCapacityDemand(40).build(); - CarrierUtils.addService(carrier, service1); + CarriersUtils.addService(carrier, service1); // Service 2 CarrierService service2 = CarrierService.Builder .newInstance(Id.create("Service2", CarrierService.class), Id.createLinkId("j(0,3)R")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) .setCapacityDemand(40).build(); - CarrierUtils.addService(carrier, service2); + CarriersUtils.addService(carrier, service2); return carrier; } @@ -620,14 +618,14 @@ private static Carrier addTwoShipmentsToCarrier(Carrier carrier) { .newInstance(Id.create("Shipment1", CarrierShipment.class), Id.createLinkId("i(1,8)"), Id.createLinkId("j(3,8)"), 40) .setDeliveryServiceTime(20).setDeliveryTimeWindow(TimeWindow.newInstance(8 * 3600, 12 * 3600)) .build(); - CarrierUtils.addShipment(carrier, shipment1); + CarriersUtils.addShipment(carrier, shipment1); // Shipment 2 CarrierShipment shipment2 = CarrierShipment.Builder .newInstance(Id.create("Shipment2", CarrierShipment.class),Id.createLinkId("i(1,8)"), Id.createLinkId("j(0,3)R"), 40) .setDeliveryServiceTime(20).setDeliveryTimeWindow(TimeWindow.newInstance(8 * 3600, 12 * 3600)) .build(); - CarrierUtils.addShipment(carrier, shipment2); + CarriersUtils.addShipment(carrier, shipment2); return carrier; } @@ -641,7 +639,7 @@ private static Carrier addThreeServicesToCarrier(Carrier carrier) { .newInstance(Id.create("Service3", CarrierService.class), Id.createLinkId("j(9,2)")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) .setCapacityDemand(40).build(); - CarrierUtils.addService(carrier, service3); + CarriersUtils.addService(carrier, service3); return carrier; } @@ -694,7 +692,7 @@ private static void defineCarriers(Carriers carriers, FleetSize fleetSize, Carri singleCarrier.setCarrierCapabilities(CarrierCapabilities.Builder.newInstance().setFleetSize(fleetSize).build()); for (CarrierVehicle carrierVehicle : vehicles) { - CarrierUtils.addCarrierVehicle(singleCarrier, carrierVehicle); + CarriersUtils.addCarrierVehicle(singleCarrier, carrierVehicle); } singleCarrier.getCarrierCapabilities().getVehicleTypes().addAll(vehicleTypes.getVehicleTypes().values()); diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/FixedCostsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java similarity index 82% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/FixedCostsTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java index ddb57fda7bf..a1811281682 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/FixedCostsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java @@ -1,30 +1,34 @@ -/* *********************************************************************** * - * 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.freight.jsprit; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.jsprit; import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; import com.graphhopper.jsprit.core.algorithm.box.SchrimpfFactory; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; import com.graphhopper.jsprit.core.util.Solutions; - +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -32,17 +36,18 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.*; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.utils.io.IOUtils; +import org.matsim.freight.carriers.*; import org.matsim.testcases.MatsimTestUtils; -import org.matsim.vehicles.*; +import org.matsim.vehicles.EngineInformation; +import org.matsim.vehicles.Vehicle; +import org.matsim.vehicles.VehicleType; +import org.matsim.vehicles.VehicleUtils; import java.net.URL; import java.util.Collection; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; /** @@ -65,17 +70,17 @@ public void setUp() throws Exception { CarrierService service1 = createMatsimService("Service1", "i(3,0)", 1); CarrierService service2 = createMatsimService("Service2", "i(9,9)R", 1); - Carrier carrier1 = CarrierUtils.createCarrier(Id.create("carrier1", Carrier.class ) ); - CarrierUtils.addService(carrier1, service1); - CarrierUtils.addService(carrier1, service2); + Carrier carrier1 = CarriersUtils.createCarrier(Id.create("carrier1", Carrier.class ) ); + CarriersUtils.addService(carrier1, service1); + CarriersUtils.addService(carrier1, service2); - Carrier carrier2 = CarrierUtils.createCarrier(Id.create("carrier2", Carrier.class ) ); - CarrierUtils.addService(carrier2, service1); - CarrierUtils.addService(carrier2, service2); + Carrier carrier2 = CarriersUtils.createCarrier(Id.create("carrier2", Carrier.class ) ); + CarriersUtils.addService(carrier2, service1); + CarriersUtils.addService(carrier2, service2); - Carrier carrier3 = CarrierUtils.createCarrier(Id.create("carrier3", Carrier.class ) ); - CarrierUtils.addService(carrier3, service1); - CarrierUtils.addService(carrier3, service2); + Carrier carrier3 = CarriersUtils.createCarrier(Id.create("carrier3", Carrier.class ) ); + CarriersUtils.addService(carrier3, service1); + CarriersUtils.addService(carrier3, service2); //Create add vehicle for carriers diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/IntegrationIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/IntegrationIT.java similarity index 58% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/IntegrationIT.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/IntegrationIT.java index 63f9a6a3bdf..984bdd3e5e8 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/IntegrationIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/IntegrationIT.java @@ -1,4 +1,25 @@ -package org.matsim.contrib.freight.jsprit; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.jsprit; import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; import com.graphhopper.jsprit.core.algorithm.box.SchrimpfFactory; @@ -11,14 +32,12 @@ import org.junit.Test; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.FreightConfigGroup; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts.Builder; -import org.matsim.contrib.freight.controler.FreightUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts.Builder; import org.matsim.testcases.MatsimTestUtils; import java.util.concurrent.ExecutionException; @@ -37,27 +56,27 @@ public void testJsprit() throws ExecutionException, InterruptedException { Config config = ConfigUtils.createConfig(); config.global().setRandomSeed(4177); - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setCarriersFile(carrierFilename); - freightConfigGroup.setCarriersVehicleTypesFile(vehicleTypeFilename); - freightConfigGroup.setTravelTimeSliceWidth(24*3600); - freightConfigGroup.setTimeWindowHandling(FreightConfigGroup.TimeWindowHandling.enforceBeginnings); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setCarriersFile(carrierFilename); + freightCarriersConfigGroup.setCarriersVehicleTypesFile(vehicleTypeFilename); + freightCarriersConfigGroup.setTravelTimeSliceWidth(24*3600); + freightCarriersConfigGroup.setTimeWindowHandling(FreightCarriersConfigGroup.TimeWindowHandling.enforceBeginnings); Scenario scenario = ScenarioUtils.createScenario(config); new MatsimNetworkReader(scenario.getNetwork()).readFile(networkFilename); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); - for (Carrier carrier : FreightUtils.getCarriers(scenario).getCarriers().values()) { - CarrierUtils.setJspritIterations(carrier, 1); + for (Carrier carrier : CarriersUtils.getCarriers(scenario).getCarriers().values()) { + CarriersUtils.setJspritIterations(carrier, 1); } - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); double scoreWithRunJsprit = 0; - for (Carrier carrier : FreightUtils.getCarriers(scenario).getCarriers().values()) { + for (Carrier carrier : CarriersUtils.getCarriers(scenario).getCarriers().values()) { scoreWithRunJsprit = scoreWithRunJsprit + carrier.getSelectedPlan().getJspritScore(); } - double scoreRunWithOldStructure = generateCarrierPlans(scenario.getNetwork(), FreightUtils.getCarriers(scenario), FreightUtils.getCarrierVehicleTypes(scenario)); + double scoreRunWithOldStructure = generateCarrierPlans(scenario.getNetwork(), CarriersUtils.getCarriers(scenario), CarriersUtils.getCarrierVehicleTypes(scenario)); Assert.assertEquals("The score of both runs are not the same", scoreWithRunJsprit, scoreRunWithOldStructure, MatsimTestUtils.EPSILON); } diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/MatsimTransformerTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java similarity index 91% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/MatsimTransformerTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java index c552a2af778..7b3060643a3 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/MatsimTransformerTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java @@ -1,15 +1,25 @@ -package org.matsim.contrib.freight.jsprit; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.jsprit; import com.graphhopper.jsprit.core.problem.Location; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; @@ -21,18 +31,26 @@ import com.graphhopper.jsprit.core.problem.vehicle.Vehicle; import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl; import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl; - import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.io.MatsimNetworkReader; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.testcases.MatsimTestUtils; -import org.matsim.vehicles.*; +import org.matsim.vehicles.VehicleType; +import org.matsim.vehicles.VehicleUtils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.*; public class MatsimTransformerTest { @@ -214,9 +232,9 @@ private VehicleRoutingProblem getVehicleRoutingProblem(ScheduledTour sTour) { private Collection getJobsFrom(ScheduledTour sTour) { Collection services = new ArrayList(); for (Tour.TourElement e : sTour.getTour().getTourElements()) { - if (e instanceof org.matsim.contrib.freight.carrier.Tour.TourActivity) { - if (e instanceof org.matsim.contrib.freight.carrier.Tour.ServiceActivity) { - CarrierService carrierService = ((org.matsim.contrib.freight.carrier.Tour.ServiceActivity) e) + if (e instanceof Tour.TourActivity) { + if (e instanceof Tour.ServiceActivity) { + CarrierService carrierService = ((Tour.ServiceActivity) e) .getService(); Service service = Service.Builder.newInstance(carrierService.getId().toString()) .setLocation(Location.newInstance(carrierService.getLocationLinkId().toString())).build(); @@ -307,7 +325,7 @@ public void whenTransforming_matsimPlan2vehicleRouteSolution_itIsMadeCorrectly() VehicleRoutingProblem vehicleRoutingProblem = VehicleRoutingProblem.Builder.newInstance().addAllJobs(services1) .addAllJobs(services2).addVehicle(v1).addVehicle(v2).build(); - CarrierPlan plan = new CarrierPlan(CarrierUtils.createCarrier(Id.create("myCarrier", Carrier.class)), sTours); + CarrierPlan plan = new CarrierPlan(CarriersUtils.createCarrier(Id.create("myCarrier", Carrier.class)), sTours); plan.setScore(-100.0); VehicleRoutingProblemSolution solution = MatsimJspritFactory.createSolution(plan, vehicleRoutingProblem); assertNotNull(solution); @@ -365,7 +383,7 @@ private VehicleType getMatsimVehicleType() { // EngineInformation engineInformation = new EngineInformation(); // engineInformation.setFuelType( FuelType.diesel ); // engineInformation.setFuelConsumption( (double) 15 ); -// CarrierUtils.CarrierVehicleTypeBuilder builder = CarrierUtils.CarrierVehicleTypeBuilder.newInstance( Id.create( "matsimType", VehicleType.class ) ) +// CarriersUtils.CarrierVehicleTypeBuilder builder = CarriersUtils.CarrierVehicleTypeBuilder.newInstance( Id.create( "matsimType", VehicleType.class ) ) VehicleType vehicleType = VehicleUtils.getFactory() .createVehicleType(Id.create("matsimType", VehicleType.class)).setMaximumVelocity(13.8); vehicleType.getCapacity().setOther(50); @@ -496,7 +514,7 @@ public void createVehicleRoutingProblemBuilderWithShipments_isMadeCorrectly() { } private Carrier createCarrierWithServices() { - Carrier carrier = CarrierUtils.createCarrier(Id.create("TestCarrier", Carrier.class)); + Carrier carrier = CarriersUtils.createCarrier(Id.create("TestCarrier", Carrier.class)); VehicleType matsimType = getMatsimVehicleType(); CarrierCapabilities.Builder ccBuilder = CarrierCapabilities.Builder.newInstance() .addVehicle(getMatsimVehicle("matsimVehicle", "i(6,0)", matsimType)).setFleetSize(FleetSize.INFINITE); @@ -504,24 +522,24 @@ private Carrier createCarrierWithServices() { CarrierService carrierService1 = CarrierService.Builder .newInstance(Id.create("serviceId", CarrierService.class), Id.create("i(7,4)R", Link.class)) .setCapacityDemand(20).setServiceDuration(10.0).build(); - CarrierUtils.addService(carrier, carrierService1); + CarriersUtils.addService(carrier, carrierService1); CarrierService carrierService2 = CarrierService.Builder .newInstance(Id.create("serviceId2", CarrierService.class), Id.create("i(3,9)", Link.class)) .setCapacityDemand(10).setServiceDuration(20.0).build(); - CarrierUtils.addService(carrier, carrierService2); + CarriersUtils.addService(carrier, carrierService2); return carrier; } private Carrier createCarrierWithShipments() { - Carrier carrier = CarrierUtils.createCarrier(Id.create("TestCarrier", Carrier.class)); + Carrier carrier = CarriersUtils.createCarrier(Id.create("TestCarrier", Carrier.class)); VehicleType matsimType = getMatsimVehicleType(); CarrierCapabilities.Builder ccBuilder = CarrierCapabilities.Builder.newInstance() .addVehicle(getMatsimVehicle("matsimVehicle", "i(6,0)", matsimType)).setFleetSize(FleetSize.INFINITE); carrier.setCarrierCapabilities(ccBuilder.build()); CarrierShipment shipment1 = getMatsimShipment("shipment1", "i(6,0)", "i(7,4)R", 10); - CarrierUtils.addShipment(carrier, shipment1); + CarriersUtils.addShipment(carrier, shipment1); CarrierShipment shipment2 = getMatsimShipment("shipment2", "i(6,0)", "i(3,9)", 20); - CarrierUtils.addShipment(carrier, shipment2); + CarriersUtils.addShipment(carrier, shipment2); return carrier; } diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCostsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsTest.java similarity index 83% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCostsTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsTest.java index 89766d95521..e85cb3ce9a1 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCostsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsTest.java @@ -1,14 +1,29 @@ -package org.matsim.contrib.freight.jsprit; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Arrays; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.jsprit; import com.graphhopper.jsprit.core.problem.Location; import com.graphhopper.jsprit.core.problem.driver.Driver; import com.graphhopper.jsprit.core.problem.vehicle.Vehicle; - import org.junit.Assert; import org.junit.Rule; import org.junit.Test; @@ -23,6 +38,11 @@ import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; +import java.util.Arrays; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class NetworkBasedTransportCostsTest { diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/SkillsIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/SkillsIT.java similarity index 77% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/SkillsIT.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/SkillsIT.java index a0fe40c3b50..3201a4cd5c9 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/jsprit/SkillsIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/SkillsIT.java @@ -1,21 +1,24 @@ -/* *********************************************************************** * - * 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.freight.jsprit; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.jsprit; import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; import com.graphhopper.jsprit.core.algorithm.box.SchrimpfFactory; @@ -29,12 +32,11 @@ 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.controler.FreightUtils; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.misc.Time; +import org.matsim.freight.carriers.*; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.VehicleType; @@ -76,7 +78,7 @@ public void testJspritWithSameSkillsRequired(){ } private VehicleRoutingProblemSolution generateCarrierPlans(Scenario scenario) { - Carrier carrier = FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("TestCarrier", Carrier.class)); + Carrier carrier = CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("TestCarrier", Carrier.class)); NetworkBasedTransportCosts networkBasedTransportCosts = NetworkBasedTransportCosts.Builder.newInstance( scenario.getNetwork(), carrier.getCarrierCapabilities().getVehicleTypes()) .setTimeSliceWidth((int) Time.parseTime("00:30:00")) @@ -94,9 +96,9 @@ private VehicleRoutingProblemSolution generateCarrierPlans(Scenario scenario) { carrier.setSelectedPlan(newPlan); SolutionPrinter.print(problem, solution, SolutionPrinter.Print.VERBOSE); -// new CarrierPlanXmlWriterV3(FreightUtils.getCarriers(scenario)).write(utils.getOutputDirectory() + "carriers.xml"); +// new CarrierPlanXmlWriterV3(CarrierControlerUtils.getCarriers(scenario)).write(utils.getOutputDirectory() + "carriers.xml"); // Scenario scNew = ScenarioUtils.createScenario(ConfigUtils.createConfig()); -// new CarrierPlanXmlReaderV3(FreightUtils.getCarriers(scNew)).readFile(utils.getOutputDirectory() + "carriers.xml"); +// new CarrierPlanXmlReaderV3(CarrierControlerUtils.getCarriers(scNew)).readFile(utils.getOutputDirectory() + "carriers.xml"); return solution; } @@ -104,9 +106,9 @@ private Scenario setupTestScenario() { Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); new MatsimNetworkReader(scenario.getNetwork()).readFile(utils.getClassInputDirectory() + "grid-network.xml"); - Carriers carriers = FreightUtils.addOrGetCarriers(scenario ); + Carriers carriers = CarriersUtils.addOrGetCarriers(scenario ); { - Carrier carrier = CarrierUtils.createCarrier( Id.create("TestCarrier", Carrier.class)); + Carrier carrier = CarriersUtils.createCarrier( Id.create("TestCarrier", Carrier.class)); { CarrierCapabilities.Builder capabilitiesBuilder = CarrierCapabilities.Builder.newInstance(); capabilitiesBuilder.setFleetSize(CarrierCapabilities.FleetSize.FINITE); @@ -124,7 +126,7 @@ private Scenario setupTestScenario() { typeOne.getCostInformation().setFixedCost( 1000.0 ).setCostsPerMeter( 0.001 ).setCostsPerSecond( 0.001 ) ; // typeOne.setCapacity(vehicleCapacity); typeOne.getCapacity().setOther( 2.0 ); - FreightUtils.addSkill(typeOne, "skill 1"); + CarriersUtils.addSkill(typeOne, "skill 1"); capabilitiesBuilder.addType(typeOne); CarrierVehicle vehicleOne = CarrierVehicle.Builder.newInstance(Id.createVehicleId("1"), carrierLocation, typeOne ) .setEarliestStart(0.0) @@ -138,7 +140,7 @@ private Scenario setupTestScenario() { typeTwo.getCostInformation().setFixedCost( 1000.0 ).setCostsPerMeter( 0.001 ).setCostsPerSecond( 0.001 ) ; // typeTwo.setCapacity(vehicleCapacity); typeTwo.getCapacity().setOther( 2.0 ); - FreightUtils.addSkill(typeTwo, "skill 2"); + CarriersUtils.addSkill(typeTwo, "skill 2"); capabilitiesBuilder.addType(typeTwo); CarrierVehicle vehicleTwo = CarrierVehicle.Builder.newInstance(Id.createVehicleId("2"), carrierLocation, typeTwo ) .setEarliestStart(0.0) @@ -155,7 +157,7 @@ private Scenario setupTestScenario() { } private void addShipmentsRequiringDifferentSkills(Scenario scenario) { - Carrier carrier = FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("TestCarrier", Carrier.class)); + Carrier carrier = CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("TestCarrier", Carrier.class)); CarrierShipment shipmentOne = CarrierShipment.Builder.newInstance( Id.create("1", CarrierShipment.class), carrierLocation, @@ -166,8 +168,8 @@ private void addShipmentsRequiringDifferentSkills(Scenario scenario) { .setDeliveryTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) .setDeliveryServiceTime(Time.parseTime("00:05:00")) .build(); - FreightUtils.addSkill(shipmentOne, "skill 1"); - CarrierUtils.addShipment(carrier, shipmentOne); + CarriersUtils.addSkill(shipmentOne, "skill 1"); + CarriersUtils.addShipment(carrier, shipmentOne); CarrierShipment shipmentTwo = CarrierShipment.Builder.newInstance( Id.create("2", CarrierShipment.class), @@ -179,12 +181,12 @@ private void addShipmentsRequiringDifferentSkills(Scenario scenario) { .setDeliveryTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) .setDeliveryServiceTime(Time.parseTime("00:05:00")) .build(); - FreightUtils.addSkill(shipmentTwo, "skill 2"); - CarrierUtils.addShipment(carrier, shipmentTwo); + CarriersUtils.addSkill(shipmentTwo, "skill 2"); + CarriersUtils.addShipment(carrier, shipmentTwo); } private void addShipmentsRequiringSameSkills(Scenario scenario) { - Carrier carrier = FreightUtils.getCarriers(scenario).getCarriers().get(Id.create("TestCarrier", Carrier.class)); + Carrier carrier = CarriersUtils.getCarriers(scenario).getCarriers().get(Id.create("TestCarrier", Carrier.class)); CarrierShipment shipmentOne = CarrierShipment.Builder.newInstance( Id.create("1", CarrierShipment.class), carrierLocation, @@ -195,8 +197,8 @@ private void addShipmentsRequiringSameSkills(Scenario scenario) { .setDeliveryTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) .setDeliveryServiceTime(Time.parseTime("00:05:00")) .build(); - FreightUtils.addSkill(shipmentOne, "skill 1"); - CarrierUtils.addShipment(carrier, shipmentOne); + CarriersUtils.addSkill(shipmentOne, "skill 1"); + CarriersUtils.addShipment(carrier, shipmentOne); CarrierShipment shipmentTwo = CarrierShipment.Builder.newInstance( Id.create("2", CarrierShipment.class), @@ -208,8 +210,8 @@ private void addShipmentsRequiringSameSkills(Scenario scenario) { .setDeliveryTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) .setDeliveryServiceTime(Time.parseTime("00:05:00")) .build(); - FreightUtils.addSkill(shipmentTwo, "skill 1"); - CarrierUtils.addShipment(carrier, shipmentTwo); + CarriersUtils.addSkill(shipmentTwo, "skill 1"); + CarriersUtils.addShipment(carrier, shipmentTwo); } } diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/DistanceScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java similarity index 75% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/DistanceScoringFunctionFactoryForTests.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java index 1aa2c0765aa..7dba7a46fdb 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/DistanceScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java @@ -1,8 +1,27 @@ -package org.matsim.contrib.freight.mobsim; - -import java.util.HashSet; -import java.util.Set; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.mobsim; +import jakarta.inject.Inject; import org.junit.Ignore; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; @@ -10,11 +29,6 @@ import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierUtils; -import org.matsim.contrib.freight.carrier.CarrierVehicle; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.controler.CarrierScoringFunctionFactory; import org.matsim.core.gbl.Gbl; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.scoring.ScoringFunction; @@ -22,9 +36,15 @@ import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.ActivityScoring; import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.BasicScoring; import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.LegScoring; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.CarrierVehicle; +import org.matsim.freight.carriers.controler.CarrierScoringFunctionFactory; import org.matsim.vehicles.Vehicle; -import jakarta.inject.Inject; +import java.util.HashSet; +import java.util.Set; @Ignore public class DistanceScoringFunctionFactoryForTests implements CarrierScoringFunctionFactory{ @@ -77,7 +97,7 @@ public void endLeg(double time) { if(currentLeg.getRoute() instanceof NetworkRoute){ NetworkRoute nRoute = (NetworkRoute) currentLeg.getRoute(); Id vehicleId = nRoute.getVehicleId(); - CarrierVehicle vehicle = CarrierUtils.getCarrierVehicle(carrier, vehicleId); + CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); Gbl.assertNotNull(vehicle); if(!employedVehicles.contains(vehicle)){ employedVehicles.add(vehicle); diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/ScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java similarity index 74% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/ScoringFunctionFactoryForTests.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java index 50e4779092b..be93f2ad668 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/ScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java @@ -1,7 +1,25 @@ -package org.matsim.contrib.freight.mobsim; - -import java.util.HashSet; -import java.util.Set; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.mobsim; import org.junit.Ignore; import org.matsim.api.core.v01.Id; @@ -10,11 +28,6 @@ import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierUtils; -import org.matsim.contrib.freight.carrier.CarrierVehicle; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.controler.CarrierScoringFunctionFactory; import org.matsim.core.gbl.Gbl; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.scoring.ScoringFunction; @@ -22,8 +35,16 @@ import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.ActivityScoring; import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.BasicScoring; import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.LegScoring; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.CarrierVehicle; +import org.matsim.freight.carriers.controler.CarrierScoringFunctionFactory; import org.matsim.vehicles.Vehicle; +import java.util.HashSet; +import java.util.Set; + @Ignore public class ScoringFunctionFactoryForTests implements CarrierScoringFunctionFactory{ @@ -75,7 +96,7 @@ public void endLeg(double time) { if(currentLeg.getRoute() instanceof NetworkRoute){ NetworkRoute nRoute = (NetworkRoute) currentLeg.getRoute(); Id vehicleId = nRoute.getVehicleId(); - CarrierVehicle vehicle = CarrierUtils.getCarrierVehicle(carrier, vehicleId); + CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); Gbl.assertNotNull(vehicle); if(!employedVehicles.contains(vehicle)){ employedVehicles.add(vehicle); diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/StrategyManagerFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/StrategyManagerFactoryForTests.java similarity index 52% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/StrategyManagerFactoryForTests.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/StrategyManagerFactoryForTests.java index 7a84c5fa2e3..fc693360e04 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/StrategyManagerFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/StrategyManagerFactoryForTests.java @@ -1,25 +1,46 @@ -package org.matsim.contrib.freight.mobsim; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.mobsim; import com.google.inject.Provider; +import jakarta.inject.Inject; import org.junit.Ignore; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierPlan; -import org.matsim.contrib.freight.controler.CarrierReRouteVehicles; -import org.matsim.contrib.freight.controler.CarrierStrategyManager; -import org.matsim.contrib.freight.controler.FreightUtils; import org.matsim.core.replanning.GenericPlanStrategyImpl; import org.matsim.core.replanning.selectors.BestPlanSelector; -import org.matsim.core.router.FastDijkstraFactory; +import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierPlan; +import org.matsim.freight.carriers.controler.CarrierReRouteVehicles; +import org.matsim.freight.carriers.controler.CarrierStrategyManager; +import org.matsim.freight.carriers.controler.CarrierControlerUtils; import org.matsim.vehicles.Vehicle; -import jakarta.inject.Inject; import java.util.Map; @Ignore @@ -57,12 +78,12 @@ private double disutility(double distance, double time) { @Override public CarrierStrategyManager get() { - final LeastCostPathCalculator router = new FastDijkstraFactory().createPathCalculator(network, new MyTravelCosts(travelTimes.get(TransportMode.car)), travelTimes.get(TransportMode.car)); + final LeastCostPathCalculator router = new SpeedyALTFactory().createPathCalculator(network, new MyTravelCosts(travelTimes.get(TransportMode.car)), travelTimes.get(TransportMode.car)); GenericPlanStrategyImpl planStrat_reRoutePlan = new GenericPlanStrategyImpl<>( new BestPlanSelector<>() ); planStrat_reRoutePlan.addStrategyModule(new CarrierReRouteVehicles.Factory(router, network, travelTimes.get(TransportMode.car )).build() ); - CarrierStrategyManager stratManager = FreightUtils.createDefaultCarrierStrategyManager(); + CarrierStrategyManager stratManager = CarrierControlerUtils.createDefaultCarrierStrategyManager(); stratManager.addStrategy(planStrat_reRoutePlan, null, 1.0); diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/TimeScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java similarity index 77% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/TimeScoringFunctionFactoryForTests.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java index a7ec4c15612..b55a80f9ba1 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/mobsim/TimeScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java @@ -1,10 +1,27 @@ -package org.matsim.contrib.freight.mobsim; - -import java.util.HashSet; -import java.util.Set; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.mobsim; import jakarta.inject.Inject; - import org.junit.Ignore; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; @@ -12,11 +29,6 @@ import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierUtils; -import org.matsim.contrib.freight.carrier.CarrierVehicle; -import org.matsim.contrib.freight.carrier.CarrierConstants; -import org.matsim.contrib.freight.controler.CarrierScoringFunctionFactory; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.scoring.ScoringFunction; import org.matsim.core.utils.misc.Time; @@ -24,8 +36,16 @@ import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.ActivityScoring; import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.BasicScoring; import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.LegScoring; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierConstants; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.CarrierVehicle; +import org.matsim.freight.carriers.controler.CarrierScoringFunctionFactory; import org.matsim.vehicles.Vehicle; +import java.util.HashSet; +import java.util.Set; + @Ignore public class TimeScoringFunctionFactoryForTests implements CarrierScoringFunctionFactory{ @@ -77,7 +97,7 @@ public void endLeg(double time) { if(currentLeg.getRoute() instanceof NetworkRoute){ NetworkRoute nRoute = (NetworkRoute) currentLeg.getRoute(); Id vehicleId = nRoute.getVehicleId(); - CarrierVehicle vehicle = CarrierUtils.getCarrierVehicle(carrier, vehicleId); + CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); assert vehicle != null : "cannot find vehicle with id=" + vehicleId; if(!employedVehicles.contains(vehicle)){ employedVehicles.add(vehicle); diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/usecases/chessboard/RunChessboardIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/usecases/chessboard/RunChessboardIT.java similarity index 58% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/usecases/chessboard/RunChessboardIT.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/usecases/chessboard/RunChessboardIT.java index 6bc1155ae7f..593b7786a62 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/usecases/chessboard/RunChessboardIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/usecases/chessboard/RunChessboardIT.java @@ -1,4 +1,25 @@ -package org.matsim.contrib.freight.usecases.chessboard; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.usecases.chessboard; import org.junit.Assert; import org.junit.Rule; diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriersIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriersIT.java new file mode 100644 index 00000000000..0749341e978 --- /dev/null +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriersIT.java @@ -0,0 +1,51 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.usecases.chessboard; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.matsim.core.config.Config; +import org.matsim.testcases.MatsimTestUtils; + +public class RunPassengerAlongWithCarriersIT { + + @Rule + public MatsimTestUtils utils = new MatsimTestUtils() ; + + @Test + public void runChessboard() { + try{ + RunPassengerAlongWithCarriers abc = new RunPassengerAlongWithCarriers(); + // --- + Config config = abc.prepareConfig(); + config.controller().setLastIteration( 1 ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + // --- + abc.run(); + } catch (Exception ee ) { + ee.printStackTrace(); + Assert.fail("something went wrong: " + ee.getMessage()); + } + } + +} diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/utils/FreightUtilsIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java similarity index 86% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/utils/FreightUtilsIT.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java index 6f9c44c6258..05f0eeb244d 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/utils/FreightUtilsIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java @@ -1,51 +1,51 @@ -/* *********************************************************************** * - * 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.freight.utils; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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 java.util.Collection; +package org.matsim.freight.carriers.utils; +import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; +import com.graphhopper.jsprit.core.algorithm.box.SchrimpfFactory; +import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; +import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; +import com.graphhopper.jsprit.core.util.Solutions; +import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.carrier.CarrierCapabilities.FleetSize; -import org.matsim.contrib.freight.controler.FreightUtils; -import org.matsim.contrib.freight.jsprit.MatsimJspritFactory; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts; -import org.matsim.contrib.freight.jsprit.NetworkRouter; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts.Builder; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.io.MatsimNetworkReader; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts.Builder; +import org.matsim.freight.carriers.jsprit.NetworkRouter; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.*; import org.matsim.vehicles.EngineInformation.FuelType; -import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; -import com.graphhopper.jsprit.core.algorithm.box.SchrimpfFactory; -import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; -import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; -import com.graphhopper.jsprit.core.util.Solutions; - -import org.junit.Assert; +import java.util.Collection; //TODO: length of routes (legs) AND end time of route are missing. @@ -53,7 +53,7 @@ * @author kturner * */ -public class FreightUtilsIT { +public class CarrierControlerUtilsIT { private final Id CARRIER_SERVICES_ID = Id.create("CarrierWServices", Carrier.class); private final Id CARRIER_SHIPMENTS_ID = Id.create("CarrierWShipments", Carrier.class); @@ -72,18 +72,18 @@ public void setUp() { //Create carrier with services and shipments Carriers carriersWithServicesAndShpiments = new Carriers(); - carrierWServices = CarrierUtils.createCarrier(CARRIER_SERVICES_ID ); + carrierWServices = CarriersUtils.createCarrier(CARRIER_SERVICES_ID ); CarrierService service1 = createMatsimService("Service1", "i(3,9)", 2); - CarrierUtils.addService(carrierWServices, service1); + CarriersUtils.addService(carrierWServices, service1); CarrierService service2 = createMatsimService("Service2", "i(4,9)", 2); - CarrierUtils.addService(carrierWServices, service2); + CarriersUtils.addService(carrierWServices, service2); //Create carrier with shipments - carrierWShipments = CarrierUtils.createCarrier(CARRIER_SHIPMENTS_ID ); + carrierWShipments = CarriersUtils.createCarrier(CARRIER_SHIPMENTS_ID ); CarrierShipment shipment1 = createMatsimShipment("shipment1", "i(1,0)", "i(7,6)R", 1); - CarrierUtils.addShipment(carrierWShipments, shipment1); + CarriersUtils.addShipment(carrierWShipments, shipment1); CarrierShipment shipment2 = createMatsimShipment("shipment2", "i(3,0)", "i(3,7)", 2); - CarrierUtils.addShipment(carrierWShipments, shipment2); + CarriersUtils.addShipment(carrierWShipments, shipment2); //Create vehicle for Carriers final Id vehTypeId = Id.create( "gridType", VehicleType.class ); @@ -97,7 +97,7 @@ public void setUp() { costInfo.setCostsPerSecond( 0.001 ) ; costInfo.setCostsPerMeter( 0.0001 ) ; costInfo.setFixedCost( 130. ) ; -// VehicleType carrierVehType = CarrierUtils.CarrierVehicleTypeBuilder.newInstance( vehTypeId ) +// VehicleType carrierVehType = CarriersUtils.CarrierVehicleTypeBuilder.newInstance( vehTypeId ) carrierVehType.setMaximumVelocity(10); CarrierVehicleTypes vehicleTypes = new CarrierVehicleTypes() ; @@ -148,7 +148,7 @@ public void setUp() { */ //Convert to jsprit VRP - Carriers carriersWithShipmentsOnly = FreightUtils.createShipmentVRPCarrierFromServiceVRPSolution( + Carriers carriersWithShipmentsOnly = CarriersUtils.createShipmentVRPCarrierFromServiceVRPSolution( carriersWithServicesAndShpiments ); // assign vehicle types to the carriers diff --git a/contribs/freight/src/test/java/org/matsim/contrib/freight/utils/FreightUtilsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java similarity index 75% rename from contribs/freight/src/test/java/org/matsim/contrib/freight/utils/FreightUtilsTest.java rename to contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java index b01f8560bf2..0f4354005b1 100644 --- a/contribs/freight/src/test/java/org/matsim/contrib/freight/utils/FreightUtilsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java @@ -1,29 +1,34 @@ -/* *********************************************************************** * - * 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.freight.utils; - -import java.net.URL; -import java.util.Collection; -import java.util.concurrent.ExecutionException; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.utils; +import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; +import com.graphhopper.jsprit.core.algorithm.box.SchrimpfFactory; +import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; +import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; +import com.graphhopper.jsprit.core.util.Solutions; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -31,14 +36,6 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.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.contrib.freight.jsprit.MatsimJspritFactory; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts.Builder; -import org.matsim.contrib.freight.jsprit.NetworkRouter; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.PlansConfigGroup; @@ -48,22 +45,25 @@ import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts.Builder; +import org.matsim.freight.carriers.jsprit.NetworkRouter; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.*; -import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm; -import com.graphhopper.jsprit.core.algorithm.box.SchrimpfFactory; -import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; -import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; -import com.graphhopper.jsprit.core.util.Solutions; -import org.junit.Assert; +import java.net.URL; +import java.util.Collection; +import java.util.concurrent.ExecutionException; -public class FreightUtilsTest { +public class CarrierControlerUtilsTest { @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - private static final Logger log = LogManager.getLogger(FreightUtilsTest.class); + private static final Logger log = LogManager.getLogger(CarrierControlerUtilsTest.class); private final Id CARRIER_SERVICES_ID = Id.create("CarrierWServices", Carrier.class); private final Id CARRIER_SHIPMENTS_ID = Id.create("CarrierWShipments", Carrier.class); @@ -82,18 +82,18 @@ public void setUp() { //Create carrier with services and shipments Carriers carriersWithServicesAndShpiments = new Carriers(); - carrierWServices = CarrierUtils.createCarrier(CARRIER_SERVICES_ID ); + carrierWServices = CarriersUtils.createCarrier(CARRIER_SERVICES_ID ); CarrierService service1 = createMatsimService("Service1", "i(3,9)", 2); - CarrierUtils.addService(carrierWServices, service1); + CarriersUtils.addService(carrierWServices, service1); CarrierService service2 = createMatsimService("Service2", "i(4,9)", 2); - CarrierUtils.addService(carrierWServices, service2); + CarriersUtils.addService(carrierWServices, service2); //Create carrier with shipments - carrierWShipments = CarrierUtils.createCarrier(CARRIER_SHIPMENTS_ID ); + carrierWShipments = CarriersUtils.createCarrier(CARRIER_SHIPMENTS_ID ); CarrierShipment shipment1 = createMatsimShipment("shipment1", "i(1,0)", "i(7,6)R", 1); - CarrierUtils.addShipment(carrierWShipments, shipment1); + CarriersUtils.addShipment(carrierWShipments, shipment1); CarrierShipment shipment2 = createMatsimShipment("shipment2", "i(3,0)", "i(3,7)", 2); - CarrierUtils.addShipment(carrierWShipments, shipment2); + CarriersUtils.addShipment(carrierWShipments, shipment2); //Create vehicle for Carriers final Id vehicleTypeId = Id.create( "gridType", VehicleType.class ); @@ -106,7 +106,7 @@ public void setUp() { costInfo.setCostsPerMeter( 0.0001 ) ; costInfo.setCostsPerSecond( 0.001 ) ; costInfo.setFixedCost( 130. ) ; -// VehicleType carrierVehType = CarrierUtils.CarrierVehicleTypeBuilder.newInstance( vehicleTypeId ) +// VehicleType carrierVehType = CarriersUtils.CarrierVehicleTypeBuilder.newInstance( vehicleTypeId ) carrierVehType.setMaximumVelocity( 10. ) ; CarrierVehicleTypes vehicleTypes = new CarrierVehicleTypes() ; vehicleTypes.getVehicleTypes().put(carrierVehType.getId(), carrierVehType); @@ -155,7 +155,7 @@ public void setUp() { */ //Convert to jsprit VRP - Carriers carriersWithShipmentsOnly = FreightUtils.createShipmentVRPCarrierFromServiceVRPSolution(carriersWithServicesAndShpiments); + Carriers carriersWithShipmentsOnly = CarriersUtils.createShipmentVRPCarrierFromServiceVRPSolution(carriersWithServicesAndShpiments); carrierWShipmentsOnlyFromCarrierWServices = carriersWithShipmentsOnly.getCarriers().get(CARRIER_SERVICES_ID); //with converted Service carrierWShipmentsOnlyFromCarrierWShipments = carriersWithShipmentsOnly.getCarriers().get(CARRIER_SHIPMENTS_ID); //with copied Shipments @@ -243,7 +243,7 @@ public void fleetAvailableAfterConvertingIsCorrect() { public void copiingOfShipmentsIsDoneCorrectly() { boolean foundShipment1 = false; boolean foundShipment2 = false; - CarrierShipment carrierShipment1 = CarrierUtils.getShipment(carrierWShipmentsOnlyFromCarrierWShipments, Id.create("shipment1", CarrierShipment.class)); + CarrierShipment carrierShipment1 = CarriersUtils.getShipment(carrierWShipmentsOnlyFromCarrierWShipments, Id.create("shipment1", CarrierShipment.class)); assert carrierShipment1 != null; if (carrierShipment1.getId() == Id.create("shipment1", CarrierShipment.class)) { System.out.println("Found Shipment1"); @@ -258,7 +258,7 @@ public void copiingOfShipmentsIsDoneCorrectly() { Assert.assertEquals(0.0, carrierShipment1.getPickupTimeWindow().getStart(), 0); Assert.assertEquals(7200.0, carrierShipment1.getPickupTimeWindow().getEnd(), 0); } - CarrierShipment carrierShipment2 = CarrierUtils.getShipment(carrierWShipmentsOnlyFromCarrierWShipments, Id.create("shipment2", CarrierShipment.class)); + CarrierShipment carrierShipment2 = CarriersUtils.getShipment(carrierWShipmentsOnlyFromCarrierWShipments, Id.create("shipment2", CarrierShipment.class)); assert carrierShipment2 != null; if (carrierShipment2.getId() == Id.create("shipment2", CarrierShipment.class)) { System.out.println("Found Shipment2"); @@ -282,7 +282,7 @@ public void copiingOfShipmentsIsDoneCorrectly() { public void convertionOfServicesIsDoneCorrectly() { boolean foundSercice1 = false; boolean foundService2 = false; - CarrierShipment carrierShipment1 = CarrierUtils.getShipment(carrierWShipmentsOnlyFromCarrierWServices, Id.create("Service1", CarrierShipment.class)); + CarrierShipment carrierShipment1 = CarriersUtils.getShipment(carrierWShipmentsOnlyFromCarrierWServices, Id.create("Service1", CarrierShipment.class)); assert carrierShipment1 != null; if (carrierShipment1.getId() == Id.create("Service1", CarrierShipment.class)) { foundSercice1 = true; @@ -296,7 +296,7 @@ public void convertionOfServicesIsDoneCorrectly() { Assert.assertEquals(0.0, carrierShipment1.getPickupTimeWindow().getStart(), 0); Assert.assertEquals(36001.0, carrierShipment1.getPickupTimeWindow().getEnd(), 0); } - CarrierShipment carrierShipment2 = CarrierUtils.getShipment(carrierWShipmentsOnlyFromCarrierWServices, Id.create("Service2", CarrierShipment.class)); + CarrierShipment carrierShipment2 = CarriersUtils.getShipment(carrierWShipmentsOnlyFromCarrierWServices, Id.create("Service2", CarrierShipment.class)); assert carrierShipment2 != null; if (carrierShipment2.getId() == Id.create("Service2", CarrierShipment.class)) { foundService2 = true; @@ -320,11 +320,11 @@ public void convertionOfServicesIsDoneCorrectly() { */ @Test(expected=UnsupportedOperationException.class) public void exceptionIsThrownWhenUsingMixedShipmentsAndServices() { - Carrier carrierMixedWServicesAndShipments = CarrierUtils.createCarrier(Id.create("CarrierMixed", Carrier.class ) ); + Carrier carrierMixedWServicesAndShipments = CarriersUtils.createCarrier(Id.create("CarrierMixed", Carrier.class ) ); CarrierService service1 = createMatsimService("Service1", "i(3,9)", 2); - CarrierUtils.addService(carrierMixedWServicesAndShipments, service1); + CarriersUtils.addService(carrierMixedWServicesAndShipments, service1); CarrierShipment shipment1 = createMatsimShipment("shipment1", "i(1,0)", "i(7,6)R", 1); - CarrierUtils.addShipment(carrierMixedWServicesAndShipments, shipment1); + CarriersUtils.addShipment(carrierMixedWServicesAndShipments, shipment1); Network network = NetworkUtils.createNetwork(); new MatsimNetworkReader(network).readFile(testUtils.getPackageInputDirectory() + "grid-network.xml"); @@ -364,15 +364,15 @@ private static CarrierService createMatsimService(String id, String to, int size public void testAddVehicleTypeSkill(){ VehiclesFactory factory = ScenarioUtils.createScenario(ConfigUtils.createConfig()).getVehicles().getFactory(); VehicleType type = factory.createVehicleType(Id.create("test", VehicleType.class)); - Assert.assertFalse("Should not have skill.", FreightUtils.hasSkill(type, "testSkill")); + Assert.assertFalse("Should not have skill.", CarriersUtils.hasSkill(type, "testSkill")); - FreightUtils.addSkill(type, "testSkillOne"); - Assert.assertTrue("Should have skill 'testSkillOne'.", FreightUtils.hasSkill(type, "testSkillOne")); + CarriersUtils.addSkill(type, "testSkillOne"); + Assert.assertTrue("Should have skill 'testSkillOne'.", CarriersUtils.hasSkill(type, "testSkillOne")); - FreightUtils.addSkill(type, "testSkillTwo"); - Assert.assertTrue("Should have skill 'testSkillOne'.", FreightUtils.hasSkill(type, "testSkillOne")); - Assert.assertTrue("Should have skill 'testSkillTwo'.", FreightUtils.hasSkill(type, "testSkillTwo")); + CarriersUtils.addSkill(type, "testSkillTwo"); + Assert.assertTrue("Should have skill 'testSkillOne'.", CarriersUtils.hasSkill(type, "testSkillOne")); + Assert.assertTrue("Should have skill 'testSkillTwo'.", CarriersUtils.hasSkill(type, "testSkillTwo")); } @Test @@ -380,15 +380,15 @@ public void testAddShipmentSkill(){ CarrierShipment shipment = CarrierShipment.Builder.newInstance( Id.create("testShipment", CarrierShipment.class), Id.createLinkId("1"), Id.createLinkId("2"), 1) .build(); - Assert.assertFalse("Should not have skill.", FreightUtils.hasSkill(shipment, "testSkill")); + Assert.assertFalse("Should not have skill.", CarriersUtils.hasSkill(shipment, "testSkill")); - FreightUtils.addSkill(shipment, "testSkillOne"); - Assert.assertTrue("Should have skill 'testSkillOne'.", FreightUtils.hasSkill(shipment, "testSkillOne")); + CarriersUtils.addSkill(shipment, "testSkillOne"); + Assert.assertTrue("Should have skill 'testSkillOne'.", CarriersUtils.hasSkill(shipment, "testSkillOne")); - FreightUtils.addSkill(shipment, "testSkillTwo"); - Assert.assertTrue("Should have skill 'testSkillOne'.", FreightUtils.hasSkill(shipment, "testSkillOne")); - Assert.assertTrue("Should have skill 'testSkillTwo'.", FreightUtils.hasSkill(shipment, "testSkillTwo")); + CarriersUtils.addSkill(shipment, "testSkillTwo"); + Assert.assertTrue("Should have skill 'testSkillOne'.", CarriersUtils.hasSkill(shipment, "testSkillOne")); + Assert.assertTrue("Should have skill 'testSkillTwo'.", CarriersUtils.hasSkill(shipment, "testSkillTwo")); } @Test @@ -396,41 +396,41 @@ public void testAddServiceSkill(){ CarrierService service = CarrierService.Builder.newInstance( Id.create("testShipment", CarrierService.class), Id.createLinkId("2")) .build(); - Assert.assertFalse("Should not have skill.", FreightUtils.hasSkill(service, "testSkill")); + Assert.assertFalse("Should not have skill.", CarriersUtils.hasSkill(service, "testSkill")); - FreightUtils.addSkill(service, "testSkillOne"); - Assert.assertTrue("Should have skill 'testSkillOne'.", FreightUtils.hasSkill(service, "testSkillOne")); + CarriersUtils.addSkill(service, "testSkillOne"); + Assert.assertTrue("Should have skill 'testSkillOne'.", CarriersUtils.hasSkill(service, "testSkillOne")); - FreightUtils.addSkill(service, "testSkillTwo"); - Assert.assertTrue("Should have skill 'testSkillOne'.", FreightUtils.hasSkill(service, "testSkillOne")); - Assert.assertTrue("Should have skill 'testSkillTwo'.", FreightUtils.hasSkill(service, "testSkillTwo")); + CarriersUtils.addSkill(service, "testSkillTwo"); + Assert.assertTrue("Should have skill 'testSkillOne'.", CarriersUtils.hasSkill(service, "testSkillOne")); + Assert.assertTrue("Should have skill 'testSkillTwo'.", CarriersUtils.hasSkill(service, "testSkillTwo")); } @Test public void testRunJsprit_allInformationGiven(){ Config config = prepareConfig(); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); URL scenarioUrl = ExamplesUtils.getTestScenarioURL( "freight-chessboard-9x9" ) ; String vraFile= IOUtils.extendUrl(scenarioUrl, "algorithm_v2.xml" ).toString(); - FreightConfigGroup freightConfig = ConfigUtils.addOrGetModule( config, FreightConfigGroup.class ) ; + FreightCarriersConfigGroup freightConfig = ConfigUtils.addOrGetModule( config, FreightCarriersConfigGroup.class ) ; freightConfig.setVehicleRoutingAlgorithmFileFile(vraFile); Scenario scenario = ScenarioUtils.loadScenario(config); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario ); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario ); Controler controler = new Controler(scenario); try { - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } - Assert.assertEquals(vraFile, ConfigUtils.addOrGetModule( controler.getConfig(), FreightConfigGroup.class ).getVehicleRoutingAlgorithmFile()); + Assert.assertEquals(vraFile, ConfigUtils.addOrGetModule( controler.getConfig(), FreightCarriersConfigGroup.class ).getVehicleRoutingAlgorithmFile()); } /** @@ -439,18 +439,18 @@ public void testRunJsprit_allInformationGiven(){ @Test(expected = java.util.concurrent.ExecutionException.class) public void testRunJsprit_NoOfJspritIterationsMissing() throws ExecutionException, InterruptedException { Config config = prepareConfig(); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Scenario scenario = ScenarioUtils.loadScenario(config); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); //remove all attributes --> remove the NumberOfJspritIterations attribute to trigger exception - Carriers carriers = FreightUtils.getCarriers(scenario); + Carriers carriers = CarriersUtils.getCarriers(scenario); for (Carrier carrier : carriers.getCarriers().values()) { carrier.getAttributes().clear(); } - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); } /** @@ -459,29 +459,29 @@ public void testRunJsprit_NoOfJspritIterationsMissing() throws ExecutionExceptio @Test public void testRunJsprit_NoAlgortihmFileGiven(){ Config config = prepareConfig(); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Scenario scenario = ScenarioUtils.loadScenario(config); - FreightUtils.loadCarriersAccordingToFreightConfig(scenario); + CarriersUtils.loadCarriersAccordingToFreightConfig(scenario); try { - FreightUtils.runJsprit(scenario); + CarriersUtils.runJsprit(scenario); } catch (Exception e) { Assert.fail(); } - Assert.assertNull(ConfigUtils.addOrGetModule(scenario.getConfig(), FreightConfigGroup.class).getVehicleRoutingAlgorithmFile()); + Assert.assertNull(ConfigUtils.addOrGetModule(scenario.getConfig(), FreightCarriersConfigGroup.class).getVehicleRoutingAlgorithmFile()); } private Config prepareConfig(){ URL scenarioUrl = ExamplesUtils.getTestScenarioURL( "freight-chessboard-9x9" ) ; Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(scenarioUrl, "config.xml" ) ); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); config.plans().setActivityDurationInterpretation(PlansConfigGroup.ActivityDurationInterpretation.tryEndTimeThenDuration ); //freight configstuff - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule(config, FreightConfigGroup.class); - freightConfigGroup.setCarriersFile(IOUtils.extendUrl(scenarioUrl, "singleCarrierFiveActivitiesWithoutRoutes.xml" ).toString() ); - freightConfigGroup.setCarriersVehicleTypesFile(IOUtils.extendUrl(scenarioUrl, "vehicleTypes.xml" ).toString() ); - freightConfigGroup.setTravelTimeSliceWidth(24*3600); - freightConfigGroup.setTimeWindowHandling(FreightConfigGroup.TimeWindowHandling.enforceBeginnings); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule(config, FreightCarriersConfigGroup.class); + freightCarriersConfigGroup.setCarriersFile(IOUtils.extendUrl(scenarioUrl, "singleCarrierFiveActivitiesWithoutRoutes.xml" ).toString() ); + freightCarriersConfigGroup.setCarriersVehicleTypesFile(IOUtils.extendUrl(scenarioUrl, "vehicleTypes.xml" ).toString() ); + freightCarriersConfigGroup.setTravelTimeSliceWidth(24*3600); + freightCarriersConfigGroup.setTimeWindowHandling(FreightCarriersConfigGroup.TimeWindowHandling.enforceBeginnings); return config; } diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/usecases/chessboard/RunChessboardIT/runChessboard/output_events.xml.gz b/contribs/freight/test/input/org/matsim/contrib/freight/usecases/chessboard/RunChessboardIT/runChessboard/output_events.xml.gz deleted file mode 100644 index 0a2fb55c999..00000000000 Binary files a/contribs/freight/test/input/org/matsim/contrib/freight/usecases/chessboard/RunChessboardIT/runChessboard/output_events.xml.gz and /dev/null differ diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/usecases/chessboard/RunChessboardIT/runChessboard/output_plans.xml.gz b/contribs/freight/test/input/org/matsim/contrib/freight/usecases/chessboard/RunChessboardIT/runChessboard/output_plans.xml.gz deleted file mode 100644 index f2c6b3d4e47..00000000000 Binary files a/contribs/freight/test/input/org/matsim/contrib/freight/usecases/chessboard/RunChessboardIT/runChessboard/output_plans.xml.gz and /dev/null differ diff --git a/contribs/freight/test/input/org/matsim/freight/carriers/CarrierEventsReadersTest/serviceBasedEvents.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierEventsReadersTest/serviceBasedEvents.xml new file mode 100644 index 00000000000..b4121096264 --- /dev/null +++ b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierEventsReadersTest/serviceBasedEvents.xml @@ -0,0 +1,213 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/contribs/freight/test/input/org/matsim/freight/carriers/CarrierEventsReadersTest/shipmentBasedEvents.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierEventsReadersTest/shipmentBasedEvents.xml new file mode 100644 index 00000000000..ca675a9bcbf --- /dev/null +++ b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierEventsReadersTest/shipmentBasedEvents.xml @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierModuleTest/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierModuleTest/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierModuleTest/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierModuleTest/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierModuleTest/network.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierModuleTest/network.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierModuleTest/network.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierModuleTest/network.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierModuleTest/plans100.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierModuleTest/plans100.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierModuleTest/plans100.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierModuleTest/plans100.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierModuleTest/vehicleTypes.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierModuleTest/vehicleTypes.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierModuleTest/vehicleTypes.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierModuleTest/vehicleTypes.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1Test/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanReaderV1Test/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1Test/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanReaderV1Test/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1Test/carrierPlansEquils_unscored_unselected.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanReaderV1Test/carrierPlansEquils_unscored_unselected.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanReaderV1Test/carrierPlansEquils_unscored_unselected.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanReaderV1Test/carrierPlansEquils_unscored_unselected.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2Test/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2Test/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2Test/carrierPlansEquilsFiniteFleet.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test/carrierPlansEquilsFiniteFleet.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2Test/carrierPlansEquilsFiniteFleet.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test/carrierPlansEquilsFiniteFleet.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2WithDtdTest/carrierPlansEquilsFiniteFleetWithDtd.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest/carrierPlansEquilsFiniteFleetWithDtd.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2WithDtdTest/carrierPlansEquilsFiniteFleetWithDtd.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest/carrierPlansEquilsFiniteFleetWithDtd.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2WithDtdTest/carrierPlansEquilsWithDtd.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest/carrierPlansEquilsWithDtd.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlReaderV2WithDtdTest/carrierPlansEquilsWithDtd.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest/carrierPlansEquilsWithDtd.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV1Test/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlWriterV1Test/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV1Test/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlWriterV1Test/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2Test/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2Test/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2Test/carrierPlansEquilsWritten.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test/carrierPlansEquilsWritten.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2Test/carrierPlansEquilsWritten.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test/carrierPlansEquilsWritten.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2_1Test/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierPlanXmlWriterV2_1Test/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierReadWriteV2_1Test/carriers.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierReadWriteV2_1Test/carriers.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierReadWriteV2_1Test/carriers.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierReadWriteV2_1Test/carriers.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierReadWriteV2_1Test/vehicles.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierReadWriteV2_1Test/vehicles.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierReadWriteV2_1Test/vehicles.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierReadWriteV2_1Test/vehicles.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoaderTest/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoaderTest/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoaderTest/vehicleTypes.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest/vehicleTypes.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeLoaderTest/vehicleTypes.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest/vehicleTypes.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderTest/vehicleTypes.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest/vehicleTypes.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderTest/vehicleTypes.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest/vehicleTypes.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderTest/vehicleTypes_v2.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest/vehicleTypes_v2.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderTest/vehicleTypes_v2.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest/vehicleTypes_v2.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderWithDtdV1Test/carrierVehicleTypes_v1.xsd b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeReaderWithDtdV1Test/carrierVehicleTypes_v1.xsd similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderWithDtdV1Test/carrierVehicleTypes_v1.xsd rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeReaderWithDtdV1Test/carrierVehicleTypes_v1.xsd diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderWithDtdV1Test/carrierVehicleTypes_v2.xsd b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeReaderWithDtdV1Test/carrierVehicleTypes_v2.xsd similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeReaderWithDtdV1Test/carrierVehicleTypes_v2.xsd rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeReaderWithDtdV1Test/carrierVehicleTypes_v2.xsd diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriterTest/vehicleTypes.xml b/contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeWriterTest/vehicleTypes.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/CarrierVehicleTypeWriterTest/vehicleTypes.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/CarrierVehicleTypeWriterTest/vehicleTypes.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/algorithms/SetupSimpleFreightScenarioTest/testSetupScenario/grid10.xml b/contribs/freight/test/input/org/matsim/freight/carriers/algorithms/SetupSimpleFreightScenarioTest/testSetupScenario/grid10.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/algorithms/SetupSimpleFreightScenarioTest/testSetupScenario/grid10.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/algorithms/SetupSimpleFreightScenarioTest/testSetupScenario/grid10.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithPersonsIT/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithPersonsIT/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithPersonsIT/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithPersonsIT/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithPersonsIT/network.xml b/contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithPersonsIT/network.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithPersonsIT/network.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithPersonsIT/network.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithPersonsIT/plans100.xml b/contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithPersonsIT/plans100.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithPersonsIT/plans100.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithPersonsIT/plans100.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithoutPersonsIT/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithoutPersonsIT/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithoutPersonsIT/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithoutPersonsIT/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithoutPersonsIT/network.xml b/contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithoutPersonsIT/network.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithoutPersonsIT/network.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithoutPersonsIT/network.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithoutPersonsIT/output_events.xml.gz b/contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithoutPersonsIT/output_events.xml.gz similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/controler/EquilWithCarrierWithoutPersonsIT/output_events.xml.gz rename to contribs/freight/test/input/org/matsim/freight/carriers/controler/EquilWithCarrierWithoutPersonsIT/output_events.xml.gz diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/controler/vehicleTypes_v2.xml b/contribs/freight/test/input/org/matsim/freight/carriers/controler/vehicleTypes_v2.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/controler/vehicleTypes_v2.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/controler/vehicleTypes_v2.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/jsprit/IntegrationIT/carrier.xml b/contribs/freight/test/input/org/matsim/freight/carriers/jsprit/IntegrationIT/carrier.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/jsprit/IntegrationIT/carrier.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/jsprit/IntegrationIT/carrier.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/jsprit/IntegrationIT/merged-network-simplified.xml.gz b/contribs/freight/test/input/org/matsim/freight/carriers/jsprit/IntegrationIT/merged-network-simplified.xml.gz similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/jsprit/IntegrationIT/merged-network-simplified.xml.gz rename to contribs/freight/test/input/org/matsim/freight/carriers/jsprit/IntegrationIT/merged-network-simplified.xml.gz diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/jsprit/IntegrationIT/vehicleTypes.xml b/contribs/freight/test/input/org/matsim/freight/carriers/jsprit/IntegrationIT/vehicleTypes.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/jsprit/IntegrationIT/vehicleTypes.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/jsprit/IntegrationIT/vehicleTypes.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/jsprit/MatsimTransformerTest/grid-network.xml b/contribs/freight/test/input/org/matsim/freight/carriers/jsprit/MatsimTransformerTest/grid-network.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/jsprit/MatsimTransformerTest/grid-network.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/jsprit/MatsimTransformerTest/grid-network.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCostsTest/network.xml b/contribs/freight/test/input/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsTest/network.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/jsprit/NetworkBasedTransportCostsTest/network.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsTest/network.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/jsprit/SkillsIT/grid-network.xml b/contribs/freight/test/input/org/matsim/freight/carriers/jsprit/SkillsIT/grid-network.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/jsprit/SkillsIT/grid-network.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/jsprit/SkillsIT/grid-network.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/jsprit/vehicleTypesForDCTest.xml b/contribs/freight/test/input/org/matsim/freight/carriers/jsprit/vehicleTypesForDCTest.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/jsprit/vehicleTypesForDCTest.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/jsprit/vehicleTypesForDCTest.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/mobsim/CarrierAgentTest/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/mobsim/CarrierAgentTest/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/mobsim/CarrierAgentTest/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/mobsim/CarrierAgentTest/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/mobsim/CarrierAgentTest/network.xml b/contribs/freight/test/input/org/matsim/freight/carriers/mobsim/CarrierAgentTest/network.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/mobsim/CarrierAgentTest/network.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/mobsim/CarrierAgentTest/network.xml diff --git a/contribs/freight/test/input/org/matsim/freight/carriers/usecases/chessboard/RunChessboardIT/runChessboard/output_events.xml.gz b/contribs/freight/test/input/org/matsim/freight/carriers/usecases/chessboard/RunChessboardIT/runChessboard/output_events.xml.gz new file mode 100644 index 00000000000..8057a55fbcc Binary files /dev/null and b/contribs/freight/test/input/org/matsim/freight/carriers/usecases/chessboard/RunChessboardIT/runChessboard/output_events.xml.gz differ diff --git a/contribs/freight/test/input/org/matsim/freight/carriers/usecases/chessboard/RunChessboardIT/runChessboard/output_plans.xml.gz b/contribs/freight/test/input/org/matsim/freight/carriers/usecases/chessboard/RunChessboardIT/runChessboard/output_plans.xml.gz new file mode 100644 index 00000000000..3ca1e52a85a Binary files /dev/null and b/contribs/freight/test/input/org/matsim/freight/carriers/usecases/chessboard/RunChessboardIT/runChessboard/output_plans.xml.gz differ diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/utils/grid-network.xml b/contribs/freight/test/input/org/matsim/freight/carriers/utils/grid-network.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/utils/grid-network.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/utils/grid-network.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/carrier/vehicleTypes_v2.xml b/contribs/freight/test/input/org/matsim/freight/carriers/vehicleTypes_v2.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/carrier/vehicleTypes_v2.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/vehicleTypes_v2.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/vrp/Matsim2VrpUtilsTest/testCreateTours/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/vrp/Matsim2VrpUtilsTest/testCreateTours/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/vrp/Matsim2VrpUtilsTest/testCreateTours/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/vrp/Matsim2VrpUtilsTest/testCreateTours/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/vrp/Matsim2VrpUtilsTest/testCreateVehicleRoutes/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/vrp/Matsim2VrpUtilsTest/testCreateVehicleRoutes/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/vrp/Matsim2VrpUtilsTest/testCreateVehicleRoutes/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/vrp/Matsim2VrpUtilsTest/testCreateVehicleRoutes/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/vrp/MatsimVrpSolverImplTest/testSelectedPlanIsInitialSolution/carrierPlansEquils.xml b/contribs/freight/test/input/org/matsim/freight/carriers/vrp/MatsimVrpSolverImplTest/testSelectedPlanIsInitialSolution/carrierPlansEquils.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/vrp/MatsimVrpSolverImplTest/testSelectedPlanIsInitialSolution/carrierPlansEquils.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/vrp/MatsimVrpSolverImplTest/testSelectedPlanIsInitialSolution/carrierPlansEquils.xml diff --git a/contribs/freight/test/input/org/matsim/contrib/freight/vrp/MatsimVrpSolverImplTest/testSelectedPlanIsInitialSolution/network.xml b/contribs/freight/test/input/org/matsim/freight/carriers/vrp/MatsimVrpSolverImplTest/testSelectedPlanIsInitialSolution/network.xml similarity index 100% rename from contribs/freight/test/input/org/matsim/contrib/freight/vrp/MatsimVrpSolverImplTest/testSelectedPlanIsInitialSolution/network.xml rename to contribs/freight/test/input/org/matsim/freight/carriers/vrp/MatsimVrpSolverImplTest/testSelectedPlanIsInitialSolution/network.xml diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverAgent.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverAgent.java index cf9fc8839dd..df29bc43a71 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverAgent.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverAgent.java @@ -22,9 +22,9 @@ 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.Carriers; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.Carriers; import org.matsim.core.scoring.ScoringFunction; import java.util.ArrayList; @@ -70,7 +70,7 @@ public void scoreSelectedPlan(Scenario scenario, ReceiverCostAllocation costAllo return; } - Carriers carriers = FreightUtils.getCarriers(scenario); + Carriers carriers = CarriersUtils.getCarriers(scenario); double score = 0.0; List> carrierIds = new ArrayList<>(); diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverControlerListener.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverControlerListener.java index 698bd61b5d7..10fe1be6bdd 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverControlerListener.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverControlerListener.java @@ -25,10 +25,10 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.HasPlansAndId; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.ScheduledTour; -import org.matsim.contrib.freight.carrier.Tour; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.ScheduledTour; +import org.matsim.freight.carriers.Tour; import org.matsim.contrib.freightreceiver.collaboration.CollaborationUtils; import org.matsim.contrib.freightreceiver.replanning.ReceiverStrategyManager; import org.matsim.core.config.ConfigUtils; @@ -165,11 +165,11 @@ private void linkReceiverTimeWindowToCarrierTourPosition() throws IOException { receiverLinkMap.put(linkId, receiver); } - try (BufferedWriter bw = IOUtils.getBufferedWriter(this.sc.getConfig().controler().getOutputDirectory() + "output_receiverInTourPlacement.csv.gz")) { + try (BufferedWriter bw = IOUtils.getBufferedWriter(this.sc.getConfig().controller().getOutputDirectory() + "output_receiverInTourPlacement.csv.gz")) { bw.write("receiverId,twStart,twEnd,twDuration,positionInTour,product,deliveryStart,deliveryEnd"); bw.newLine(); - for (Carrier carrier : FreightUtils.getCarriers(this.sc).getCarriers().values()) { + for (Carrier carrier : CarriersUtils.getCarriers(this.sc).getCarriers().values()) { Collection scheduledTours = carrier.getSelectedPlan().getScheduledTours(); for (ScheduledTour tour : scheduledTours) { for (int i = 0; i < tour.getTour().getTourElements().size(); i++) { diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocation.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocation.java index c7b7ae3e141..72ccdeb68fa 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocation.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocation.java @@ -20,7 +20,7 @@ package org.matsim.contrib.freightreceiver; -import org.matsim.contrib.freight.carrier.Carrier; +import org.matsim.freight.carriers.Carrier; public interface ReceiverCostAllocation { double getScore(Carrier carrier, Receiver receiver); diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocationEqualProportion.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocationEqualProportion.java index a2905150735..6f85efcd2f1 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocationEqualProportion.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocationEqualProportion.java @@ -23,7 +23,7 @@ import com.google.inject.Inject; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.carrier.Carrier; +import org.matsim.freight.carriers.Carrier; import java.util.*; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocationFixed.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocationFixed.java index 2e12e2cc4f5..5f3a6a2dea2 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocationFixed.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverCostAllocationFixed.java @@ -20,7 +20,7 @@ package org.matsim.contrib.freightreceiver; import org.apache.logging.log4j.LogManager; -import org.matsim.contrib.freight.carrier.Carrier; +import org.matsim.freight.carriers.Carrier; /** * A simple implementation where the cost allocated by the {@link Carrier} to diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverModule.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverModule.java index eadce5c1518..aac11b5e7b2 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverModule.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverModule.java @@ -20,7 +20,7 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; -import org.matsim.contrib.freight.carrier.Carrier; +import org.matsim.freight.carriers.Carrier; import org.matsim.contrib.freightreceiver.replanning.*; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.AbstractModule; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverOrder.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverOrder.java index 0ce8984c076..081004dcb71 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverOrder.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverOrder.java @@ -22,7 +22,7 @@ import org.apache.logging.log4j.LogManager; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.BasicPlan; -import org.matsim.contrib.freight.carrier.Carrier; +import org.matsim.freight.carriers.Carrier; import java.util.ArrayList; import java.util.Collection; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverPlan.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverPlan.java index abbb8821a25..0497d364b3d 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverPlan.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverPlan.java @@ -23,8 +23,8 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.BasicPlan; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.TimeWindow; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.TimeWindow; import org.matsim.contrib.freightreceiver.collaboration.CollaborationUtils; import org.matsim.utils.objectattributes.attributable.Attributable; import org.matsim.utils.objectattributes.attributable.Attributes; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverScoreStats.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverScoreStats.java index 8e9d8c3de75..a9a63491a07 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverScoreStats.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverScoreStats.java @@ -4,7 +4,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.CarriersUtils; import org.matsim.contrib.freightreceiver.collaboration.CollaborationUtils; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.events.IterationEndsEvent; @@ -15,11 +15,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.io.BufferedWriter; import java.io.File; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.Locale; /** @@ -58,7 +58,7 @@ public ReceiverScoreStats() throws UncheckedIOException { @Override public void notifyStartup(final StartupEvent event) { - String fileName = sc.getConfig().controler().getOutputDirectory() + ReceiverUtils.FILENAME_RECEIVER_SCORES; + String fileName = sc.getConfig().controller().getOutputDirectory() + ReceiverUtils.FILENAME_RECEIVER_SCORES; if (fileName.toLowerCase(Locale.ROOT).endsWith(".txt")) { this.out = IOUtils.getBufferedWriter(fileName); } else { @@ -69,8 +69,8 @@ public void notifyStartup(final StartupEvent event) { } catch (IOException e) { throw new UncheckedIOException(e); } - this.minIteration = event.getServices().getConfig().controler().getFirstIteration(); - int maxIter = event.getServices().getConfig().controler().getLastIteration(); + this.minIteration = event.getServices().getConfig().controller().getFirstIteration(); + int maxIter = event.getServices().getConfig().controller().getLastIteration(); int iterations = maxIter - this.minIteration; if (iterations > 5000) iterations = 5000; // limit the history size this.history = new double[4][iterations + 1]; @@ -92,12 +92,12 @@ public void notifyIterationEnds(final IterationEndsEvent event) { if ((event.getIteration() + 1) % (ConfigUtils.addOrGetModule(sc.getConfig(), ReceiverConfigGroup.class).getReceiverReplanningInterval()) != 0) return; String dir = event.getServices().getControlerIO().getIterationPath(event.getIteration()); - FreightUtils.writeCarriers(FreightUtils.getCarriers(sc), dir + File.separator + event.getIteration() + CARRIER_PLANS_XML); + CarriersUtils.writeCarriers(CarriersUtils.getCarriers(sc), dir + File.separator + event.getIteration() + CARRIER_PLANS_XML); new ReceiversWriter(ReceiverUtils.getReceivers(sc)).write(dir + File.separator + event.getIteration() + RECEIVER_PLANS_XML); } private void writeIterationScores(IterationEndsEvent event) { - String fileName = sc.getConfig().controler().getOutputDirectory() + ReceiverUtils.FILENAME_RECEIVER_SCORES; + String fileName = sc.getConfig().controller().getOutputDirectory() + ReceiverUtils.FILENAME_RECEIVER_SCORES; double sumScoreWorst = 0.0; double sumScoreBest = 0.0; @@ -228,7 +228,7 @@ public void notifyShutdown(final ShutdownEvent controlerShudownEvent) { } static void writeHeadings(Scenario sc) { - try(BufferedWriter bw = IOUtils.getBufferedWriter(sc.getConfig().controler().getOutputDirectory() + RECEIVER_STATS_CSV)) { + try(BufferedWriter bw = IOUtils.getBufferedWriter(sc.getConfig().controller().getOutputDirectory() + RECEIVER_STATS_CSV)) { bw.write(String.format("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s", "iteration", "receiver_id", @@ -264,7 +264,7 @@ private void recordReceiverStats(IterationEndsEvent event) { boolean member = (boolean) receiver.getAttributes().getAttribute(CollaborationUtils.ATTR_GRANDCOALITION_MEMBER); - try (BufferedWriter bw1 = IOUtils.getAppendingBufferedWriter(sc.getConfig().controler().getOutputDirectory() + RECEIVER_STATS_CSV)) { + try (BufferedWriter bw1 = IOUtils.getAppendingBufferedWriter(sc.getConfig().controller().getOutputDirectory() + RECEIVER_STATS_CSV)) { bw1.write(String.format("%d,%s,%s,%f,%f,%f,%s,%f,%f,%f,%b,%b", event.getIteration(), receiver.getId(), diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverTriggersCarrierReplanningListener.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverTriggersCarrierReplanningListener.java index b5c5fa34062..938bef0d1d3 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverTriggersCarrierReplanningListener.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverTriggersCarrierReplanningListener.java @@ -25,11 +25,10 @@ import org.apache.logging.log4j.LogManager; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.controler.FreightUtils; -import org.matsim.contrib.freight.jsprit.MatsimJspritFactory; -import org.matsim.contrib.freight.jsprit.NetworkBasedTransportCosts; -import org.matsim.contrib.freight.jsprit.NetworkRouter; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.jsprit.MatsimJspritFactory; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.freight.carriers.jsprit.NetworkRouter; import org.matsim.contrib.freightreceiver.collaboration.CollaborationUtils; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.events.IterationStartsEvent; @@ -61,7 +60,7 @@ public void notifyIterationStarts(IterationStartsEvent event) { CollaborationUtils.setCoalitionFromReceiverAttributes( sc ); // clean out plans, services, shipments from carriers: - Map, Carrier> carriers = FreightUtils.getCarriers(sc).getCarriers(); + Map, Carrier> carriers = CarriersUtils.getCarriers(sc).getCarriers(); for( Carrier carrier : carriers.values() ){ carrier.clearPlans(); carrier.getShipments().clear(); @@ -119,10 +118,10 @@ public void notifyIterationStarts(IterationStartsEvent event) { carrier.setSelectedPlan(newPlan); } - String outputdirectory = sc.getConfig().controler().getOutputDirectory(); + String outputdirectory = sc.getConfig().controller().getOutputDirectory(); outputdirectory += outputdirectory.endsWith("/") ? "" : "/"; -// new CarrierPlanWriter(FreightUtils.getCarriers(sc)).write(outputdirectory + ReceiverConfigGroup.CARRIERS_FILE); - new CarrierPlanWriter(FreightUtils.getCarriers(sc)).write(outputdirectory +receiverConfig.getCarriersFile() ); +// new CarrierPlanWriter(CarrierControlerUtils.getCarriers(sc)).write(outputdirectory + ReceiverConfigGroup.CARRIERS_FILE); + new CarrierPlanWriter(CarriersUtils.getCarriers(sc)).write(outputdirectory +receiverConfig.getCarriersFile() ); // new ReceiversWriter( ReceiverUtils.getReceivers( sc ) ).write(outputdirectory + ReceiverConfigGroup.RECEIVERS_FILE); new ReceiversWriter( ReceiverUtils.getReceivers( sc ) ).write(outputdirectory + receiverConfig.getReceiversFile()); } diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverUtils.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverUtils.java index 47bad03c44c..dcd2861daed 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverUtils.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiverUtils.java @@ -5,7 +5,7 @@ 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.Carrier; +import org.matsim.freight.carriers.Carrier; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; @@ -19,7 +19,7 @@ private ReceiverUtils() { public static final String ATTR_RECEIVER_SCORE = "score"; public static final String ATTR_RECEIVER_TW_COST = "twCost"; - //Now using the MATSim-infrastructure to avoid problems if this element is named differently beetween (MATSim) FreightUtils and here. + //Now using the MATSim-infrastructure to avoid problems if this element is named differently beetween (MATSim) CarrierControlerUtils and here. // I also replaced the usage here by the current MATSim syntax KMT'jan21 // private static final String CARRIERS_SCENARIO_ELEMENT = "carriers"; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversReaderV2.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversReaderV2.java index b0c5de62e52..2036326c078 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversReaderV2.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversReaderV2.java @@ -22,8 +22,8 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.TimeWindow; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.TimeWindow; import org.matsim.contrib.freightreceiver.collaboration.CollaborationUtils; import org.matsim.core.api.internal.MatsimReader; import org.matsim.core.utils.io.MatsimXmlParser; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriter.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriter.java index e8573765c22..cd9e2f33a06 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriter.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriter.java @@ -22,12 +22,12 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; -import org.matsim.contrib.freight.carrier.TimeWindow; +import org.matsim.freight.carriers.TimeWindow; import org.matsim.core.api.internal.MatsimWriter; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.Counter; import java.io.IOException; +import java.io.UncheckedIOException; /** * Writes a {@link Receivers} container in the MATSim XML format. diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandler.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandler.java index 40e036b6775..09172159e06 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandler.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandler.java @@ -20,7 +20,7 @@ package org.matsim.contrib.freightreceiver; -import org.matsim.contrib.freight.carrier.TimeWindow; +import org.matsim.freight.carriers.TimeWindow; import java.io.BufferedWriter; import java.io.IOException; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandlerImplV1.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandlerImplV1.java index cdf7ee41b7a..ecc7b58f43e 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandlerImplV1.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandlerImplV1.java @@ -20,7 +20,7 @@ package org.matsim.contrib.freightreceiver; -import org.matsim.contrib.freight.carrier.TimeWindow; +import org.matsim.freight.carriers.TimeWindow; import org.matsim.core.utils.misc.Time; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesXmlWriterDelegate; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandlerImplV2.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandlerImplV2.java index c2f4e8f55db..c2b8fe50f1b 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandlerImplV2.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/ReceiversWriterHandlerImplV2.java @@ -20,7 +20,7 @@ package org.matsim.contrib.freightreceiver; -import org.matsim.contrib.freight.carrier.TimeWindow; +import org.matsim.freight.carriers.TimeWindow; import org.matsim.core.utils.misc.Time; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesXmlWriterDelegate; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/UsecasesCarrierScoringFunctionFactory.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/UsecasesCarrierScoringFunctionFactory.java index 7ef7064e495..5cc872f2b50 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/UsecasesCarrierScoringFunctionFactory.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/UsecasesCarrierScoringFunctionFactory.java @@ -7,9 +7,9 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.controler.CarrierScoringFunctionFactory; -import org.matsim.contrib.freight.controler.FreightActivity; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.controler.CarrierScoringFunctionFactory; +import org.matsim.freight.carriers.controler.FreightActivity; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.scoring.ScoringFunction; import org.matsim.core.scoring.SumScoringFunction; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/Coalition.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/Coalition.java index e267baa3b3b..9afea8cdc9e 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/Coalition.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/Coalition.java @@ -1,6 +1,6 @@ package org.matsim.contrib.freightreceiver.collaboration; -import org.matsim.contrib.freight.carrier.Carrier; +import org.matsim.freight.carriers.Carrier; import org.matsim.contrib.freightreceiver.Receiver; import org.matsim.utils.objectattributes.attributable.Attributable; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/CollaborationUtils.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/CollaborationUtils.java index 1142c4ea589..25e73445613 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/CollaborationUtils.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/CollaborationUtils.java @@ -4,9 +4,9 @@ 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.Carriers; -import org.matsim.contrib.freight.controler.FreightUtils; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.Carriers; import org.matsim.contrib.freightreceiver.*; public class CollaborationUtils{ @@ -42,7 +42,7 @@ public static void createCoalitionWithCarriersAndAddCollaboratingReceivers(Scena /* Add carrier and receivers to coalition */ Coalition coalition = CollaborationUtils.createCoalition(); - for (Carrier carrier : FreightUtils.getCarriers(sc).getCarriers().values()){ + for (Carrier carrier : CarriersUtils.getCarriers(sc).getCarriers().values()){ if (!coalition.getCarrierCoalitionMembers().contains(carrier)){ coalition.addCarrierCoalitionMember(carrier); } diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/CollaborationUtilsNew.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/CollaborationUtilsNew.java index 12a273d7f61..c3c3d3d544e 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/CollaborationUtilsNew.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/CollaborationUtilsNew.java @@ -1,6 +1,6 @@ package org.matsim.contrib.freightreceiver.collaboration; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.Carriers; import org.matsim.contrib.freightreceiver.*; /** diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/MutableCoalition.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/MutableCoalition.java index 7e797b57341..4799f493912 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/MutableCoalition.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/MutableCoalition.java @@ -1,7 +1,7 @@ package org.matsim.contrib.freightreceiver.collaboration; -import org.matsim.contrib.freight.carrier.Carrier; +import org.matsim.freight.carriers.Carrier; import org.matsim.contrib.freightreceiver.Receiver; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesImpl; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/TimeWindowMutator.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/TimeWindowMutator.java index fa92790ba3f..bf972b057fe 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/TimeWindowMutator.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/collaboration/TimeWindowMutator.java @@ -21,7 +21,7 @@ */ package org.matsim.contrib.freightreceiver.collaboration; -import org.matsim.contrib.freight.carrier.TimeWindow; +import org.matsim.freight.carriers.TimeWindow; import org.matsim.contrib.freightreceiver.ReceiverPlan; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.replanning.ReplanningContext; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/OrderFrequencyStrategyManager.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/OrderFrequencyStrategyManager.java index 97af3b36976..f74750d9924 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/OrderFrequencyStrategyManager.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/OrderFrequencyStrategyManager.java @@ -41,7 +41,7 @@ public ReceiverStrategyManager get() { GenericPlanStrategyImpl strategy = new GenericPlanStrategyImpl<>( new ExpBetaPlanChanger.Factory().setBetaValue(10.0).build() ); strategy.addStrategyModule(new OrderSizeMutator(true)); strategyManager.addStrategy(strategy, null, 0.15); - strategyManager.addChangeRequest((int) (sc.getConfig().controler().getLastIteration()*0.9), strategy, null, 0.0); + strategyManager.addChangeRequest((int) (sc.getConfig().controller().getLastIteration()*0.9), strategy, null, 0.0); } /* @@ -52,7 +52,7 @@ public ReceiverStrategyManager get() { GenericPlanStrategyImpl strategy = new GenericPlanStrategyImpl<>( new ExpBetaPlanChanger.Factory().setBetaValue(10.0).build() ); strategy.addStrategyModule(new OrderSizeMutator(false)); strategyManager.addStrategy(strategy, null, 0.15); - strategyManager.addChangeRequest((int) (sc.getConfig().controler().getLastIteration()*0.9), strategy, null, 0.0); + strategyManager.addChangeRequest((int) (sc.getConfig().controller().getLastIteration()*0.9), strategy, null, 0.0); } /* Replanning for grand coalition receivers. TODO Removed for now. */ diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/ReceiverStrategyManager.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/ReceiverStrategyManager.java index db66d80f006..0ef128e441a 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/ReceiverStrategyManager.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/ReceiverStrategyManager.java @@ -20,7 +20,7 @@ package org.matsim.contrib.freightreceiver.replanning; -import org.matsim.contrib.freight.controler.CarrierStrategyManager; +import org.matsim.freight.carriers.controler.CarrierStrategyManager; import org.matsim.contrib.freightreceiver.Receiver; import org.matsim.contrib.freightreceiver.ReceiverPlan; import org.matsim.core.replanning.GenericStrategyManager; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/ServiceTimeStrategyManagerProvider.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/ServiceTimeStrategyManagerProvider.java index 8e2b3f4c8c7..6271e402b57 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/ServiceTimeStrategyManagerProvider.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/ServiceTimeStrategyManagerProvider.java @@ -39,7 +39,7 @@ public ReceiverStrategyManager get() { GenericPlanStrategyImpl increaseStrategy = new GenericPlanStrategyImpl<>(new ExpBetaPlanChanger.Factory().build()); increaseStrategy.addStrategyModule(new ServiceTimeMutator(Time.parseTime("0:15:00"), Time.parseTime("04:00:00"), true)); strategyManager.addStrategy(increaseStrategy, null, 0.15); - strategyManager.addChangeRequest((int) (sc.getConfig().controler().getLastIteration() * 0.9), increaseStrategy, null, 0.0); + strategyManager.addChangeRequest((int) (sc.getConfig().controller().getLastIteration() * 0.9), increaseStrategy, null, 0.0); } { @@ -48,7 +48,7 @@ public ReceiverStrategyManager get() { GenericPlanStrategyImpl decreaseStrategy = new GenericPlanStrategyImpl<>(new ExpBetaPlanChanger.Factory().build()); decreaseStrategy.addStrategyModule(new ServiceTimeMutator(Time.parseTime("00:15:00"), Time.parseTime("01:00:00"), false)); strategyManager.addStrategy(decreaseStrategy, null, 0.15); - strategyManager.addChangeRequest((int) (sc.getConfig().controler().getLastIteration() * 0.9), decreaseStrategy, null, 0.0); + strategyManager.addChangeRequest((int) (sc.getConfig().controller().getLastIteration() * 0.9), decreaseStrategy, null, 0.0); } /* Replanning for grand coalition receivers.*/ diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/TimeWindowStrategyManagerFactory.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/TimeWindowStrategyManagerFactory.java index c4d789e1ee2..e19d1437dc0 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/TimeWindowStrategyManagerFactory.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/TimeWindowStrategyManagerFactory.java @@ -42,7 +42,7 @@ public ReceiverStrategyManager get() { GenericPlanStrategyImpl strategy = new GenericPlanStrategyImpl<>(new ExpBetaPlanChanger.Factory().setBetaValue(10.).build()); strategy.addStrategyModule(new TimeWindowUpperBoundMutator(Time.parseTime("01:00:00"))); strategyManager.addStrategy(strategy, null, 0.3); - strategyManager.addChangeRequest((int) (sc.getConfig().controler().getLastIteration() * 0.9), strategy, null, 0.0); + strategyManager.addChangeRequest((int) (sc.getConfig().controller().getLastIteration() * 0.9), strategy, null, 0.0); } /* Replanning for grand coalition receivers. TODO Ignored for now */ diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/TimeWindowUpperBoundMutator.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/TimeWindowUpperBoundMutator.java index 681a00c0524..97ea20b2e20 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/TimeWindowUpperBoundMutator.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/replanning/TimeWindowUpperBoundMutator.java @@ -18,7 +18,7 @@ package org.matsim.contrib.freightreceiver.replanning; -import org.matsim.contrib.freight.carrier.TimeWindow; +import org.matsim.freight.carriers.TimeWindow; import org.matsim.contrib.freightreceiver.ReceiverPlan; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.replanning.ReplanningContext; diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/ReceiverChessboardScenario.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/ReceiverChessboardScenario.java index 8e1884f1337..b5b2f535b45 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/ReceiverChessboardScenario.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/ReceiverChessboardScenario.java @@ -27,9 +27,8 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.NetworkWriter; -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.contrib.freightreceiver.*; import org.matsim.contrib.freightreceiver.collaboration.CollaborationUtils; import org.matsim.core.config.Config; @@ -86,7 +85,7 @@ public static Scenario createChessboardScenario(long seed, int numberOfReceivers } /* Link the carriers to the receivers. */ - CollaborationUtils.linkReceiverOrdersToCarriers(ReceiverUtils.getReceivers(sc), FreightUtils.getCarriers(sc)); + CollaborationUtils.linkReceiverOrdersToCarriers(ReceiverUtils.getReceivers(sc), CarriersUtils.getCarriers(sc)); CollaborationUtils.createCoalitionWithCarriersAndAddCollaboratingReceivers(sc); return sc; } @@ -102,15 +101,15 @@ private static Config setupChessboardConfig(long seed, String outputFolder) { config.setContext(context); - config.controler().setOutputDirectory(outputFolder); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(ReceiverChessboardParameters.NUM_ITERATIONS); - config.controler().setMobsim("qsim"); - config.controler().setWriteSnapshotsInterval(ReceiverChessboardParameters.STAT_INTERVAL); + config.controller().setOutputDirectory(outputFolder); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(ReceiverChessboardParameters.NUM_ITERATIONS); + config.controller().setMobsim("qsim"); + config.controller().setWriteSnapshotsInterval(ReceiverChessboardParameters.STAT_INTERVAL); config.global().setRandomSeed(seed); config.network().setInputFile("grid9x9.xml"); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); return config; } @@ -120,7 +119,7 @@ private static Config setupChessboardConfig(long seed, String outputFolder) { */ public static void writeFreightScenario(Scenario sc) { /* Write the necessary bits to file. */ - String outputFolder = sc.getConfig().controler().getOutputDirectory(); + String outputFolder = sc.getConfig().controller().getOutputDirectory(); boolean success = new File(outputFolder).mkdirs(); if (!success) { LOG.warn("Could not successfully create '" + outputFolder + "'. Maybe it already exists?"); @@ -128,13 +127,13 @@ public static void writeFreightScenario(Scenario sc) { new NetworkWriter(sc.getNetwork()).write(outputFolder + "network.xml"); new ConfigWriter(sc.getConfig()).write(outputFolder + "config.xml"); - FreightUtils.writeCarriers(FreightUtils.getCarriers(sc),outputFolder + "carriers.xml"); + CarriersUtils.writeCarriers(CarriersUtils.getCarriers(sc),outputFolder + "carriers.xml"); new ReceiversWriter(ReceiverUtils.getReceivers(sc)).write(outputFolder + "receivers.xml"); /* Write the vehicle types. FIXME This will have to change so that vehicle * types lie at the Carriers level, and not per Carrier. In this scenario * there luckily is only a single Carrier. */ - new CarrierVehicleTypeWriter(CarrierVehicleTypes.getVehicleTypes(FreightUtils.getCarriers(sc))).write(outputFolder + "carrierVehicleTypes.xml"); + new CarrierVehicleTypeWriter(CarrierVehicleTypes.getVehicleTypes(CarriersUtils.getCarriers(sc))).write(outputFolder + "carrierVehicleTypes.xml"); } @@ -143,7 +142,7 @@ public static void writeFreightScenario(Scenario sc) { * for experiments, but this must be adapted in the future to accept other parameters as inputs to enable different orders per receiver. */ private static void createReceiverOrders(Scenario sc) { - Carriers carriers = FreightUtils.getCarriers(sc); + Carriers carriers = CarriersUtils.getCarriers(sc); Receivers receivers = ReceiverUtils.getReceivers(sc); Carrier carrierOne = carriers.getCarriers().get(Id.create("Carrier1", Carrier.class)); @@ -265,7 +264,7 @@ static void createAndAddChessboardReceivers(Scenario sc, int numberOfReceivers) */ private static void createChessboardCarriersAndAddToScenario(Scenario sc) { Id carrierId = Id.create("Carrier1", Carrier.class); - Carrier carrier = CarrierUtils.createCarrier(carrierId); + Carrier carrier = CarriersUtils.createCarrier(carrierId); Id carrierLocation = selectRandomLink(sc.getNetwork()); CarrierCapabilities.Builder capBuilder = CarrierCapabilities.Builder.newInstance(); @@ -317,7 +316,7 @@ private static void createChessboardCarriersAndAddToScenario(Scenario sc) { types.getVehicleTypes().put(typeLight.getId(), typeLight); types.getVehicleTypes().put(typeHeavy.getId(), typeHeavy); - Carriers carriers = FreightUtils.addOrGetCarriers(sc); + Carriers carriers = CarriersUtils.addOrGetCarriers(sc); carriers.addCarrier(carrier); } diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/RunReceiverChessboardWithEqualProportionCost.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/RunReceiverChessboardWithEqualProportionCost.java index ae0efa51070..469f45574ee 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/RunReceiverChessboardWithEqualProportionCost.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/RunReceiverChessboardWithEqualProportionCost.java @@ -23,9 +23,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.controler.FreightUtils; -import org.matsim.contrib.freight.usecases.analysis.CarrierScoreStats; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.usecases.analysis.CarrierScoreStats; import org.matsim.contrib.freightreceiver.ReceiverModule; import org.matsim.contrib.freightreceiver.ReceiverReplanningType; import org.matsim.contrib.freightreceiver.ReceiverUtils; @@ -65,7 +65,7 @@ static void run(int run) { true); Controler controler = new Controler(scenario); - controler.getConfig().controler().setLastIteration(50); + controler.getConfig().controller().setLastIteration(50); /* Set up the receiver module. */ ReceiverModule receiverModule = new ReceiverModule(ReceiverUtils.createEqualProportionCostAllocation()); @@ -83,7 +83,7 @@ static void run(int run) { * TODO This is less elegant than the embedded score stats for the receiver. */ static void prepareFreightOutputDataAndStats(MatsimServices controler) { - CarrierScoreStats scoreStats = new CarrierScoreStats(FreightUtils.getCarriers(controler.getScenario()), controler.getScenario().getConfig().controler().getOutputDirectory() + "/carrier_scores", true); + CarrierScoreStats scoreStats = new CarrierScoreStats(CarriersUtils.getCarriers(controler.getScenario()), controler.getScenario().getConfig().controller().getOutputDirectory() + "/carrier_scores", true); controler.addControlerListener(scoreStats); } diff --git a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/RunReceiverChessboardWithFixedCarrierCost.java b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/RunReceiverChessboardWithFixedCarrierCost.java index 15d840b5d66..112785c45b8 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/RunReceiverChessboardWithFixedCarrierCost.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/contrib/freightreceiver/run/chessboard/RunReceiverChessboardWithFixedCarrierCost.java @@ -23,9 +23,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.controler.FreightUtils; -import org.matsim.contrib.freight.usecases.analysis.CarrierScoreStats; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.usecases.analysis.CarrierScoreStats; import org.matsim.contrib.freightreceiver.ReceiverModule; import org.matsim.contrib.freightreceiver.ReceiverReplanningType; import org.matsim.contrib.freightreceiver.ReceiverUtils; @@ -65,7 +65,7 @@ static void run(int run) { true); Controler controler = new Controler(scenario); - controler.getConfig().controler().setLastIteration(50); + controler.getConfig().controller().setLastIteration(50); /* Set up the receiver module. */ ReceiverModule receiverModule = new ReceiverModule(ReceiverUtils.createFixedReceiverCostAllocation(100.0)); @@ -85,7 +85,7 @@ static void run(int run) { * TODO This is less elegant than the embedded score stats for the receiver. */ static void prepareFreightOutputDataAndStats(MatsimServices controler) { - CarrierScoreStats scoreStats = new CarrierScoreStats(FreightUtils.getCarriers(controler.getScenario()), controler.getScenario().getConfig().controler().getOutputDirectory() + "/carrier_scores", true); + CarrierScoreStats scoreStats = new CarrierScoreStats(CarriersUtils.getCarriers(controler.getScenario()), controler.getScenario().getConfig().controller().getOutputDirectory() + "/carrier_scores", true); controler.addControlerListener(scoreStats); } diff --git a/contribs/freightreceiver/src/test/java/org/matsim/contrib/freightreceiver/ReceiversReaderTest.java b/contribs/freightreceiver/src/test/java/org/matsim/contrib/freightreceiver/ReceiversReaderTest.java index 77e2ab92753..f5ba3475e0b 100644 --- a/contribs/freightreceiver/src/test/java/org/matsim/contrib/freightreceiver/ReceiversReaderTest.java +++ b/contribs/freightreceiver/src/test/java/org/matsim/contrib/freightreceiver/ReceiversReaderTest.java @@ -24,8 +24,8 @@ import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Id; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.TimeWindow; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.TimeWindow; import org.matsim.contrib.freightreceiver.collaboration.CollaborationUtils; import org.matsim.core.utils.misc.Time; import org.matsim.testcases.MatsimTestUtils; diff --git a/contribs/hybridsim/pom.xml b/contribs/hybridsim/pom.xml index 55a9bcd52b2..2a8fffb488b 100644 --- a/contribs/hybridsim/pom.xml +++ b/contribs/hybridsim/pom.xml @@ -10,8 +10,8 @@ hybridsim - 3.24.2 - 1.57.2 + 3.24.4 + 1.58.0 @@ -37,16 +37,20 @@ - - - + + kr.motd.maven os-maven-plugin 1.7.1 - - - - + + + initialize + + detect + + + + org.xolstice.maven.plugins protobuf-maven-plugin diff --git a/contribs/hybridsim/src/main/java/org/matsim/contrib/hybridsim/run/RunExample.java b/contribs/hybridsim/src/main/java/org/matsim/contrib/hybridsim/run/RunExample.java index ebab0cd810f..7521cd4df26 100644 --- a/contribs/hybridsim/src/main/java/org/matsim/contrib/hybridsim/run/RunExample.java +++ b/contribs/hybridsim/src/main/java/org/matsim/contrib/hybridsim/run/RunExample.java @@ -23,7 +23,6 @@ import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; @@ -44,7 +43,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -81,8 +80,8 @@ public static void main(String[] args) throws IOException, InterruptedException } Config c = ConfigUtils.createConfig(); - c.controler().setLastIteration(0); - c.controler().setWriteEventsInterval(1); + c.controller().setLastIteration(0); + c.controller().setWriteEventsInterval(1); c.qsim().setEndTime(3600); @@ -94,7 +93,7 @@ public static void main(String[] args) throws IOException, InterruptedException createHybridsimScenario(sc); //enable for grpc_jps_as_a_service branch final Controler controller = new Controler(sc); - controller.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controller.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); final EventsManager eventsManager = EventsUtils.createEventsManager(); @@ -328,7 +327,7 @@ private static void createHybridsimScenario(Scenario sc) { } private static void enrichConfig(Config c) { - PlanCalcScoreConfigGroup.ActivityParams pre = new PlanCalcScoreConfigGroup.ActivityParams("origin"); + ScoringConfigGroup.ActivityParams pre = new ScoringConfigGroup.ActivityParams("origin"); pre.setTypicalDuration(49); // needs to be geq 49, otherwise when // running a simulation one gets // "java.lang.RuntimeException: zeroUtilityDuration of type pre-evac must be greater than 0.0. Did you forget to specify the typicalDuration?" @@ -340,18 +339,18 @@ private static void enrichConfig(Config c) { pre.setLatestStartTime(49); pre.setOpeningTime(49); - PlanCalcScoreConfigGroup.ActivityParams post = new PlanCalcScoreConfigGroup.ActivityParams("destination"); + ScoringConfigGroup.ActivityParams post = new ScoringConfigGroup.ActivityParams("destination"); post.setTypicalDuration(49); // dito post.setMinimalDuration(49); post.setClosingTime(49); post.setEarliestEndTime(49); post.setLatestStartTime(49); post.setOpeningTime(49); - c.planCalcScore().addActivityParams(pre); - c.planCalcScore().addActivityParams(post); + c.scoring().addActivityParams(pre); + c.scoring().addActivityParams(post); - c.planCalcScore().setLateArrival_utils_hr(0.); - c.planCalcScore().setPerforming_utils_hr(0.); + c.scoring().setLateArrival_utils_hr(0.); + c.scoring().setPerforming_utils_hr(0.); } private static void createPopulation(Scenario sc) { diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceModule.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceModule.java index d151624afe2..a6229390386 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceModule.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceModule.java @@ -167,7 +167,7 @@ public > Builder withFixedCosts(Class> Builder withLegEstimator(Class> estimator, Class> option, + public > Builder withLegEstimator(Class> estimator, Class> option, String... modes) { for (String mode : modes) { diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/ModeChoiceWeightScheduler.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/ModeChoiceWeightScheduler.java index c817bb6d849..5d0eed4bb41 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/ModeChoiceWeightScheduler.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/ModeChoiceWeightScheduler.java @@ -40,8 +40,8 @@ public void notifyStartup(StartupEvent event) { anneal = imc.getAnneal(); // The first iteration does not do any replanning - n = config.controler().getLastIteration() - 1; - double disableInnovation = config.strategy().getFractionOfIterationsToDisableInnovation(); + n = config.controller().getLastIteration() - 1; + double disableInnovation = config.replanning().getFractionOfIterationsToDisableInnovation(); if (disableInnovation > 0 && disableInnovation < 1) n *= disableInnovation; diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/PlanModelService.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/PlanModelService.java index 4930197c262..93c2ca21a0f 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/PlanModelService.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/PlanModelService.java @@ -157,6 +157,7 @@ public List allowedModes(PlanModel planModel) { /** * Calculate the estimates for all options. Note that plan model has to be routed before computing estimates. */ + @SuppressWarnings("rawtypes") public void calculateEstimates(EstimatorContext context, PlanModel planModel) { for (Map.Entry> e : planModel.getEstimates().entrySet()) { @@ -208,7 +209,7 @@ public void calculateEstimates(EstimatorContext context, PlanModel planModel) { if (tripEst != null && legMode.equals(c.getMode())) continue; - LegEstimator> legEst = (LegEstimator>) legEstimators.get(legMode); + LegEstimator legEst = legEstimators.get(legMode); if (legEst == null) throw new IllegalStateException("No leg estimator defined for mode: " + legMode); diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/AnalyzeCarChoice.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/AnalyzeCarChoice.java index fb97767357a..4c04f72487c 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/AnalyzeCarChoice.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/AnalyzeCarChoice.java @@ -63,8 +63,8 @@ public Integer call() throws Exception { Config config = scenario.getConfig(); - config.controler().setLastIteration(0); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setLastIteration(0); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); InformedModeChoiceConfigGroup imc = ConfigUtils.addOrGetModule(config, InformedModeChoiceConfigGroup.class); diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/GenerateChoiceSet.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/GenerateChoiceSet.java index 6be247ec47b..14d08f8902c 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/GenerateChoiceSet.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/GenerateChoiceSet.java @@ -74,8 +74,8 @@ public Integer call() throws Exception { Config config = scenario.getConfig(); - config.controler().setLastIteration(0); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setLastIteration(0); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); InformedModeChoiceConfigGroup imc = ConfigUtils.addOrGetModule(config, InformedModeChoiceConfigGroup.class); diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/StrategyOptions.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/StrategyOptions.java index 12655fd73f8..532c0995236 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/StrategyOptions.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/StrategyOptions.java @@ -9,7 +9,7 @@ import org.matsim.api.core.v01.population.Plan; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.replanning.choosers.ForceInnovationStrategyChooser; import org.matsim.core.replanning.choosers.StrategyChooser; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule; @@ -104,7 +104,7 @@ public void applyConfig(Config config, TriConsumer log) // Depends on number of pre generated plans if (getModeChoice() == ModeChoice.none) - config.strategy().setMaxAgentPlanMemorySize(Math.max(config.strategy().getMaxAgentPlanMemorySize(), group.k) + 5); + config.replanning().setMaxAgentPlanMemorySize(Math.max(config.replanning().getMaxAgentPlanMemorySize(), group.k) + 5); } @@ -128,13 +128,13 @@ public Module applyModule(Binder binder, Config config, Consumer strategies = config.strategy().getStrategySettings().stream() + List strategies = config.replanning().getStrategySettings().stream() .filter(s -> !filtered.contains(s.getStrategyName()) || !Objects.equals(s.getSubpopulation(), defaultSubpopulation)) .collect(Collectors.toList()); //add time mutation - strategies.add(new StrategyConfigGroup.StrategySettings() + strategies.add(new ReplanningConfigGroup.StrategySettings() .setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.TimeAllocationMutator) .setSubpopulation(defaultSubpopulation) .setWeight(group.timeMutation) @@ -142,7 +142,7 @@ public Module applyModule(Binder binder, Config config, Consumer config.strategy().addStrategySettings(s)); + config.replanning().clearStrategySettings(); + strategies.forEach(s -> config.replanning().addStrategySettings(s)); if (group.forceInnovation > 0) binder.bind(new TypeLiteral>() { diff --git a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/ModeChoiceWeightSchedulerTest.java b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/ModeChoiceWeightSchedulerTest.java index 103712a5eaa..b7a4d6cd386 100644 --- a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/ModeChoiceWeightSchedulerTest.java +++ b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/ModeChoiceWeightSchedulerTest.java @@ -14,7 +14,7 @@ public class ModeChoiceWeightSchedulerTest extends ScenarioTest { @Test public void linear() { - controler.getConfig().controler().setLastIteration(100); + controler.getConfig().controller().setLastIteration(100); InformedModeChoiceConfigGroup imc = ConfigUtils.addOrGetModule(controler.getConfig(), InformedModeChoiceConfigGroup.class); imc.setInvBeta(1); @@ -40,7 +40,7 @@ public void linear() { @Test public void quadratic() { - controler.getConfig().controler().setLastIteration(101); + controler.getConfig().controller().setLastIteration(101); InformedModeChoiceConfigGroup imc = ConfigUtils.addOrGetModule(controler.getConfig(), InformedModeChoiceConfigGroup.class); imc.setInvBeta(1); @@ -60,4 +60,4 @@ public void quadratic() { assertThat(scheduler.getInvBeta()).isEqualTo(0.25); } -} \ No newline at end of file +} diff --git a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/TestScenario.java b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/TestScenario.java index aecf81f24c3..98798263fad 100644 --- a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/TestScenario.java +++ b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/TestScenario.java @@ -10,7 +10,7 @@ import org.matsim.application.MATSimApplication; 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; @@ -65,8 +65,8 @@ public static Config loadConfig(MatsimTestUtils utils) { URL context = ExamplesUtils.getTestScenarioURL("kelheim"); Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(context, "config.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; } @@ -78,28 +78,28 @@ protected Config prepareConfig(Config config) { for (String act : List.of("home", "restaurant", "other", "visit", "errands", "accomp_other", "accomp_children", "educ_higher", "educ_secondary", "educ_primary", "educ_tertiary", "educ_kiga", "educ_other")) { - config.planCalcScore() - .addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams(act + "_" + ii).setTypicalDuration(ii)); + config.scoring() + .addActivityParams(new ScoringConfigGroup.ActivityParams(act + "_" + ii).setTypicalDuration(ii)); } - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("work_" + ii).setTypicalDuration(ii) + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("work_" + ii).setTypicalDuration(ii) .setOpeningTime(6. * 3600.).setClosingTime(20. * 3600.)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("business_" + ii).setTypicalDuration(ii) + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("business_" + ii).setTypicalDuration(ii) .setOpeningTime(6. * 3600.).setClosingTime(20. * 3600.)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("leisure_" + ii).setTypicalDuration(ii) + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("leisure_" + ii).setTypicalDuration(ii) .setOpeningTime(9. * 3600.).setClosingTime(27. * 3600.)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("shop_daily_" + ii).setTypicalDuration(ii) + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("shop_daily_" + ii).setTypicalDuration(ii) .setOpeningTime(8. * 3600.).setClosingTime(20. * 3600.)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("shop_other_" + ii).setTypicalDuration(ii) + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("shop_other_" + ii).setTypicalDuration(ii) .setOpeningTime(8. * 3600.).setClosingTime(20. * 3600.)); } - 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("car", "ride", "bike", "walk", "pt")); diff --git a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/estimators/ComplexEstimatorTest.java b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/estimators/ComplexEstimatorTest.java index 3ce186a0124..5d3dd6a7a36 100644 --- a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/estimators/ComplexEstimatorTest.java +++ b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/estimators/ComplexEstimatorTest.java @@ -21,7 +21,7 @@ public void bindings() { Config config = TestScenario.loadConfig(utils); - config.controler().setLastIteration(2); + config.controller().setLastIteration(2); Controler controler = MATSimApplication.prepare(TestScenario.class, config, "--complex"); controler.run(); diff --git a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/replanning/SelectSingleTripModeStrategyTest.java b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/replanning/SelectSingleTripModeStrategyTest.java index ada9595df9d..7ae3ffca08f 100644 --- a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/replanning/SelectSingleTripModeStrategyTest.java +++ b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/replanning/SelectSingleTripModeStrategyTest.java @@ -7,7 +7,7 @@ import org.matsim.application.MATSimApplication; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -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.PlanStrategy; @@ -24,9 +24,9 @@ public void selectSingleTrip() { Config config = TestScenario.loadConfig(utils); - config.controler().setLastIteration(10); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - config.strategy().addStrategySettings(new StrategyConfigGroup.StrategySettings() + config.controller().setLastIteration(10); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.replanning().addStrategySettings(new ReplanningConfigGroup.StrategySettings() .setStrategyName(InformedModeChoiceModule.SELECT_SINGLE_TRIP_MODE_STRATEGY) .setSubpopulation("person") .setWeight(0.5) diff --git a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/search/TopKMinMaxTest.java b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/search/TopKMinMaxTest.java index 55aa1d8e8e7..e57a6413116 100644 --- a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/search/TopKMinMaxTest.java +++ b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/search/TopKMinMaxTest.java @@ -236,7 +236,7 @@ else if (invocationOnMock.getArgument(0).equals(TransportMode.walk)) { tripBinder.addBinding(TransportMode.car).toInstance(new CarTripEstimator()); - ScoringParameters.Builder scoring = new ScoringParameters.Builder(config.planCalcScore(), config.planCalcScore().getScoringParameters("person"), Map.of(), config.scenario()); + ScoringParameters.Builder scoring = new ScoringParameters.Builder(config.scoring(), config.scoring().getScoringParameters("person"), Map.of(), config.scenario()); bind(ScoringParametersForPerson.class).toInstance(person -> scoring.build()); bind(InformedModeChoiceConfigGroup.class).toInstance(ConfigUtils.addOrGetModule(config, InformedModeChoiceConfigGroup.class)); diff --git a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyLocationChoicePlanAlgorithm.java b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyLocationChoicePlanAlgorithm.java index 2a242659ae1..7d0fa5398b2 100644 --- a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyLocationChoicePlanAlgorithm.java +++ b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyLocationChoicePlanAlgorithm.java @@ -55,7 +55,7 @@ final class BestReplyLocationChoicePlanAlgorithm implements PlanAlgorithm { private static final Logger log = LogManager.getLogger( BestReplyLocationChoicePlanAlgorithm.class ) ; - + private final ActivityFacilities facilities; private final ObjectAttributes personsMaxDCScoreUnscaled; private final ScaleEpsilon scaleEpsilon; @@ -168,15 +168,15 @@ private ChoiceSet createChoiceSetFromCircle(Plan plan, int personIndex, final QuadTree quadTree = this.quadTreesOfType.get( convertedType ); Gbl.assertNotNull( quadTree ); Collection list = quadTree.getDisk(center.getX(), center.getY(), maxRadius ); - + for (ActivityFacilityWithIndex facility : list) { // int facilityIndex = this.lcContext.getFacilityIndex(facility.getId()); int facilityIndex = facility.getArrayIndex(); - if (this.sampler.sample(facilityIndex, personIndex)) { - + if (this.sampler.sample(facilityIndex, personIndex)) { + // only add destination if it can be reached with the chosen mode String mode = PopulationUtils.getPreviousLeg( plan, actToMove ).getMode(); - + Id linkId = null; // try to get linkId from facility, else get it from act. other options not allowed! if (facility.getLinkId() != null) { @@ -186,16 +186,16 @@ private ChoiceSet createChoiceSetFromCircle(Plan plan, int personIndex, linkId = actToMove.getLinkId(); } // TODO: solve this generic. for that we need info from the config, which modes are actually teleported. - if (this.lcContext.getScenario().getNetwork().getLinks().get(linkId).getAllowedModes().contains(mode) || - mode.equals(TransportMode.bike) || + if (this.lcContext.getScenario().getNetwork().getLinks().get(linkId).getAllowedModes().contains(mode) || + mode.equals(TransportMode.bike) || mode.equals(TransportMode.walk) || mode.equals(TransportMode.transit_walk) || mode.equals(TransportMode.other)) { cs.addDestination(facility.getId()); - } + } } } - + return cs; } @@ -223,14 +223,14 @@ private double convertEpsilonIntoDistance(Person person, String type) { // maxDCScore *= scale; // apply the scale factors given in the config file - /* + /* * here one could do a much more sophisticated calculation including time use and travel speed estimations (from previous iteration) */ double travelSpeedCrowFly = this.dccg.getTravelSpeed_car(); - double betaTime = this.scenario.getConfig().planCalcScore().getModes().get(TransportMode.car ).getMarginalUtilityOfTraveling(); + double betaTime = this.scenario.getConfig().scoring().getModes().get(TransportMode.car ).getMarginalUtilityOfTraveling(); // if ( Boolean.getBoolean(this.scenario.getConfig().vspExperimental().getValue(VspExperimentalConfigKey.isUsingOpportunityCostOfTimeForLocationChoice)) ) { if ( this.scenario.getConfig().vspExperimental().isUsingOpportunityCostOfTimeForLocationChoice() ) { - betaTime -= this.scenario.getConfig().planCalcScore().getPerforming_utils_hr() ; + betaTime -= this.scenario.getConfig().scoring().getPerforming_utils_hr() ; // needs to be negative (I think) since AH uses this as a cost parameter. kai, jan'13 } double maxTravelTime = Double.MAX_VALUE; @@ -243,7 +243,7 @@ private double convertEpsilonIntoDistance(Person person, String type) { // correct way. kai, jan'13 } // distance linear - double maxDistance = travelSpeedCrowFly * maxTravelTime; + double maxDistance = travelSpeedCrowFly * maxTravelTime; // define a maximum distance choice set manually // yyyy it is quite stupid to do the following at the end of this method and not at the beginning. Can probably be moved up, but would need to be tested. kai, jul'23 diff --git a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyLocationChoicePlanStrategy.java b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyLocationChoicePlanStrategy.java index 134d10ac14a..048c3a03f3e 100644 --- a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyLocationChoicePlanStrategy.java +++ b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyLocationChoicePlanStrategy.java @@ -29,7 +29,6 @@ import org.matsim.core.replanning.PlanStrategyImpl; import org.matsim.core.replanning.ReplanningContext; import org.matsim.core.replanning.modules.ReRoute; -import org.matsim.core.replanning.modules.TripsToLegsModule; import org.matsim.core.replanning.selectors.BestPlanSelector; import org.matsim.core.replanning.selectors.ExpBetaPlanChanger; import org.matsim.core.replanning.selectors.ExpBetaPlanSelector; @@ -82,13 +81,13 @@ public void init(ReplanningContext replanningContext) { delegate = new PlanStrategyImpl( new BestPlanSelector<>() ); break; case "ChangeExpBeta": - delegate = new PlanStrategyImpl( new ExpBetaPlanChanger( config.planCalcScore().getBrainExpBeta() ) ); + delegate = new PlanStrategyImpl( new ExpBetaPlanChanger( config.scoring().getBrainExpBeta() ) ); break; case "SelectRandom": delegate = new PlanStrategyImpl( new RandomPlanSelector() ); break; default: - delegate = new PlanStrategyImpl( new ExpBetaPlanSelector( config.planCalcScore() ) ); + delegate = new PlanStrategyImpl( new ExpBetaPlanSelector( config.scoring() ) ); break; } delegate.addStrategyModule(new BestReplyLocationChoiceStrategymodule(tripRouterProvider, lcContext, maxDcScoreWrapper.getPersonsMaxDCScoreUnscaled(), scoringFunctionFactory, travelTimes, travelDisutilities, timeInterpretation) ); diff --git a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/DCScoringFunctionFactory.java b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/DCScoringFunctionFactory.java index da142e4aecb..902ac71178a 100644 --- a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/DCScoringFunctionFactory.java +++ b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/DCScoringFunctionFactory.java @@ -33,12 +33,12 @@ import org.matsim.core.scoring.functions.ScoringParameters; class DCScoringFunctionFactory implements ScoringFunctionFactory { - + private final static Logger log = LogManager.getLogger(DCScoringFunctionFactory.class); - + private final Scenario scenario; private final DestinationChoiceContext lcContext; - + private boolean usingConfigParamsForScoring = true; private boolean usingIndividualScoringParameters = true; private ScoringParameters nonPersonalizedScoringParameters = null; @@ -47,7 +47,7 @@ public DCScoringFunctionFactory(Scenario scenario, DestinationChoiceContext lcCo this.scenario = scenario; this.lcContext = lcContext; log.info("creating DCScoringFunctionFactory"); - + // configure ScoringFunction according to config FrozenTastesConfigGroup dccg = (FrozenTastesConfigGroup) scenario.getConfig().getModule( FrozenTastesConfigGroup.GROUP_NAME ); if (dccg != null) { @@ -55,7 +55,7 @@ public DCScoringFunctionFactory(Scenario scenario, DestinationChoiceContext lcCo this.setUsingIndividualScoringParameters(dccg.getUseIndividualScoringParameters()); } else log.warn("No DestinationChoiceConfigGroup was found in the config - cannot configure DCScoringFunctionFactory according to it!"); } - + public void setUsingConfigParamsForScoring(boolean val) { this.usingConfigParamsForScoring = val; } @@ -65,15 +65,15 @@ public void setUsingIndividualScoringParameters(boolean val) { if (!this.usingIndividualScoringParameters) { Config config = this.scenario.getConfig(); String subPopulationAttributeName = null; - this.nonPersonalizedScoringParameters = new ScoringParameters.Builder(config.planCalcScore(), config.planCalcScore().getScoringParameters(subPopulationAttributeName), config.scenario()).build(); + this.nonPersonalizedScoringParameters = new ScoringParameters.Builder(config.scoring(), config.scoring().getScoringParameters(subPopulationAttributeName), config.scenario()).build(); } } - + @Override public ScoringFunction createNewScoringFunction(Person person) { - + SumScoringFunction scoringFunctionAccumulator = new SumScoringFunction(); - + SumScoringFunction.BasicScoring scoringFunction; if (this.usingConfigParamsForScoring) { scoringFunction = new DCActivityWOFacilitiesScoringFunction(person, this.lcContext); @@ -83,7 +83,7 @@ public ScoringFunction createNewScoringFunction(Person person) { scoringFunction = new DCActivityScoringFunction(person.getSelectedPlan(), this.lcContext); } scoringFunctionAccumulator.addScoringFunction(scoringFunction); - + if (this.usingIndividualScoringParameters) { ScoringParameters scoringParameters = new ScoringParameters.Builder(this.scenario, person ).build(); scoringFunctionAccumulator.addScoringFunction(new CharyparNagelLegScoring(scoringParameters, this.scenario.getNetwork(), this.scenario.getConfig().transit().getTransitModes())); @@ -92,7 +92,7 @@ public ScoringFunction createNewScoringFunction(Person person) { scoringFunctionAccumulator.addScoringFunction(new CharyparNagelLegScoring(this.nonPersonalizedScoringParameters, this.scenario.getNetwork(), this.scenario.getConfig().transit().getTransitModes())); scoringFunctionAccumulator.addScoringFunction(new CharyparNagelAgentStuckScoring(this.nonPersonalizedScoringParameters)); } - + return scoringFunctionAccumulator; } } diff --git a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/DestinationChoiceContext.java b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/DestinationChoiceContext.java index b708ddfa416..2016faa9147 100644 --- a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/DestinationChoiceContext.java +++ b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/DestinationChoiceContext.java @@ -19,6 +19,7 @@ package org.matsim.contrib.locationchoice.frozenepsilons; +import java.io.UncheckedIOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -37,13 +38,12 @@ import org.matsim.core.api.internal.MatsimFactory; import org.matsim.core.api.internal.MatsimToplevelContainer; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.router.priorityqueue.HasIndex; import org.matsim.core.scoring.functions.ScoringParameters; import org.matsim.core.utils.collections.CollectionUtils; import org.matsim.core.utils.collections.QuadTree; import org.matsim.core.utils.collections.Tuple; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.facilities.ActivityFacility; import org.matsim.facilities.ActivityFacilityImpl; import org.matsim.facilities.ActivityOption; @@ -62,11 +62,11 @@ * */ class DestinationChoiceContext implements MatsimToplevelContainer { - + private static final Logger log = LogManager.getLogger(DestinationChoiceContext.class); - + public static final String ELEMENT_NAME = "DestinationChoiceBestResponseContext"; - + private final Scenario scenario; private ScaleEpsilon scaleEpsilon; // private ActTypeConverter actTypeConverter; @@ -87,9 +87,9 @@ class DestinationChoiceContext implements MatsimToplevelContainer { private Map> quadTreesOfType = new HashMap>(); private TreeMap facilitiesOfType = new TreeMap(); - + public DestinationChoiceContext(Scenario scenario) { - this.scenario = scenario; + this.scenario = scenario; log.info("dc context created but not yet initialized"); this.init(); // actually wanted to leave this away to be able to create but not yet fill the context. @@ -108,10 +108,10 @@ public DestinationChoiceContext(Scenario scenario) { } - + public void init() { if ( params==null ){ - this.params = new ScoringParameters.Builder( scenario.getConfig().planCalcScore(), scenario.getConfig().planCalcScore().getScoringParameters( null ), + this.params = new ScoringParameters.Builder( scenario.getConfig().scoring(), scenario.getConfig().scoring().getScoringParameters( null ), scenario.getConfig().scenario() ).build(); this.dccg = ConfigUtils.addOrGetModule( this.scenario.getConfig(), FrozenTastesConfigGroup.class ); ActivitiesHandler defineFlexibleActivities = new ActivitiesHandler( this.dccg ); @@ -126,7 +126,7 @@ public void init() { log.info( "dc context initialized" ); } } - + private void readOrCreateKVals(long seed) { ReadOrCreateKVals computer = new ReadOrCreateKVals(seed, this.scenario); this.arekValsRead = computer.run(); @@ -138,27 +138,27 @@ private void readOrCreateKVals(long seed) { this.personIndices.put(personId, personIndex); this.personsKValuesArray[personIndex] = (Double) scenario.getPopulation().getPersons().get(personId).getAttributes().getAttribute("k"); personIndex++; - } - + } + this.facilityIndices = new TObjectIntHashMap<>(); this.faciliesWithIndexMap = new HashMap<>(); this.facilitiesKValuesArray = new double[this.scenario.getActivityFacilities().getFacilities().size()]; int facilityIndex = 0; for (ActivityFacility facility : this.scenario.getActivityFacilities().getFacilities().values()) { Id facilityId = facility.getId(); - + this.facilityIndices.put(facilityId, facilityIndex); this.facilitiesKValuesArray[facilityIndex] = (Double) facility.getAttributes().getAttribute("k"); this.faciliesWithIndexMap.put(facilityId, new ActivityFacilityWithIndex(facility, facilityIndex)); - + facilityIndex++; } } - + private void readFacilitesAttributesAndBetas() { String pBetasFileName = this.dccg.getpBetasFile(); String fAttributesFileName = this.dccg.getfAttributesFile(); - if (pBetasFileName != null && fAttributesFileName!= null) { + if (pBetasFileName != null && fAttributesFileName!= null) { ObjectAttributesXmlReader personsBetasReader = new ObjectAttributesXmlReader(this.personsBetas); ObjectAttributesXmlReader facilitiesAttributesReader = new ObjectAttributesXmlReader(this.facilitiesAttributes); try { @@ -171,10 +171,10 @@ private void readFacilitesAttributesAndBetas() { } } } - + private void readPrefs() { String prefsFileName = this.dccg.getPrefsFile(); - if (prefsFileName != null) { + if (prefsFileName != null) { ObjectAttributesXmlReader prefsReader = new ObjectAttributesXmlReader(this.prefsAttributes); try { prefsReader.readFile(prefsFileName); @@ -185,7 +185,7 @@ private void readPrefs() { } } else { log.warn("prefs are taken from the config and if available from the desires as there is no preferences file specified \n"); - for (ActivityParams activityParams : this.scenario.getConfig().planCalcScore().getActivityParams()) { + for (ActivityParams activityParams : this.scenario.getConfig().scoring().getActivityParams()) { for (Person p : this.scenario.getPopulation().getPersons().values()) { prefsAttributes.putAttribute(p.getId().toString(), "typicalDuration_" + activityParams.getActivityType(), activityParams.getTypicalDuration()); @@ -199,7 +199,7 @@ private void readPrefs() { } } } - + // public boolean cacheQuadTrees() { // return this.cacheQuadTrees; // } @@ -211,7 +211,7 @@ private void readPrefs() { // this.facilitiesOfType.clear(); // } // } - + Tuple, ActivityFacilityImpl[]> getQuadTreeAndFacilities( String activityType ) { /** * If this is set to true, QuadTrees are stored in memory. @@ -235,22 +235,22 @@ Tuple, ActivityFacilityImpl[]> getQuadTreeAn } else return new Tuple<>( quadTree, facilities ); } else return getTuple(activityType); } - + private Tuple, ActivityFacilityImpl[]> getTuple(String activityType) { TreesBuilder treesBuilder = new TreesBuilder(CollectionUtils.stringToSet(activityType), this.scenario.getNetwork(), this.dccg); // treesBuilder.setActTypeConverter(this.getConverter()); treesBuilder.createTrees(scenario.getActivityFacilities()); - + ActivityFacilityImpl[] facilities = treesBuilder.getFacilitiesOfType().get(activityType); - + /* * Create a copy of the treesBuilder.getQuadTreesOfType() outcome where the * ActivityFacility objects are replaced by ActivityFacilityWithIndex objects. * TODO: let the TreeBuilder use ActivityFacilityWithIndex objects directly? */ QuadTree quadTree = null; - + QuadTree qt = treesBuilder.getQuadTreesOfType().get(activityType); if (qt != null) { double minX = qt.getMinEasting(); @@ -260,12 +260,12 @@ private Tuple, ActivityFacilityImpl[]> getTu quadTree = new QuadTree(minX, minY, maxX, maxY); for (ActivityFacility activityFacility : qt.values()) { quadTree.put(activityFacility.getCoord().getX(), activityFacility.getCoord().getY(), this.faciliesWithIndexMap.get(activityFacility.getId())); - } + } } - + return new Tuple, ActivityFacilityImpl[]>(quadTree, facilities); } - + public Scenario getScenario() { return scenario; } @@ -293,7 +293,7 @@ private boolean kValsAreRead() { // public ObjectAttributes getPersonsKValues() { // return personsKValues; // } - + // public ObjectAttributes getFacilitiesKValues() { // return facilitiesKValues; // } @@ -301,7 +301,7 @@ private boolean kValsAreRead() { public double[] getPersonsKValuesArray() { return personsKValuesArray; } - + public double[] getFacilitiesKValuesArray() { return facilitiesKValuesArray; } @@ -309,19 +309,19 @@ public double[] getFacilitiesKValuesArray() { // public Map, Integer> getPersonIndices() { // return Collections.unmodifiableMap(this.personIndices); // } - + public int getPersonIndex(Id id) { return this.personIndices.get(id); } - + // public Map, Integer> getFacilityIndices() { // return Collections.unmodifiableMap(this.facilityIndices); // } - + public int getFacilityIndex(Id id) { return this.facilityIndices.get(id); } - + ObjectAttributes getPersonsBetas() { return personsBetas; } @@ -342,17 +342,17 @@ ObjectAttributes getPrefsAttributes() { public TreeMap getFacilityPenalties() { return facilityPenalties; } - + public static final class ActivityFacilityWithIndex implements ActivityFacility, HasIndex { private final ActivityFacility activityFacility; private final int index; - + ActivityFacilityWithIndex( ActivityFacility activityFacility, int index ) { this.activityFacility = activityFacility; this.index = index; } - + @Override public Id getLinkId() { return this.activityFacility.getLinkId(); diff --git a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/ReadOrComputeMaxDCScore.java b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/ReadOrComputeMaxDCScore.java index 3d9c24759a9..b18968fa170 100644 --- a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/ReadOrComputeMaxDCScore.java +++ b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/ReadOrComputeMaxDCScore.java @@ -19,6 +19,7 @@ package org.matsim.contrib.locationchoice.frozenepsilons; +import java.io.UncheckedIOException; import java.util.HashSet; import java.util.List; @@ -30,7 +31,6 @@ import org.matsim.api.core.v01.population.Plan; import org.matsim.contrib.locationchoice.utils.ScaleEpsilon; import org.matsim.core.router.TripStructureUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.utils.objectattributes.ObjectAttributes; import org.matsim.utils.objectattributes.ObjectAttributesXmlReader; diff --git a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/ReadOrCreateKVals.java b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/ReadOrCreateKVals.java index 4b374fe53cb..fd0ae4c124d 100644 --- a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/ReadOrCreateKVals.java +++ b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/frozenepsilons/ReadOrCreateKVals.java @@ -24,28 +24,29 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Person; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.facilities.ActivityFacility; import org.matsim.utils.objectattributes.ObjectAttributes; import org.matsim.utils.objectattributes.ObjectAttributesXmlReader; - class ReadOrCreateKVals { - +import java.io.UncheckedIOException; + +class ReadOrCreateKVals { + private static final Logger log = LogManager.getLogger(ReadOrCreateKVals.class); - + private Scenario scenario; private ObjectAttributes facilitiesKValues = new ObjectAttributes(); private ObjectAttributes personsKValues = new ObjectAttributes(); private RandomFromVarDistr rnd; - + public ReadOrCreateKVals(long seed, Scenario scenario) { this.scenario = scenario; this.rnd = new RandomFromVarDistr(); this.rnd.setSeed(seed); } - + /* - * return 0 if files are read and 1 if k values are created. + * return 0 if files are read and 1 if k values are created. * This is important to know for reading (case 0) or computation of maxDCScore (case 1) */ public int run() { @@ -58,7 +59,7 @@ public int run() { return 1; } log.info("at least one facility kValue or person kValue is missing, start crating all values"); - if (pkValuesFileName != null && fkValuesFileName != null && maxEpsValuesFileName != null) { + if (pkValuesFileName != null && fkValuesFileName != null && maxEpsValuesFileName != null) { ObjectAttributesXmlReader persKValuesReader = new ObjectAttributesXmlReader(this.personsKValues); ObjectAttributesXmlReader facKValuesReader = new ObjectAttributesXmlReader(this.facilitiesKValues); try { @@ -108,7 +109,7 @@ public void assignKValues() { this.assignKValuesPersons(); this.assignKValuesAlternatives(); } - + // does not matter which distribution is chosen here private void assignKValuesPersons() { for (Person p : this.scenario.getPopulation().getPersons().values()) { @@ -120,5 +121,5 @@ private void assignKValuesAlternatives() { facility.getAttributes().putAttribute("k", rnd.getUniform(1.0)); } } - + } diff --git a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/timegeography/LocationChoicePlanStrategy.java b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/timegeography/LocationChoicePlanStrategy.java index 210f59c15e0..70562a0c1fd 100644 --- a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/timegeography/LocationChoicePlanStrategy.java +++ b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/timegeography/LocationChoicePlanStrategy.java @@ -34,13 +34,13 @@ public LocationChoicePlanStrategy(Scenario scenario, Provider tripRo delegate = new PlanStrategyImpl( new BestPlanSelector() ); break; case "ChangeExpBeta": - delegate = new PlanStrategyImpl( new ExpBetaPlanChanger( scenario.getConfig().planCalcScore().getBrainExpBeta() ) ); + delegate = new PlanStrategyImpl( new ExpBetaPlanChanger( scenario.getConfig().scoring().getBrainExpBeta() ) ); break; case "SelectRandom": delegate = new PlanStrategyImpl( new RandomPlanSelector() ); break; default: - delegate = new PlanStrategyImpl( new ExpBetaPlanSelector( scenario.getConfig().planCalcScore() ) ); + delegate = new PlanStrategyImpl( new ExpBetaPlanSelector( scenario.getConfig().scoring() ) ); break; } delegate.addStrategyModule(new DestinationChoice( tripRouterProvider, scenario, timeInterpretation) ); diff --git a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/zzunused/LCPlan.java b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/zzunused/LCPlan.java index 75da3189c3a..f1ba43fd0f5 100644 --- a/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/zzunused/LCPlan.java +++ b/contribs/locationchoice/src/main/java/org/matsim/contrib/locationchoice/zzunused/LCPlan.java @@ -285,4 +285,35 @@ else if (planElement instanceof Leg) { destPlan.score = srcPlan.getScore(); } + @Override + public void setPlanId(Id planId) { + throw new UnsupportedOperationException(); + + } + + @Override + public Id getId() { + throw new UnsupportedOperationException(); + } + + @Override + public int getIterationCreated() { + throw new UnsupportedOperationException(); + } + + @Override + public void setIterationCreated(int iteration) { + throw new UnsupportedOperationException(); + } + + @Override + public String getPlanMutator() { + throw new UnsupportedOperationException(); + } + + @Override + public void setPlanMutator(String planMutator) { + throw new UnsupportedOperationException(); + } + } diff --git a/matsim/src/main/java/org/matsim/core/router/AbstractFastRouterDelegate.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/AbstractFastRouterDelegate.java similarity index 97% rename from matsim/src/main/java/org/matsim/core/router/AbstractFastRouterDelegate.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/AbstractFastRouterDelegate.java index 9fb320b1409..b26cce699a6 100644 --- a/matsim/src/main/java/org/matsim/core/router/AbstractFastRouterDelegate.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/AbstractFastRouterDelegate.java @@ -1,112 +1,112 @@ -/* *********************************************************************** * - * project: org.matsim.* - * FastRouterDelegate.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.core.router; - -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Node; -import org.matsim.core.router.util.LeastCostPathCalculator.Path; -import org.matsim.core.router.util.NodeData; -import org.matsim.core.router.util.NodeDataFactory; -import org.matsim.core.router.util.PreProcessDijkstra; -import org.matsim.core.router.util.RoutingNetworkLink; -import org.matsim.core.router.util.RoutingNetworkNode; -import org.matsim.core.utils.collections.RouterPriorityQueue; - -import java.util.ArrayList; - -/*package*/ abstract class AbstractFastRouterDelegate implements FastRouterDelegate { - - /*package*/ final Dijkstra dijkstra; - /*package*/ final NodeDataFactory nodeDataFactory; - - /*package*/ AbstractFastRouterDelegate(final Dijkstra dijkstra, final NodeDataFactory nodeDataFactory) { - this.dijkstra = dijkstra; - this.nodeDataFactory = nodeDataFactory; - } - - @Override - public void initialize() { - // Some classes might override this method and do some additional stuff... - } - - @Override - public Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime) { - ArrayList nodes = new ArrayList<>(); - ArrayList links = new ArrayList<>(); - - nodes.add(0, ((RoutingNetworkNode) toNode).getNode()); - Link tmpLink = getData(toNode).getPrevLink(); -// if (tmpLink != null) { - // original code -// while (tmpLink.getFromNode() != fromNode) { -// links.add(0, ((RoutingNetworkLink) tmpLink).getLink()); -// nodes.add(0, ((RoutingNetworkLink) tmpLink).getLink().getFromNode()); -// tmpLink = getData(tmpLink.getFromNode()).getPrevLink(); -// } -// links.add(0, ((RoutingNetworkLink) tmpLink).getLink()); -// nodes.add(0, ((RoutingNetworkNode) tmpLink.getFromNode()).getNode()); - - /* - * Adapted this code to be compatible with the MultiNodeDijkstra located in - * the location choice contrib. When a MultiNodeDijkstra uses multiple start nodes, - * there is not a single start node that could be used to check whether - * "tmpLink.getFromNode() != fromNode" is true. Instead, the start nodes do not have - * a previous link. - * For the regular Dikstra, this is also fine since the start node also does not have - * a previous node. - * cdobler, feb'14 - */ - while (tmpLink != null) { - links.add(0, ((RoutingNetworkLink) tmpLink).getLink()); - nodes.add(0, ((RoutingNetworkLink) tmpLink).getLink().getFromNode()); - tmpLink = getData(tmpLink.getFromNode()).getPrevLink(); - } -// } - - NodeData toNodeData = getData(toNode); - return new Path(nodes, links, arrivalTime - startTime, toNodeData.getCost()); - } - - @Override - public void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue pendingNodes) { - - RoutingNetworkNode routingNetworkNode = (RoutingNetworkNode) outNode; - NodeData outData = getData(routingNetworkNode); - double currTime = outData.getTime(); - double currCost = outData.getCost(); - if (this.dijkstra.pruneDeadEnds) { - PreProcessDijkstra.DeadEndData ddOutData = getPreProcessData(routingNetworkNode); - - for (Link l : routingNetworkNode.getOutLinksArray()) { - this.dijkstra.relaxNodeLogic(l, pendingNodes, currTime, currCost, toNode, ddOutData); - } - } else { // this.pruneDeadEnds == false - for (Link l : routingNetworkNode.getOutLinksArray()) { - this.dijkstra.relaxNodeLogic(l, pendingNodes, currTime, currCost, toNode, null); - } - } - } - - @Override - public PreProcessDijkstra.DeadEndData getPreProcessData(final Node n) { - return ((RoutingNetworkNode) n).getDeadEndData(); - } -} +/* *********************************************************************** * + * project: org.matsim.* + * FastRouterDelegate.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.core.router; + +import org.matsim.api.core.v01.network.Link; +import org.matsim.api.core.v01.network.Node; +import org.matsim.core.router.util.LeastCostPathCalculator.Path; +import org.matsim.core.router.util.NodeData; +import org.matsim.core.router.util.NodeDataFactory; +import org.matsim.core.router.util.PreProcessDijkstra; +import org.matsim.core.router.util.RoutingNetworkLink; +import org.matsim.core.router.util.RoutingNetworkNode; +import org.matsim.core.utils.collections.RouterPriorityQueue; + +import java.util.ArrayList; + +/*package*/ abstract class AbstractFastRouterDelegate implements FastRouterDelegate { + + /*package*/ final Dijkstra dijkstra; + /*package*/ final NodeDataFactory nodeDataFactory; + + /*package*/ AbstractFastRouterDelegate(final Dijkstra dijkstra, final NodeDataFactory nodeDataFactory) { + this.dijkstra = dijkstra; + this.nodeDataFactory = nodeDataFactory; + } + + @Override + public void initialize() { + // Some classes might override this method and do some additional stuff... + } + + @Override + public Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime) { + ArrayList nodes = new ArrayList<>(); + ArrayList links = new ArrayList<>(); + + nodes.add(0, ((RoutingNetworkNode) toNode).getNode()); + Link tmpLink = getData(toNode).getPrevLink(); +// if (tmpLink != null) { + // original code +// while (tmpLink.getFromNode() != fromNode) { +// links.add(0, ((RoutingNetworkLink) tmpLink).getLink()); +// nodes.add(0, ((RoutingNetworkLink) tmpLink).getLink().getFromNode()); +// tmpLink = getData(tmpLink.getFromNode()).getPrevLink(); +// } +// links.add(0, ((RoutingNetworkLink) tmpLink).getLink()); +// nodes.add(0, ((RoutingNetworkNode) tmpLink.getFromNode()).getNode()); + + /* + * Adapted this code to be compatible with the MultiNodeDijkstra located in + * the location choice contrib. When a MultiNodeDijkstra uses multiple start nodes, + * there is not a single start node that could be used to check whether + * "tmpLink.getFromNode() != fromNode" is true. Instead, the start nodes do not have + * a previous link. + * For the regular Dikstra, this is also fine since the start node also does not have + * a previous node. + * cdobler, feb'14 + */ + while (tmpLink != null) { + links.add(0, ((RoutingNetworkLink) tmpLink).getLink()); + nodes.add(0, ((RoutingNetworkLink) tmpLink).getLink().getFromNode()); + tmpLink = getData(tmpLink.getFromNode()).getPrevLink(); + } +// } + + NodeData toNodeData = getData(toNode); + return new Path(nodes, links, arrivalTime - startTime, toNodeData.getCost()); + } + + @Override + public void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue pendingNodes) { + + RoutingNetworkNode routingNetworkNode = (RoutingNetworkNode) outNode; + NodeData outData = getData(routingNetworkNode); + double currTime = outData.getTime(); + double currCost = outData.getCost(); + if (this.dijkstra.pruneDeadEnds) { + PreProcessDijkstra.DeadEndData ddOutData = getPreProcessData(routingNetworkNode); + + for (Link l : routingNetworkNode.getOutLinksArray()) { + this.dijkstra.relaxNodeLogic(l, pendingNodes, currTime, currCost, toNode, ddOutData); + } + } else { // this.pruneDeadEnds == false + for (Link l : routingNetworkNode.getOutLinksArray()) { + this.dijkstra.relaxNodeLogic(l, pendingNodes, currTime, currCost, toNode, null); + } + } + } + + @Override + public PreProcessDijkstra.DeadEndData getPreProcessData(final Node n) { + return ((RoutingNetworkNode) n).getDeadEndData(); + } +} diff --git a/matsim/src/main/java/org/matsim/core/router/ArrayFastRouterDelegate.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/ArrayFastRouterDelegate.java similarity index 97% rename from matsim/src/main/java/org/matsim/core/router/ArrayFastRouterDelegate.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/ArrayFastRouterDelegate.java index 0a9fd54a41e..d220c3aa769 100644 --- a/matsim/src/main/java/org/matsim/core/router/ArrayFastRouterDelegate.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/ArrayFastRouterDelegate.java @@ -1,62 +1,62 @@ -/* *********************************************************************** * - * project: org.matsim.* - * ArrayFastRouterDelegate.java - * * - * *********************************************************************** * - * * - * 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.core.router; - -import org.matsim.api.core.v01.network.Node; -import org.matsim.core.router.util.ArrayRoutingNetwork; -import org.matsim.core.router.util.ArrayRoutingNetworkNode; -import org.matsim.core.router.util.NodeData; -import org.matsim.core.router.util.NodeDataFactory; - -/*package*/ class ArrayFastRouterDelegate extends AbstractFastRouterDelegate { - - private final ArrayRoutingNetwork network; - private final NodeData[] nodeData; - private boolean isInitialized = false; - - /*package*/ ArrayFastRouterDelegate(final Dijkstra dijkstra, final NodeDataFactory nodeDataFactory, - final ArrayRoutingNetwork network) { - super(dijkstra, nodeDataFactory); - this.network = network; - this.nodeData = new NodeData[network.getNodes().size()]; - } - - @Override - public final void initialize() { - // lazy initialization - if (!isInitialized) { - for (Node node : this.network.getNodes().values()) { - int index = ((ArrayRoutingNetworkNode) node).getArrayIndex(); - this.nodeData[index] = nodeDataFactory.createNodeData(); - } - - this.isInitialized = true; - } - } - - /* - * The NodeData is taken from the array. - */ - public NodeData getData(final Node n) { - ArrayRoutingNetworkNode routingNetworkNode = (ArrayRoutingNetworkNode) n; - return this.nodeData[routingNetworkNode.getArrayIndex()]; - } +/* *********************************************************************** * + * project: org.matsim.* + * ArrayFastRouterDelegate.java + * * + * *********************************************************************** * + * * + * 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.core.router; + +import org.matsim.api.core.v01.network.Node; +import org.matsim.core.router.util.ArrayRoutingNetwork; +import org.matsim.core.router.util.ArrayRoutingNetworkNode; +import org.matsim.core.router.util.NodeData; +import org.matsim.core.router.util.NodeDataFactory; + +/*package*/ class ArrayFastRouterDelegate extends AbstractFastRouterDelegate { + + private final ArrayRoutingNetwork network; + private final NodeData[] nodeData; + private boolean isInitialized = false; + + /*package*/ ArrayFastRouterDelegate(final Dijkstra dijkstra, final NodeDataFactory nodeDataFactory, + final ArrayRoutingNetwork network) { + super(dijkstra, nodeDataFactory); + this.network = network; + this.nodeData = new NodeData[network.getNodes().size()]; + } + + @Override + public final void initialize() { + // lazy initialization + if (!isInitialized) { + for (Node node : this.network.getNodes().values()) { + int index = ((ArrayRoutingNetworkNode) node).getArrayIndex(); + this.nodeData[index] = nodeDataFactory.createNodeData(); + } + + this.isInitialized = true; + } + } + + /* + * The NodeData is taken from the array. + */ + public NodeData getData(final Node n) { + ArrayRoutingNetworkNode routingNetworkNode = (ArrayRoutingNetworkNode) n; + return this.nodeData[routingNetworkNode.getArrayIndex()]; + } } \ No newline at end of file diff --git a/matsim/src/main/java/org/matsim/core/router/ArrayFastRouterDelegateFactory.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/ArrayFastRouterDelegateFactory.java similarity index 100% rename from matsim/src/main/java/org/matsim/core/router/ArrayFastRouterDelegateFactory.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/ArrayFastRouterDelegateFactory.java diff --git a/matsim/src/main/java/org/matsim/core/router/FastMultiNodeDijkstra.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/FastMultiNodeDijkstra.java similarity index 92% rename from matsim/src/main/java/org/matsim/core/router/FastMultiNodeDijkstra.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/FastMultiNodeDijkstra.java index e2315d02101..d7b1b420751 100644 --- a/matsim/src/main/java/org/matsim/core/router/FastMultiNodeDijkstra.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/FastMultiNodeDijkstra.java @@ -1,208 +1,207 @@ -/* *********************************************************************** * - * project: org.matsim.* - * FastDijkstra.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.core.router; - -import java.util.Collection; -import java.util.Iterator; - -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.router.priorityqueue.BinaryMinHeap; -import org.matsim.core.router.util.ArrayRoutingNetwork; -import org.matsim.core.router.util.ArrayRoutingNetworkNode; -import org.matsim.core.router.util.DijkstraNodeData; -import org.matsim.core.router.util.DijkstraNodeDataFactory; -import org.matsim.core.router.util.PreProcessDijkstra; -import org.matsim.core.router.util.RoutingNetwork; -import org.matsim.core.router.util.RoutingNetworkNode; -import org.matsim.core.router.util.TravelDisutility; -import org.matsim.core.router.util.TravelTime; -import org.matsim.core.utils.collections.RouterPriorityQueue; -import org.matsim.vehicles.Vehicle; - -/** - *

    Performance optimized version of the MultiNodeDijkstra least cost path router - * which uses its own network to route within.

    - * - * @see org.matsim.core.router.MultiNodeDijkstra - * @see org.matsim.core.router.FastDijkstra - * @see org.matsim.core.router.util.RoutingNetwork - * @author cdobler - */ -public class FastMultiNodeDijkstra extends MultiNodeDijkstra { - - /*package*/ final RoutingNetwork routingNetwork; - private final FastRouterDelegate fastRouter; - private BinaryMinHeap heap = null; - private int maxSize = -1; - - /* - * Create the routing network here and clear the nodeData map - * which is not used by this implementation. - */ - protected FastMultiNodeDijkstra(final RoutingNetwork routingNetwork, final TravelDisutility costFunction, - final TravelTime timeFunction, final PreProcessDijkstra preProcessData, - final FastRouterDelegateFactory fastRouterFactory, boolean searchAllEndNodes) { - super(routingNetwork, costFunction, timeFunction, preProcessData, searchAllEndNodes); - - this.routingNetwork = routingNetwork; - this.fastRouter = fastRouterFactory.createFastRouterDelegate(this, new DijkstraNodeDataFactory(), routingNetwork); - - this.nodeData.clear(); - } - - /* - * Replace the references to the from and to nodes with their corresponding - * nodes in the routing network. - */ - @Override - public Path calcLeastCostPath(final Node fromNode, final Node toNode, final double startTime, final Person person, final Vehicle vehicle) { - - this.fastRouter.initialize(); - this.routingNetwork.initialize(); - - Node routingNetworkFromNode; - Node routingNetworkToNode; - - if (fromNode instanceof ImaginaryNode) { - Collection initialNodes = ((ImaginaryNode) fromNode).initialNodes; - for (InitialNode initialNode : initialNodes) initialNode.node = routingNetwork.getNodes().get(initialNode.node.getId()); - routingNetworkFromNode = fromNode; - } else routingNetworkFromNode = routingNetwork.getNodes().get(fromNode.getId()); - - if (toNode instanceof ImaginaryNode) { - Collection initialNodes = ((ImaginaryNode) toNode).initialNodes; - for (InitialNode initialNode : initialNodes) initialNode.node = routingNetwork.getNodes().get(initialNode.node.getId()); - routingNetworkToNode = toNode; - } else routingNetworkToNode = routingNetwork.getNodes().get(toNode.getId()); - - return super.calcLeastCostPath(routingNetworkFromNode, routingNetworkToNode, startTime, person, vehicle); - } - - @Override - /*package*/ RouterPriorityQueue createRouterPriorityQueue() { - /* - * Re-use existing BinaryMinHeap instead of creating a new one. For large networks (> 10^6 nodes and links) this reduced - * the computation time by 40%! cdobler, oct'15 - */ - if (this.routingNetwork instanceof ArrayRoutingNetwork) { - int size = this.routingNetwork.getNodes().size(); - if (this.heap == null || this.maxSize != size) { - this.maxSize = size; - this.heap = new BinaryMinHeap<>(maxSize); - return this.heap; - } else { - this.heap.reset(); - return this.heap; - } -// int maxSize = this.routingNetwork.getNodes().size(); -// return new BinaryMinHeap(maxSize); - } else { - return super.createRouterPriorityQueue(); - } - } - - /* - * Constructs the path and replaces the nodes and links from the routing network - * with their corresponding nodes and links from the network. - */ - @Override - protected Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime) { - /* - * If the fromNode is an imaginaryNode some special treatment is necessary. - * The path returned by the fastRouter also contains the travel time and cost - * from the trips start coordinate to the start node of the path. This information - * is stored in the ImaginaryNode (respectively in its InitialNodes). Therefore, - * we have to store a reference to the imaginary node. - */ - ImaginaryNode imaginaryNode = null; - if (fromNode instanceof ImaginaryNode) imaginaryNode = (ImaginaryNode) fromNode; - - if (!(fromNode instanceof RoutingNetworkNode)) fromNode = this.routingNetwork.getNodes().get(fromNode.getId()); - if (!(toNode instanceof RoutingNetworkNode)) toNode = this.routingNetwork.getNodes().get(toNode.getId()); - - Path path = this.fastRouter.constructPath(fromNode, toNode, startTime, arrivalTime); - - /* - * Here, we correct the path's travel time and cost if necessary. - * To do so, we look for the InitialNode that matches the path's first node. - * The path's travel time and cost are then reduced by the values - * found in the InitialNode. - */ - if (imaginaryNode != null && path != null && path.nodes.size() > 0) { - Node pathFromNode = path.getFromNode(); - double initialCost = 0.0; - double initialTime = 0.0; - - Iterator iter = imaginaryNode.initialNodes.iterator(); - while (iter.hasNext()) { - InitialNode initialNode = iter.next(); - if (initialNode.node.getId().equals(pathFromNode.getId())) { - initialCost = initialNode.initialCost; - initialTime = initialNode.initialTime; - break; - } - } - - return new Path(path.nodes, path.links, path.travelTime - initialTime, path.travelCost - initialCost); - } - - return path; - } - - /* - * Constructs the path and replaces the nodes and links from the routing network - * with their corresponding nodes and links from the network. - */ - @Override - public Path constructPath(Node fromNode, Node toNode, double startTime) { - if (toNode == null || fromNode == null) return null; - if (!(fromNode instanceof RoutingNetworkNode)) fromNode = this.routingNetwork.getNodes().get(fromNode.getId()); - if (!(toNode instanceof RoutingNetworkNode)) toNode = this.routingNetwork.getNodes().get(toNode.getId()); - return super.constructPath(fromNode, toNode, startTime); - } - - /* - * For performance reasons the outgoing links of a node are stored in - * the routing network in an array instead of a map. Therefore we have - * to iterate over an array instead of over a map. - */ - @Override - protected void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue pendingNodes) { - fastRouter.relaxNode(outNode, toNode, pendingNodes); - } - - /* - * The DijkstraNodeData is taken from the RoutingNetworkNode and not from a map. - */ - @Override - protected DijkstraNodeData getData(final Node n) { - return (DijkstraNodeData) fastRouter.getData(n); - } - - /* - * The DeadEndData is taken from the RoutingNetworkNode and not from a map. - */ - @Override - protected PreProcessDijkstra.DeadEndData getPreProcessData(final Node n) { - return fastRouter.getPreProcessData(n); - } -} +/* *********************************************************************** * + * project: org.matsim.* + * FastDijkstra.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.core.router; + +import java.util.Collection; +import java.util.Iterator; + +import org.matsim.api.core.v01.network.Node; +import org.matsim.api.core.v01.population.Person; +import org.matsim.core.router.priorityqueue.BinaryMinHeap; +import org.matsim.core.router.util.ArrayRoutingNetwork; +import org.matsim.core.router.util.ArrayRoutingNetworkNode; +import org.matsim.core.router.util.DijkstraNodeData; +import org.matsim.core.router.util.DijkstraNodeDataFactory; +import org.matsim.core.router.util.PreProcessDijkstra; +import org.matsim.core.router.util.RoutingNetwork; +import org.matsim.core.router.util.RoutingNetworkNode; +import org.matsim.core.router.util.TravelDisutility; +import org.matsim.core.router.util.TravelTime; +import org.matsim.core.utils.collections.RouterPriorityQueue; +import org.matsim.vehicles.Vehicle; + +/** + *

    Performance optimized version of the MultiNodeDijkstra least cost path router + * which uses its own network to route within.

    + * + * @see MultiNodeDijkstra + * @see org.matsim.core.router.util.RoutingNetwork + * @author cdobler + */ +public class FastMultiNodeDijkstra extends MultiNodeDijkstra { + + /*package*/ final RoutingNetwork routingNetwork; + private final FastRouterDelegate fastRouter; + private BinaryMinHeap heap = null; + private int maxSize = -1; + + /* + * Create the routing network here and clear the nodeData map + * which is not used by this implementation. + */ + protected FastMultiNodeDijkstra(final RoutingNetwork routingNetwork, final TravelDisutility costFunction, + final TravelTime timeFunction, final PreProcessDijkstra preProcessData, + final FastRouterDelegateFactory fastRouterFactory, boolean searchAllEndNodes) { + super(routingNetwork, costFunction, timeFunction, preProcessData, searchAllEndNodes); + + this.routingNetwork = routingNetwork; + this.fastRouter = fastRouterFactory.createFastRouterDelegate(this, new DijkstraNodeDataFactory(), routingNetwork); + + this.nodeData.clear(); + } + + /* + * Replace the references to the from and to nodes with their corresponding + * nodes in the routing network. + */ + @Override + public Path calcLeastCostPath(final Node fromNode, final Node toNode, final double startTime, final Person person, final Vehicle vehicle) { + + this.fastRouter.initialize(); + this.routingNetwork.initialize(); + + Node routingNetworkFromNode; + Node routingNetworkToNode; + + if (fromNode instanceof ImaginaryNode) { + Collection initialNodes = ((ImaginaryNode) fromNode).initialNodes; + for (InitialNode initialNode : initialNodes) initialNode.node = routingNetwork.getNodes().get(initialNode.node.getId()); + routingNetworkFromNode = fromNode; + } else routingNetworkFromNode = routingNetwork.getNodes().get(fromNode.getId()); + + if (toNode instanceof ImaginaryNode) { + Collection initialNodes = ((ImaginaryNode) toNode).initialNodes; + for (InitialNode initialNode : initialNodes) initialNode.node = routingNetwork.getNodes().get(initialNode.node.getId()); + routingNetworkToNode = toNode; + } else routingNetworkToNode = routingNetwork.getNodes().get(toNode.getId()); + + return super.calcLeastCostPath(routingNetworkFromNode, routingNetworkToNode, startTime, person, vehicle); + } + + @Override + /*package*/ RouterPriorityQueue createRouterPriorityQueue() { + /* + * Re-use existing BinaryMinHeap instead of creating a new one. For large networks (> 10^6 nodes and links) this reduced + * the computation time by 40%! cdobler, oct'15 + */ + if (this.routingNetwork instanceof ArrayRoutingNetwork) { + int size = this.routingNetwork.getNodes().size(); + if (this.heap == null || this.maxSize != size) { + this.maxSize = size; + this.heap = new BinaryMinHeap<>(maxSize); + return this.heap; + } else { + this.heap.reset(); + return this.heap; + } +// int maxSize = this.routingNetwork.getNodes().size(); +// return new BinaryMinHeap(maxSize); + } else { + return super.createRouterPriorityQueue(); + } + } + + /* + * Constructs the path and replaces the nodes and links from the routing network + * with their corresponding nodes and links from the network. + */ + @Override + protected Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime) { + /* + * If the fromNode is an imaginaryNode some special treatment is necessary. + * The path returned by the fastRouter also contains the travel time and cost + * from the trips start coordinate to the start node of the path. This information + * is stored in the ImaginaryNode (respectively in its InitialNodes). Therefore, + * we have to store a reference to the imaginary node. + */ + ImaginaryNode imaginaryNode = null; + if (fromNode instanceof ImaginaryNode) imaginaryNode = (ImaginaryNode) fromNode; + + if (!(fromNode instanceof RoutingNetworkNode)) fromNode = this.routingNetwork.getNodes().get(fromNode.getId()); + if (!(toNode instanceof RoutingNetworkNode)) toNode = this.routingNetwork.getNodes().get(toNode.getId()); + + Path path = this.fastRouter.constructPath(fromNode, toNode, startTime, arrivalTime); + + /* + * Here, we correct the path's travel time and cost if necessary. + * To do so, we look for the InitialNode that matches the path's first node. + * The path's travel time and cost are then reduced by the values + * found in the InitialNode. + */ + if (imaginaryNode != null && path != null && path.nodes.size() > 0) { + Node pathFromNode = path.getFromNode(); + double initialCost = 0.0; + double initialTime = 0.0; + + Iterator iter = imaginaryNode.initialNodes.iterator(); + while (iter.hasNext()) { + InitialNode initialNode = iter.next(); + if (initialNode.node.getId().equals(pathFromNode.getId())) { + initialCost = initialNode.initialCost; + initialTime = initialNode.initialTime; + break; + } + } + + return new Path(path.nodes, path.links, path.travelTime - initialTime, path.travelCost - initialCost); + } + + return path; + } + + /* + * Constructs the path and replaces the nodes and links from the routing network + * with their corresponding nodes and links from the network. + */ + @Override + public Path constructPath(Node fromNode, Node toNode, double startTime) { + if (toNode == null || fromNode == null) return null; + if (!(fromNode instanceof RoutingNetworkNode)) fromNode = this.routingNetwork.getNodes().get(fromNode.getId()); + if (!(toNode instanceof RoutingNetworkNode)) toNode = this.routingNetwork.getNodes().get(toNode.getId()); + return super.constructPath(fromNode, toNode, startTime); + } + + /* + * For performance reasons the outgoing links of a node are stored in + * the routing network in an array instead of a map. Therefore we have + * to iterate over an array instead of over a map. + */ + @Override + protected void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue pendingNodes) { + fastRouter.relaxNode(outNode, toNode, pendingNodes); + } + + /* + * The DijkstraNodeData is taken from the RoutingNetworkNode and not from a map. + */ + @Override + protected DijkstraNodeData getData(final Node n) { + return (DijkstraNodeData) fastRouter.getData(n); + } + + /* + * The DeadEndData is taken from the RoutingNetworkNode and not from a map. + */ + @Override + protected PreProcessDijkstra.DeadEndData getPreProcessData(final Node n) { + return fastRouter.getPreProcessData(n); + } +} diff --git a/matsim/src/main/java/org/matsim/core/router/FastMultiNodeDijkstraFactory.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/FastMultiNodeDijkstraFactory.java similarity index 100% rename from matsim/src/main/java/org/matsim/core/router/FastMultiNodeDijkstraFactory.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/FastMultiNodeDijkstraFactory.java diff --git a/matsim/src/main/java/org/matsim/core/router/FastRouterDelegate.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/FastRouterDelegate.java similarity index 97% rename from matsim/src/main/java/org/matsim/core/router/FastRouterDelegate.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/FastRouterDelegate.java index f1706df5828..1ba4c7acd5b 100644 --- a/matsim/src/main/java/org/matsim/core/router/FastRouterDelegate.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/FastRouterDelegate.java @@ -1,65 +1,65 @@ -/* *********************************************************************** * - * project: org.matsim.* - * FastRouterDelegate.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.core.router; - -import org.matsim.api.core.v01.network.Node; -import org.matsim.core.router.util.LeastCostPathCalculator.Path; -import org.matsim.core.router.util.NodeData; -import org.matsim.core.router.util.PreProcessDijkstra; -import org.matsim.core.utils.collections.RouterPriorityQueue; - -/** - * This class is used by the faster implementations of the Dijkstra, AStarEuclidean and - * AStarLandmarks router. Basically, the methods perform the conversation from the - * Network to the RoutingNetwork where the routing data is stored in the nodes and not - * in maps. - * - * @author cdobler - */ -/*package*/ interface FastRouterDelegate { - - /* - * Some implementations might use this for lazy initialization. - */ - /*package*/ void initialize(); - - /* - * Constructs the path and replaces the nodes and links from the routing network - * with their corresponding nodes and links from the network. - */ - /*package*/ Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime); - /* - * For performance reasons the outgoing links of a node are stored in - * the routing network in an array instead of a map. Therefore we have - * to iterate over an array instead of over a map. - */ - /*package*/ void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue pendingNodes); - - /* - * The NodeData is taken from the RoutingNetworkNode and not from a map. - */ - /*package*/ NodeData getData(final Node n); - - /* - * The DeadEndData is taken from the RoutingNetworkNode and not from a map. - */ - /*package*/ PreProcessDijkstra.DeadEndData getPreProcessData(final Node n); -} +/* *********************************************************************** * + * project: org.matsim.* + * FastRouterDelegate.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.core.router; + +import org.matsim.api.core.v01.network.Node; +import org.matsim.core.router.util.LeastCostPathCalculator.Path; +import org.matsim.core.router.util.NodeData; +import org.matsim.core.router.util.PreProcessDijkstra; +import org.matsim.core.utils.collections.RouterPriorityQueue; + +/** + * This class is used by the faster implementations of the Dijkstra, AStarEuclidean and + * AStarLandmarks router. Basically, the methods perform the conversation from the + * Network to the RoutingNetwork where the routing data is stored in the nodes and not + * in maps. + * + * @author cdobler + */ +/*package*/ interface FastRouterDelegate { + + /* + * Some implementations might use this for lazy initialization. + */ + /*package*/ void initialize(); + + /* + * Constructs the path and replaces the nodes and links from the routing network + * with their corresponding nodes and links from the network. + */ + /*package*/ Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime); + /* + * For performance reasons the outgoing links of a node are stored in + * the routing network in an array instead of a map. Therefore we have + * to iterate over an array instead of over a map. + */ + /*package*/ void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue pendingNodes); + + /* + * The NodeData is taken from the RoutingNetworkNode and not from a map. + */ + /*package*/ NodeData getData(final Node n); + + /* + * The DeadEndData is taken from the RoutingNetworkNode and not from a map. + */ + /*package*/ PreProcessDijkstra.DeadEndData getPreProcessData(final Node n); +} diff --git a/matsim/src/main/java/org/matsim/core/router/FastRouterDelegateFactory.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/FastRouterDelegateFactory.java similarity index 94% rename from matsim/src/main/java/org/matsim/core/router/FastRouterDelegateFactory.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/FastRouterDelegateFactory.java index 807ef17ab22..14d1a98a82c 100644 --- a/matsim/src/main/java/org/matsim/core/router/FastRouterDelegateFactory.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/FastRouterDelegateFactory.java @@ -26,5 +26,5 @@ public interface FastRouterDelegateFactory { public FastRouterDelegate createFastRouterDelegate(Dijkstra dijkstra, - NodeDataFactory nodeDataFactory, RoutingNetwork routingNetwork); + NodeDataFactory nodeDataFactory, RoutingNetwork routingNetwork); } diff --git a/matsim/src/main/java/org/matsim/core/router/ImaginaryNode.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/ImaginaryNode.java similarity index 97% rename from matsim/src/main/java/org/matsim/core/router/ImaginaryNode.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/ImaginaryNode.java index 2bd9d531434..2e299aa6d1c 100644 --- a/matsim/src/main/java/org/matsim/core/router/ImaginaryNode.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/ImaginaryNode.java @@ -30,39 +30,39 @@ import org.matsim.utils.objectattributes.attributable.Attributes; /** - * Used by the MultiNodeDijkstra for backwards compatibility with default Dijkstra. - * + * Used by the MultiNodeDijkstra for backwards compatibility with default Dijkstra. + * * @see org.matsim.core.router.Dijkstra - * @see org.matsim.core.router.MultiNodeDijkstra + * @see MultiNodeDijkstra * @author cdobler */ public class ImaginaryNode implements Node { /*package*/ final Collection initialNodes; /*package*/ final Coord coord; - + ImaginaryNode(Collection initialNodes, Coord coord) { this.initialNodes = initialNodes; this.coord = coord; } - + ImaginaryNode(Collection initialNodes) { this.initialNodes = initialNodes; - + double sumX = 0.0; double sumY = 0.0; - + for (InitialNode initialNode : initialNodes) { sumX += initialNode.node.getCoord().getX(); sumY += initialNode.node.getCoord().getY(); } - + sumX /= initialNodes.size(); sumY /= initialNodes.size(); this.coord = new Coord(sumX, sumY); } - + @Override public Coord getCoord() { return this.coord; @@ -112,4 +112,4 @@ public void setCoord(Coord coord) { public Attributes getAttributes() { throw new UnsupportedOperationException(); } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/router/MultiNodeDijkstra.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/MultiNodeDijkstra.java similarity index 97% rename from matsim/src/main/java/org/matsim/core/router/MultiNodeDijkstra.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/MultiNodeDijkstra.java index 3a400c5d35b..689c16a85c6 100644 --- a/matsim/src/main/java/org/matsim/core/router/MultiNodeDijkstra.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/MultiNodeDijkstra.java @@ -43,66 +43,66 @@ /** *

    An extended implementation of the Dijkstra algorithm that supports multiple * start- and/or end nodes.

    - * + * *

    To do so, ImaginaryNodes and IntialNodes are introduced which is required for * backwards compatibility with the default Dijkstra implementation which expects * only single nodes as arguments.

    - * + * *

    Therefore, ImaginaryNodes are introduced. They contain a collection of * InitialNodes that represents the start or end nodes to be used by the algorithm. * Each InitialNode represents a node from the network. In addition, initial time and * costs can be defined, i.e. the time respectively costs to reach that node.

    - * + * *

    By default, only the cheapest path between is calculated, i.e. the routing algorithm * will terminate before all end nodes have been reached. This behaviour can be changed * by setting the searchAllEndNodes parameter to true.

    - * + * * @see org.matsim.core.router.Dijkstra * @see org.matsim.core.router.InitialNode - * @see org.matsim.core.router.ImaginaryNode - * + * @see ImaginaryNode + * * @author cdobler */ public class MultiNodeDijkstra extends Dijkstra implements MultiNodePathCalculator { - + private final static Logger log = LogManager.getLogger(MultiNodeDijkstra.class); - + /* * If this value is true, the algorithm tries to find routes to all end nodes. * Otherwise only the one(s) with the lowest costs are found. - * + * * When enabling this option, select end nodes with care! If only one of them * is in a not reachable part of the network, the algorithm will process the * entire reachable part of the network before terminating. */ private boolean searchAllEndNodes; - + MultiNodeDijkstra(Network network, TravelDisutility costFunction, TravelTime timeFunction, boolean searchAllEndNodes) { super(network, costFunction, timeFunction); this.searchAllEndNodes = searchAllEndNodes; } - + MultiNodeDijkstra(final Network network, final TravelDisutility costFunction, final TravelTime timeFunction, final PreProcessDijkstra preProcessData, boolean searchAllEndNodes) { super(network, costFunction, timeFunction, preProcessData); this.searchAllEndNodes = searchAllEndNodes; } - + public static ImaginaryNode createImaginaryNode(Collection nodes) { return new ImaginaryNode(nodes); } - + public static ImaginaryNode createImaginaryNode(Collection nodes, Coord coord) { return new ImaginaryNode(nodes, coord); } - + /* * We have to extend this method from the original Dijkstra. The given input nodes might be * ImaginaryNodes which contain multiple start / end nodes for the routing process. Those * nodes should be part of the routing network, therefore we perform the check for each of them. - * + * * Regular nodes are directly passed to the super class. - * + * * cdobler, jun'14 */ /*package*/ @Override @@ -112,29 +112,29 @@ void checkNodeBelongToNetwork(Node node) { for (InitialNode initialNode : imaginaryNode.initialNodes) super.checkNodeBelongToNetwork(initialNode.node); } else super.checkNodeBelongToNetwork(node); } - + @Override /*package*/ Node searchLogic( final Node fromNode, final Node toNode, final RouterPriorityQueue pendingNodes, Person person, Vehicle vehicle ) { - + // If it is an imaginary node... if (toNode instanceof ImaginaryNode) { - + Map, InitialNode> endNodes = new HashMap<>(); - + Collection initialNodes = ((ImaginaryNode) toNode).initialNodes; for (InitialNode initialNode : initialNodes) endNodes.put(initialNode.node.getId(), initialNode); // find out which one is the cheapest end node double minCost = Double.POSITIVE_INFINITY; Node minCostNode = null; - + // continue searching as long as unvisited end nodes are available boolean stillSearching = endNodes.size() > 0; - + while (stillSearching) { Node outNode = pendingNodes.poll(); - + if (outNode == null) { /* * This is not necessarily a problem. Some of the out nodes might be reachable only @@ -154,24 +154,24 @@ void checkNodeBelongToNetwork(Node node) { log.trace(sb.toString()); } } - + if (searchAllEndNodes && endNodes.size() > 0) { for (InitialNode endNode : endNodes.values()) { log.trace("No route was found from node " + fromNode.getId() + " to destination node " + endNode.node.getId() + "."); log.trace( Dijkstra.createInfoMessage( person, vehicle ) ); } } - + endNodes.clear(); stillSearching = false; } else { DijkstraNodeData data = getData(outNode); InitialNode initData = endNodes.remove(outNode.getId()); - + /* * If the node is an end node. - * Note: - * The node was head of the priority queue, i.e. the shortest path to the + * Note: + * The node was head of the priority queue, i.e. the shortest path to the * node has been found. The algorithm will not re-visit the node on another * route! */ @@ -182,7 +182,7 @@ void checkNodeBelongToNetwork(Node node) { minCostNode = outNode; } } - + if (searchAllEndNodes) { relaxNode(outNode, null, pendingNodes); stillSearching = endNodes.size() > 0; @@ -196,13 +196,13 @@ void checkNodeBelongToNetwork(Node node) { } } } - + return minCostNode; - } + } // ... otherwise: default behaviour. else return super.searchLogic(fromNode, toNode, pendingNodes, person, vehicle ); } - + /* * initFromNode -> first Node in pendingNodes -> calcLeastCostPath will relax that node * -> we relax that dummy node here @@ -210,18 +210,18 @@ void checkNodeBelongToNetwork(Node node) { @Override /*package*/ void initFromNode(final Node fromNode, final Node toNode, final double startTime, final RouterPriorityQueue pendingNodes) { - + // If it is an imaginary node, we relax it. - if (fromNode instanceof ImaginaryNode) { + if (fromNode instanceof ImaginaryNode) { relaxImaginaryNode((ImaginaryNode) fromNode, pendingNodes, startTime); } // ... otherwise: default behaviour. else super.initFromNode(fromNode, toNode, startTime, pendingNodes); } - + protected void relaxImaginaryNode(final ImaginaryNode outNode, final RouterPriorityQueue pendingNodes, final double currTime) { - + double currCost = 0.0; // should be 0 for (InitialNode initialNode : outNode.initialNodes) { @@ -229,10 +229,10 @@ protected void relaxImaginaryNode(final ImaginaryNode outNode, final RouterPrior double travelCost = initialNode.initialCost; DijkstraNodeData data = getData(initialNode.node); Link l = null; // fromLink - use a dummy link here?? - visitNode(initialNode.node, data, pendingNodes, currTime + travelTime, currCost + travelCost, l); + visitNode(initialNode.node, data, pendingNodes, currTime + travelTime, currCost + travelCost, l); } - } - + } + @Override protected Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime) { ArrayList nodes = new ArrayList(); @@ -240,7 +240,7 @@ protected Path constructPath(Node fromNode, Node toNode, double startTime, doubl nodes.add(0, toNode); Link tmpLink = getData(toNode).getPrevLink(); - + // Only this part has been adapted. Could probably also be changed in the super class. while (tmpLink != null) { links.add(0, tmpLink); @@ -256,12 +256,12 @@ protected Path constructPath(Node fromNode, Node toNode, double startTime, doubl return path; } - + /** * This method should only be called from outside after calcLeastCostPath(...) has * been executed. After that, the paths between the multiple start and/or end nodes * can be constructed using this method. - * + * * Is there a way to check whether this method is called as intended?? * cdobler, oct'13 */ @@ -275,9 +275,9 @@ public Path constructPath(Node fromNode, Node toNode, double startTime) { if (!fromData.isVisited(this.getIterationId())) return null; double arrivalTime = toData.getTime(); - + // now construct and return the path - return constructPath(fromNode, toNode, startTime, arrivalTime); + return constructPath(fromNode, toNode, startTime, arrivalTime); } } diff --git a/matsim/src/main/java/org/matsim/core/router/MultiNodeDijkstraFactory.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/MultiNodeDijkstraFactory.java similarity index 98% rename from matsim/src/main/java/org/matsim/core/router/MultiNodeDijkstraFactory.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/MultiNodeDijkstraFactory.java index 0859b794dec..060cb872150 100644 --- a/matsim/src/main/java/org/matsim/core/router/MultiNodeDijkstraFactory.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/MultiNodeDijkstraFactory.java @@ -35,12 +35,12 @@ public class MultiNodeDijkstraFactory implements LeastCostPathCalculatorFactory private final boolean searchAllEndNodes; private final boolean usePreProcessData; private final Map preProcessData = new HashMap<>(); - + public MultiNodeDijkstraFactory() { this.searchAllEndNodes = false; this.usePreProcessData = false; } - + public MultiNodeDijkstraFactory(final boolean searchAllEndNodes) { this.searchAllEndNodes = searchAllEndNodes; this.usePreProcessData = false; @@ -52,7 +52,7 @@ public MultiNodeDijkstraFactory(final boolean usePreProcessData, final boolean s } @Override - public synchronized LeastCostPathCalculator createPathCalculator(final Network network, final TravelDisutility travelCosts, final TravelTime travelTimes) { + public synchronized LeastCostPathCalculator createPathCalculator(final Network network, final TravelDisutility travelCosts, final TravelTime travelTimes) { if (this.usePreProcessData) { PreProcessDijkstra preProcessDijkstra = this.preProcessData.get(network); if (preProcessDijkstra == null) { @@ -62,7 +62,7 @@ public synchronized LeastCostPathCalculator createPathCalculator(final Network n } return new MultiNodeDijkstra(network, travelCosts, travelTimes, preProcessDijkstra, this.searchAllEndNodes); } - + return new MultiNodeDijkstra(network, travelCosts, travelTimes, this.searchAllEndNodes); } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/router/MultiNodePathCalculator.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/MultiNodePathCalculator.java similarity index 98% rename from matsim/src/main/java/org/matsim/core/router/MultiNodePathCalculator.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/MultiNodePathCalculator.java index 787dd6c9d86..52abc2a295e 100644 --- a/matsim/src/main/java/org/matsim/core/router/MultiNodePathCalculator.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/MultiNodePathCalculator.java @@ -21,11 +21,12 @@ package org.matsim.core.router; import org.matsim.api.core.v01.network.Node; +import org.matsim.core.router.ImaginaryNode; import org.matsim.core.router.util.LeastCostPathCalculator; /** * Marker interface so that one can program against an interface rather than against a very specific implementation. - * + * * @author nagel */ public interface MultiNodePathCalculator extends LeastCostPathCalculator { diff --git a/matsim/src/main/java/org/matsim/core/router/RoutingNetworkImaginaryNode.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/RoutingNetworkImaginaryNode.java similarity index 100% rename from matsim/src/main/java/org/matsim/core/router/RoutingNetworkImaginaryNode.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/RoutingNetworkImaginaryNode.java diff --git a/matsim/src/main/java/org/matsim/core/router/util/AbstractRoutingNetwork.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/AbstractRoutingNetwork.java similarity index 100% rename from matsim/src/main/java/org/matsim/core/router/util/AbstractRoutingNetwork.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/AbstractRoutingNetwork.java diff --git a/matsim/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkFactory.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkFactory.java similarity index 99% rename from matsim/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkFactory.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkFactory.java index 954f6ad941f..693353a9e13 100644 --- a/matsim/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkFactory.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkFactory.java @@ -26,7 +26,7 @@ import org.matsim.api.core.v01.network.Node; public abstract class AbstractRoutingNetworkFactory implements RoutingNetworkFactory { - + @Override public Link createLink(final Id id, final Node fromNode, final Node toNode) { throw new RuntimeException("Not supported operation!"); @@ -36,4 +36,4 @@ public Link createLink(final Id id, final Node fromNode, final Node toNode public RoutingNetworkNode createNode(final Id id, final Coord coord) { throw new RuntimeException("Not supported operation!"); } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkLink.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkLink.java similarity index 100% rename from matsim/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkLink.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkLink.java diff --git a/matsim/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkNode.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkNode.java similarity index 100% rename from matsim/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkNode.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/AbstractRoutingNetworkNode.java diff --git a/matsim/src/main/java/org/matsim/core/router/util/ArrayRoutingNetwork.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/ArrayRoutingNetwork.java similarity index 100% rename from matsim/src/main/java/org/matsim/core/router/util/ArrayRoutingNetwork.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/ArrayRoutingNetwork.java diff --git a/matsim/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkFactory.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkFactory.java similarity index 98% rename from matsim/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkFactory.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkFactory.java index 5954a97430c..314211e9369 100644 --- a/matsim/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkFactory.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkFactory.java @@ -29,12 +29,11 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; -import org.matsim.core.network.LinkFactory; public class ArrayRoutingNetworkFactory extends AbstractRoutingNetworkFactory { - + private final static Logger log = LogManager.getLogger(ArrayRoutingNetworkFactory.class); - + private int nodeArrayIndexCounter; private int linkArrayIndexCounter; @@ -42,9 +41,9 @@ public class ArrayRoutingNetworkFactory extends AbstractRoutingNetworkFactory { public synchronized ArrayRoutingNetwork createRoutingNetwork(final Network network) { this.nodeArrayIndexCounter = 0; this.linkArrayIndexCounter = 0; - + ArrayRoutingNetwork routingNetwork = new ArrayRoutingNetwork(network); - + for (Node node : network.getNodes().values()) { RoutingNetworkNode routingNode = createRoutingNetworkNode(node, node.getOutLinks().size()); routingNetwork.addNode(routingNode); @@ -56,22 +55,22 @@ public synchronized ArrayRoutingNetwork createRoutingNetwork(final Network netwo RoutingNetworkLink dijkstraLink = createRoutingNetworkLink(link, fromNode, toNode); routingLinks.put(dijkstraLink.getId(), dijkstraLink); } - + for (Node node : network.getNodes().values()) { RoutingNetworkLink[] outLinks = new RoutingNetworkLink[node.getOutLinks().size()]; - + int i = 0; for (Link outLink : node.getOutLinks().values()) { outLinks[i] = routingLinks.remove(outLink.getId()); i++; } - + RoutingNetworkNode dijkstraNode = routingNetwork.getNodes().get(node.getId()); dijkstraNode.setOutLinksArray(outLinks); } - + if (routingLinks.size() > 0) log.warn("Not all links have been use in the ArrayRoutingNetwork - check connectivity of input network!"); - + return routingNetwork; } @@ -84,4 +83,4 @@ public ArrayRoutingNetworkNode createRoutingNetworkNode(final Node node, final i public ArrayRoutingNetworkLink createRoutingNetworkLink(final Link link, final RoutingNetworkNode fromNode, final RoutingNetworkNode toNode) { return new ArrayRoutingNetworkLink(link, fromNode, toNode, this.linkArrayIndexCounter++); } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkLink.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkLink.java similarity index 100% rename from matsim/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkLink.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkLink.java diff --git a/matsim/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkNode.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkNode.java similarity index 100% rename from matsim/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkNode.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/ArrayRoutingNetworkNode.java diff --git a/matsim/src/main/java/org/matsim/core/router/util/RoutingNetwork.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetwork.java similarity index 92% rename from matsim/src/main/java/org/matsim/core/router/util/RoutingNetwork.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetwork.java index 833d407c7f7..61a7fac40aa 100644 --- a/matsim/src/main/java/org/matsim/core/router/util/RoutingNetwork.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetwork.java @@ -25,21 +25,19 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; +import org.matsim.core.router.util.RoutingNetworkNode; /** * A network that is used by FastDijkstra, FastAStarEuclidean and FastAStarLandmarks. * Instead of storing the node data in a map, the data is attached directly to the nodes * which is faster but also consumes more memory. - * - * @see org.matsim.core.router.FastDijkstra - * @see org.matsim.core.router.FastAStarEuclidean - * @see org.matsim.core.router.FastAStarLandmarks + * * @author cdobler */ public interface RoutingNetwork extends Network { - + public void initialize(); - + @Override public Map, RoutingNetworkNode> getNodes(); -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/router/util/RoutingNetworkFactory.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetworkFactory.java similarity index 99% rename from matsim/src/main/java/org/matsim/core/router/util/RoutingNetworkFactory.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetworkFactory.java index 2eeaf5cb661..604f4e91f72 100644 --- a/matsim/src/main/java/org/matsim/core/router/util/RoutingNetworkFactory.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetworkFactory.java @@ -26,10 +26,10 @@ import org.matsim.api.core.v01.network.Node; public interface RoutingNetworkFactory extends NetworkFactory { - + public RoutingNetwork createRoutingNetwork(final Network network); - + public RoutingNetworkNode createRoutingNetworkNode(final Node node, final int numOutLinks); - + public RoutingNetworkLink createRoutingNetworkLink(final Link link, final RoutingNetworkNode fromNode, final RoutingNetworkNode toNode); } diff --git a/matsim/src/main/java/org/matsim/core/router/util/RoutingNetworkLink.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetworkLink.java similarity index 98% rename from matsim/src/main/java/org/matsim/core/router/util/RoutingNetworkLink.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetworkLink.java index 48c7eabad08..ce6a058ae91 100644 --- a/matsim/src/main/java/org/matsim/core/router/util/RoutingNetworkLink.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetworkLink.java @@ -28,17 +28,17 @@ public interface RoutingNetworkLink extends Link { // routingNetworkLink.getLink().getFreeSpeed() ; // but NOT // routingNetworkLink.getFreeSpeed() ; - // The current approach seems to be doing both. Why did it add the second way of doing things? + // The current approach seems to be doing both. Why did it add the second way of doing things? // (I can imagine that this came from retrofitting, but a design choice explanation would still be helpful.) kai, may'17 public Link getLink(); - + @Override public Id getId(); - + @Override public RoutingNetworkNode getFromNode(); - + @Override public RoutingNetworkNode getToNode(); -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/router/util/RoutingNetworkNode.java b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetworkNode.java similarity index 99% rename from matsim/src/main/java/org/matsim/core/router/util/RoutingNetworkNode.java rename to contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetworkNode.java index 298e3cfea88..a62e49e3554 100644 --- a/matsim/src/main/java/org/matsim/core/router/util/RoutingNetworkNode.java +++ b/contribs/locationchoice/src/main/java/org/matsim/core/router/util/RoutingNetworkNode.java @@ -24,14 +24,14 @@ import org.matsim.core.router.util.PreProcessDijkstra.DeadEndData; public interface RoutingNetworkNode extends Node { - + public Node getNode(); public void setOutLinksArray(RoutingNetworkLink[] outLinks); - + public RoutingNetworkLink[] getOutLinksArray(); public void setDeadEndData(DeadEndData deadEndData); - + public DeadEndData getDeadEndData(); -} \ No newline at end of file +} diff --git a/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/Initializer.java b/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/Initializer.java index 9f640aafaaf..cf53eb647bd 100644 --- a/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/Initializer.java +++ b/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/Initializer.java @@ -51,10 +51,10 @@ public void init(MatsimTestUtils utils) { preparePlans(scenario); this.controler = new Controler(scenario); - this.controler.getConfig().controler().setCreateGraphs(false); - this.controler.getConfig().controler().setWriteEventsInterval(0); // disables events-writing + this.controler.getConfig().controller().setCreateGraphs(false); + this.controler.getConfig().controller().setWriteEventsInterval(0); // disables events-writing this.controler.getConfig() - .controler() + .controller() .setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); this.controler.run(); } @@ -74,7 +74,7 @@ private static void preparePlans(Scenario scenario) { .forEach(planElement -> ((Leg)planElement).setRoute(null)); final FreespeedTravelTimeAndDisutility timeCostCalc = new FreespeedTravelTimeAndDisutility( - scenario.getConfig().planCalcScore()); + scenario.getConfig().scoring()); PlanAlgorithm router = new PlanRouter(new TripRouterFactoryBuilderWithDefaults().build(scenario).get(), TimeInterpretation.create(scenario.getConfig())); PersonPrepareForSim pp4s = new PersonPrepareForSim(router, scenario); scenario.getPopulation().getPersons().values().forEach(pp4s::run); diff --git a/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/LocationChoiceIT.java b/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/LocationChoiceIT.java index a7841c8799f..82fbd9e7a0e 100644 --- a/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/LocationChoiceIT.java +++ b/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/LocationChoiceIT.java @@ -44,10 +44,10 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.RoutingConfigGroup; 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; @@ -124,7 +124,7 @@ public PlanStrategy get() { // (this is now only necessary since the config for all three tests sets MyLocationChoice instead of LocationChoice. Probably // should pull the best response test away from the other (old) test. kai, feb'13 - controler.getConfig().controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); + controler.getConfig().controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); controler.run(); // test that everything worked as expected @@ -137,7 +137,7 @@ public PlanStrategy get() { assertEquals("number of plans in person.", 2, person.getPlans().size()); Plan newPlan = person.getSelectedPlan(); Activity newWork = (Activity) newPlan.getPlanElements().get(2); - if (!config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if (!config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { newWork = (Activity) newPlan.getPlanElements().get(6); } assertNotNull( newWork ) ; @@ -188,9 +188,9 @@ static Config localCreateConfig( String configFileName ) { Config config = ConfigUtils.loadConfig(configFileName, new DestinationChoiceConfigGroup() , new FrozenTastesConfigGroup() ) ; config.global().setNumberOfThreads(0); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(1); - config.controler().setMobsim("qsim"); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(1); + config.controller().setMobsim("qsim"); config.qsim().setSnapshotStyle(QSimConfigGroup.SnapshotStyle.queue) ; final DestinationChoiceConfigGroup dccg = ConfigUtils.addOrGetModule(config, DestinationChoiceConfigGroup.class ) ; @@ -199,18 +199,18 @@ static Config localCreateConfig( String configFileName ) { ActivityParams home = new ActivityParams("home"); home.setTypicalDuration(12*60*60); - config.planCalcScore().addActivityParams(home); + config.scoring().addActivityParams(home); ActivityParams work = new ActivityParams("work"); work.setTypicalDuration(12*60*60); - config.planCalcScore().addActivityParams(work); + config.scoring().addActivityParams(work); ActivityParams shop = new ActivityParams("shop"); shop.setTypicalDuration(1.*60*60); - config.planCalcScore().addActivityParams(shop); + config.scoring().addActivityParams(shop); final StrategySettings strategySettings = new StrategySettings(Id.create("1", StrategySettings.class)); strategySettings.setStrategyName("MyLocationChoice"); strategySettings.setWeight(1.0); - config.strategy().addStrategySettings(strategySettings); + config.replanning().addStrategySettings(strategySettings); ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class).setEffectiveLaneWidth(1.) ; config.qsim().setLinkWidthForVis((float)1.) ; diff --git a/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyIT.java b/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyIT.java index 9b85f7ec218..133a45fc886 100644 --- a/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyIT.java +++ b/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/frozenepsilons/BestReplyIT.java @@ -24,14 +24,14 @@ public void testRunControler() { IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("chessboard"), "config.xml"), new FrozenTastesConfigGroup() ); - + // override or add some material: ConfigUtils.loadConfig(config, utils.getPackageInputDirectory() + "/config.xml"); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); - - + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + + Scenario scenario = ScenarioUtils.loadScenario(config); RunLocationChoiceBestResponse.run(scenario ); } diff --git a/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/frozenepsilons/FrozenEpsilonLocaChoiceIT.java b/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/frozenepsilons/FrozenEpsilonLocaChoiceIT.java index 92ccc17d567..08af97c8a0c 100644 --- a/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/frozenepsilons/FrozenEpsilonLocaChoiceIT.java +++ b/contribs/locationchoice/src/test/java/org/matsim/contrib/locationchoice/frozenepsilons/FrozenEpsilonLocaChoiceIT.java @@ -5,7 +5,7 @@ import static org.matsim.contrib.locationchoice.frozenepsilons.FrozenTastesConfigGroup.Algotype; import static org.matsim.contrib.locationchoice.frozenepsilons.FrozenTastesConfigGroup.Algotype.bestResponse; import static org.matsim.contrib.locationchoice.frozenepsilons.FrozenTastesConfigGroup.ApproximationLevel; -import static org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import static org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import java.util.HashSet; import java.util.List; @@ -33,8 +33,8 @@ import org.matsim.contrib.analysis.kai.KaiAnalysisListener; 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.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; @@ -95,8 +95,8 @@ public void testLocationChoiceJan2013() { // CONFIG: final Config config = localCreateConfig( this.utils.getPackageInputDirectory() + "../config2.xml"); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); { FrozenTastesConfigGroup dccg = ConfigUtils.addOrGetModule( config, FrozenTastesConfigGroup.class ); @@ -107,7 +107,7 @@ public void testLocationChoiceJan2013() { dccg.setRandomSeed( 4711 ); dccg.setTravelTimeApproximationLevel( ApproximationLevel.localRouting ); } - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setRoutingRandomness(0.); // SCENARIO: final Scenario scenario = ScenarioUtils.createScenario(config ); @@ -157,7 +157,7 @@ public void install() { Plan newPlan = person.getSelectedPlan(); System.err.println( " newPlan: " + newPlan ) ; Activity newWork = (Activity) newPlan.getPlanElements().get(2 ); - if ( !config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { newWork = (Activity) newPlan.getPlanElements().get(6); } System.err.println( " newWork: " + newWork ) ; @@ -173,7 +173,7 @@ public void testLocationChoiceFeb2013NegativeScores() { // config: final Config config = localCreateConfig( utils.getPackageInputDirectory() + "../config2.xml"); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); final FrozenTastesConfigGroup dccg = ConfigUtils.addOrGetModule(config, FrozenTastesConfigGroup.class ) ; @@ -201,7 +201,7 @@ public void testLocationChoiceFeb2013NegativeScores() { // CONTROL(L)ER: Controler controler = new Controler(scenario); - controler.getConfig().controler().setOverwriteFileSetting( OverwriteFileSetting.overwriteExistingFiles ); + controler.getConfig().controller().setOverwriteFileSetting( OverwriteFileSetting.overwriteExistingFiles ); // set scoring function DCScoringFunctionFactory scoringFunctionFactory = new DCScoringFunctionFactory(controler.getScenario(), lcContext); @@ -236,33 +236,33 @@ enum RunType { shortRun, medRun, longRun } Config config = ConfigUtils.createConfig() ; switch( runType ) { case shortRun: - config.controler().setLastIteration( 2 ); + config.controller().setLastIteration( 2 ); break; case medRun: - config.controler().setLastIteration( 100 ); + config.controller().setLastIteration( 100 ); break; case longRun: - config.controler().setLastIteration( 1000 ); + config.controller().setLastIteration( 1000 ); break; default: throw new RuntimeException( Gbl.NOT_IMPLEMENTED) ; } - config.controler().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); - config.planCalcScore().addActivityParams( new ActivityParams( "home" ).setTypicalDuration( 12.*3600. ) ); - config.planCalcScore().addActivityParams( new ActivityParams( "shop" ).setTypicalDuration( 2.*3600. ) ); + config.scoring().addActivityParams( new ActivityParams( "home" ).setTypicalDuration( 12.*3600. ) ); + config.scoring().addActivityParams( new ActivityParams( "shop" ).setTypicalDuration( 2.*3600. ) ); - config.strategy().addStrategySettings( new StrategySettings( ).setStrategyName( FrozenTastes.LOCATION_CHOICE_PLAN_STRATEGY ).setWeight( 1.0 ).setDisableAfter( 10 ) ); + config.replanning().addStrategySettings( new StrategySettings( ).setStrategyName( FrozenTastes.LOCATION_CHOICE_PLAN_STRATEGY ).setWeight( 1.0 ).setDisableAfter( 10 ) ); switch ( runType ){ case shortRun: break; case medRun: case longRun: - config.strategy().addStrategySettings( new StrategySettings().setStrategyName( FrozenTastes.LOCATION_CHOICE_PLAN_STRATEGY ).setWeight( 0.1 ) ); - config.strategy().addStrategySettings( new StrategySettings().setStrategyName( DefaultSelector.ChangeExpBeta ).setWeight( 1.0 ) ); - config.strategy().setFractionOfIterationsToDisableInnovation( 0.8 ); - config.planCalcScore().setFractionOfIterationsToStartScoreMSA( 0.8 ); + config.replanning().addStrategySettings( new StrategySettings().setStrategyName( FrozenTastes.LOCATION_CHOICE_PLAN_STRATEGY ).setWeight( 0.1 ) ); + config.replanning().addStrategySettings( new StrategySettings().setStrategyName( DefaultSelector.ChangeExpBeta ).setWeight( 1.0 ) ); + config.replanning().setFractionOfIterationsToDisableInnovation( 0.8 ); + config.scoring().setFractionOfIterationsToStartScoreMSA( 0.8 ); break ; default: throw new RuntimeException( Gbl.NOT_IMPLEMENTED ) ; @@ -358,7 +358,7 @@ enum RunType { shortRun, medRun, longRun } // CONTROL(L)ER: Controler controler = new Controler(scenario); - controler.getConfig().controler().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); + controler.getConfig().controller().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); FrozenTastes.configure( controler ); @@ -518,9 +518,9 @@ static Config localCreateConfig( String configFileName ) { Config config = ConfigUtils.loadConfig(configFileName, new FrozenTastesConfigGroup() ) ; config.global().setNumberOfThreads(0); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(1); - config.controler().setMobsim("qsim"); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(1); + config.controller().setMobsim("qsim"); config.qsim().setSnapshotStyle( QSimConfigGroup.SnapshotStyle.queue ) ; final FrozenTastesConfigGroup dccg = ConfigUtils.addOrGetModule(config, FrozenTastesConfigGroup.class ) ; @@ -529,18 +529,18 @@ static Config localCreateConfig( String configFileName ) { ActivityParams home = new ActivityParams("home"); home.setTypicalDuration(12*60*60); - config.planCalcScore().addActivityParams(home); + config.scoring().addActivityParams(home); ActivityParams work = new ActivityParams("work"); work.setTypicalDuration(12*60*60); - config.planCalcScore().addActivityParams(work); + config.scoring().addActivityParams(work); ActivityParams shop = new ActivityParams("shop"); shop.setTypicalDuration(1.*60*60); - config.planCalcScore().addActivityParams(shop); + config.scoring().addActivityParams(shop); final StrategySettings strategySettings = new StrategySettings(Id.create("1", StrategySettings.class )); strategySettings.setStrategyName("MyLocationChoice"); strategySettings.setWeight(1.0); - config.strategy().addStrategySettings(strategySettings); + config.replanning().addStrategySettings(strategySettings); ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class ).setEffectiveLaneWidth(1. ) ; config.qsim().setLinkWidthForVis((float)1.) ; diff --git a/contribs/locationchoice/src/test/java/org/matsim/core/router/BackwardFastMultiNodeTest.java b/contribs/locationchoice/src/test/java/org/matsim/core/router/BackwardFastMultiNodeTest.java index a2590bccf2b..844fdbe02ef 100644 --- a/contribs/locationchoice/src/test/java/org/matsim/core/router/BackwardFastMultiNodeTest.java +++ b/contribs/locationchoice/src/test/java/org/matsim/core/router/BackwardFastMultiNodeTest.java @@ -46,19 +46,19 @@ * @author cdobler */ public class BackwardFastMultiNodeTest { - + @Test public void testBackwardsFastMultiNodeDijkstra_OneToOne() { runTestBackwardsFastMultiNodeDijkstra_OneToOne(true); runTestBackwardsFastMultiNodeDijkstra_OneToOne(false); } - + private void runTestBackwardsFastMultiNodeDijkstra_OneToOne(boolean searchAllEndNodes) { - + Config config = ConfigUtils.createConfig(); - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setRoutingRandomness(0.); Scenario scenario = ScenarioUtils.createScenario(config); - + createNetwork(scenario); TravelTime travelTime = new FreeSpeedTravelTime(); @@ -66,59 +66,59 @@ private void runTestBackwardsFastMultiNodeDijkstra_OneToOne(boolean searchAllEnd config ).createTravelDisutility(travelTime ); BackwardFastMultiNodeDijkstra dijkstra = (BackwardFastMultiNodeDijkstra) new BackwardFastMultiNodeDijkstraFactory(searchAllEndNodes). createPathCalculator(scenario.getNetwork(), travelDisutility, travelTime); - + Node fromNode = scenario.getNetwork().getNodes().get(Id.create("n3", Node.class)); Node toNode = scenario.getNetwork().getNodes().get(Id.create("n0", Node.class)); - + /* * test calcLeastCostPath method */ Path path = dijkstra.calcLeastCostPath(fromNode, toNode, 3600.0, null, null); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation */ path = dijkstra.constructPath(fromNode, toNode, 3600.0); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); } - + /* * Search only cheapest to node. n5 should not be found. */ @Test public void testBackwardsFastMultiNodeDijkstra_OneToMany() { - + Config config = ConfigUtils.createConfig(); - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setRoutingRandomness(0.); Scenario scenario = ScenarioUtils.createScenario(config); - + createNetwork(scenario); TravelTime travelTime = new FreeSpeedTravelTime(); @@ -126,7 +126,7 @@ public void testBackwardsFastMultiNodeDijkstra_OneToMany() { config ).createTravelDisutility(travelTime ); BackwardFastMultiNodeDijkstra dijkstra = (BackwardFastMultiNodeDijkstra) new BackwardFastMultiNodeDijkstraFactory(false). createPathCalculator(scenario.getNetwork(), travelDisutility, travelTime); - + Node fromNode = scenario.getNetwork().getNodes().get(Id.create("n3", Node.class)); Node toNode1 = scenario.getNetwork().getNodes().get(Id.create("n0", Node.class)); Node toNode2 = scenario.getNetwork().getNodes().get(Id.create("n4", Node.class)); @@ -136,79 +136,79 @@ public void testBackwardsFastMultiNodeDijkstra_OneToMany() { toNodes.add(new InitialNode(toNode2, 0.0, 0.0)); toNodes.add(new InitialNode(toNode3, 0.0, 0.0)); Node toNode = dijkstra.createImaginaryNode(toNodes); - + /* * test calcLeastCostPath method */ Path path = dijkstra.calcLeastCostPath(fromNode, toNode, 3600.0, null, null); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode1 */ path = dijkstra.constructPath(fromNode, toNode1, 3600.0); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode2 */ path = dijkstra.constructPath(fromNode, toNode2, 3600.0); - + Assert.assertEquals(1.333, path.travelCost, 0.001); Assert.assertEquals(400.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n4", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l3", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode3 */ path = dijkstra.constructPath(fromNode, toNode3, 3600.0); - + Assert.assertNull(null); } - + @Test public void testBackwardsFastMultiNodeDijkstra_OneToMany_SearchAllNodes() { - + Config config = ConfigUtils.createConfig(); - config.plansCalcRoute().setRoutingRandomness(0.); + config.routing().setRoutingRandomness(0.); Scenario scenario = ScenarioUtils.createScenario(config); - + createNetwork(scenario); TravelTime travelTime = new FreeSpeedTravelTime(); @@ -216,7 +216,7 @@ public void testBackwardsFastMultiNodeDijkstra_OneToMany_SearchAllNodes() { config ).createTravelDisutility(travelTime ); BackwardFastMultiNodeDijkstra dijkstra = (BackwardFastMultiNodeDijkstra) new BackwardFastMultiNodeDijkstraFactory(true). createPathCalculator(scenario.getNetwork(), travelDisutility, travelTime); - + Node fromNode = scenario.getNetwork().getNodes().get(Id.create("n3", Node.class)); Node toNode1 = scenario.getNetwork().getNodes().get(Id.create("n0", Node.class)); Node toNode2 = scenario.getNetwork().getNodes().get(Id.create("n4", Node.class)); @@ -226,89 +226,89 @@ public void testBackwardsFastMultiNodeDijkstra_OneToMany_SearchAllNodes() { toNodes.add(new InitialNode(toNode2, 0.0, 0.0)); toNodes.add(new InitialNode(toNode3, 0.0, 0.0)); Node toNode = dijkstra.createImaginaryNode(toNodes); - + /* * test calcLeastCostPath method */ Path path = dijkstra.calcLeastCostPath(fromNode, toNode, 3600.0, null, null); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode1 */ path = dijkstra.constructPath(fromNode, toNode1, 3600.0); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode2 */ path = dijkstra.constructPath(fromNode, toNode2, 3600.0); - + Assert.assertEquals(1.333, path.travelCost, 0.001); Assert.assertEquals(400.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n4", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l3", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode3 */ path = dijkstra.constructPath(fromNode, toNode3, 3600.0); - + Assert.assertEquals(2.0, path.travelCost, 0.0); Assert.assertEquals(600.0, path.travelTime, 0.0); - + Assert.assertEquals(5, path.nodes.size()); Assert.assertEquals(Id.create("n5", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n4", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(3).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(4).getId()); - + Assert.assertEquals(4, path.links.size()); Assert.assertEquals(Id.create("l4", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l3", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(2).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(3).getId()); } - + /* * Network structure - * + * * n0---l0---n1---l1---n2---l2---n3 * | * | @@ -336,7 +336,7 @@ private void createNetwork(Scenario scenario) { Node n4 = scenario.getNetwork().getFactory().createNode(Id.create("n4", Node.class), new Coord(1000.0, y1)); double y = -4000.0; Node n5 = scenario.getNetwork().getFactory().createNode(Id.create("n5", Node.class), new Coord(1000.0, y)); - + /* * create links */ @@ -345,7 +345,7 @@ private void createNetwork(Scenario scenario) { Link l2 = scenario.getNetwork().getFactory().createLink(Id.create("l2", Link.class), n2, n3); Link l3 = scenario.getNetwork().getFactory().createLink(Id.create("l3", Link.class), n4, n1); Link l4 = scenario.getNetwork().getFactory().createLink(Id.create("l4", Link.class), n5, n4); - + /* * set link parameter */ @@ -354,13 +354,13 @@ private void createNetwork(Scenario scenario) { l2.setLength(1000.0); l3.setLength(2000.0); l4.setLength(2000.0); - + l0.setFreespeed(10.0); l1.setFreespeed(10.0); l2.setFreespeed(10.0); l3.setFreespeed(10.0); l4.setFreespeed(10.0); - + /* * add nodes to network */ @@ -370,7 +370,7 @@ private void createNetwork(Scenario scenario) { scenario.getNetwork().addNode(n3); scenario.getNetwork().addNode(n4); scenario.getNetwork().addNode(n5); - + /* * add links to network */ diff --git a/matsim/src/test/java/org/matsim/core/router/FastMultiNodeTest.java b/contribs/locationchoice/src/test/java/org/matsim/core/router/FastMultiNodeTest.java similarity index 98% rename from matsim/src/test/java/org/matsim/core/router/FastMultiNodeTest.java rename to contribs/locationchoice/src/test/java/org/matsim/core/router/FastMultiNodeTest.java index ad2af47c972..1dc5a2a4650 100644 --- a/matsim/src/test/java/org/matsim/core/router/FastMultiNodeTest.java +++ b/contribs/locationchoice/src/test/java/org/matsim/core/router/FastMultiNodeTest.java @@ -44,19 +44,19 @@ * Some more tests - but all of them assuming that there is only * a single from node as in the location choice use case. * For test using multiple from nodes look at MultiNodeDijkstraTest! - * + * * @author cdobler */ public class FastMultiNodeTest { - + @Test public void testFastMultiNodeDijkstra_OneToOne() { - + Config config = ConfigUtils.createConfig(); - config.plansCalcRoute().setRoutingRandomness( 0. ); + config.routing().setRoutingRandomness( 0. ); Scenario scenario = ScenarioUtils.createScenario(config); - + createNetwork(scenario); TravelTime travelTime = new FreeSpeedTravelTime(); @@ -64,57 +64,57 @@ public void testFastMultiNodeDijkstra_OneToOne() { config ).createTravelDisutility(travelTime ); FastMultiNodeDijkstra dijkstra = (FastMultiNodeDijkstra) new FastMultiNodeDijkstraFactory(). createPathCalculator(scenario.getNetwork(), travelDisutility, travelTime); - + Node fromNode = scenario.getNetwork().getNodes().get(Id.create("n0", Node.class)); Node toNode = scenario.getNetwork().getNodes().get(Id.create("n3", Node.class)); - + /* * test calcLeastCostPath method */ Path path = dijkstra.calcLeastCostPath(fromNode, toNode, 3600.0, null, null); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation */ path = dijkstra.constructPath(fromNode, toNode, 3600.0); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); } - + @Test public void testFastMultiNodeDijkstra_OneToMany() { - + Config config = ConfigUtils.createConfig(); - config.plansCalcRoute().setRoutingRandomness( 0. ); + config.routing().setRoutingRandomness( 0. ); Scenario scenario = ScenarioUtils.createScenario(config); - + createNetwork(scenario); TravelTime travelTime = new FreeSpeedTravelTime(); @@ -122,7 +122,7 @@ public void testFastMultiNodeDijkstra_OneToMany() { config ).createTravelDisutility(travelTime ); FastMultiNodeDijkstra dijkstra = (FastMultiNodeDijkstra) new FastMultiNodeDijkstraFactory(false). createPathCalculator(scenario.getNetwork(), travelDisutility, travelTime); - + Node fromNode = scenario.getNetwork().getNodes().get(Id.create("n0", Node.class)); Node toNode1 = scenario.getNetwork().getNodes().get(Id.create("n3", Node.class)); Node toNode2 = scenario.getNetwork().getNodes().get(Id.create("n4", Node.class)); @@ -132,80 +132,80 @@ public void testFastMultiNodeDijkstra_OneToMany() { toNodes.add(new InitialNode(toNode2, 0.0, 0.0)); toNodes.add(new InitialNode(toNode3, 0.0, 0.0)); Node toNode = dijkstra.createImaginaryNode(toNodes); - + /* * test calcLeastCostPath method */ Path path = dijkstra.calcLeastCostPath(fromNode, toNode, 3600.0, null, null); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode1 */ path = dijkstra.constructPath(fromNode, toNode1, 3600.0); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode2 */ path = dijkstra.constructPath(fromNode, toNode2, 3600.0); - + Assert.assertEquals(1.333, path.travelCost, 0.001); Assert.assertEquals(400.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n4", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l3", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode3 */ path = dijkstra.constructPath(fromNode, toNode3, 3600.0); - + Assert.assertNull(path); } - + @Test public void testFastMultiNodeDijkstra_OneToMany_SearchAllNodes() { - + Config config = ConfigUtils.createConfig(); - config.plansCalcRoute().setRoutingRandomness( 0. ); + config.routing().setRoutingRandomness( 0. ); Scenario scenario = ScenarioUtils.createScenario(config); - + createNetwork(scenario); TravelTime travelTime = new FreeSpeedTravelTime(); @@ -213,7 +213,7 @@ public void testFastMultiNodeDijkstra_OneToMany_SearchAllNodes() { config ).createTravelDisutility(travelTime ); FastMultiNodeDijkstra dijkstra = (FastMultiNodeDijkstra) new FastMultiNodeDijkstraFactory(true). createPathCalculator(scenario.getNetwork(), travelDisutility, travelTime); - + Node fromNode = scenario.getNetwork().getNodes().get(Id.create("n0", Node.class)); Node toNode1 = scenario.getNetwork().getNodes().get(Id.create("n3", Node.class)); Node toNode2 = scenario.getNetwork().getNodes().get(Id.create("n4", Node.class)); @@ -223,89 +223,89 @@ public void testFastMultiNodeDijkstra_OneToMany_SearchAllNodes() { toNodes.add(new InitialNode(toNode2, 0.0, 0.0)); toNodes.add(new InitialNode(toNode3, 0.0, 0.0)); Node toNode = dijkstra.createImaginaryNode(toNodes); - + /* * test calcLeastCostPath method */ Path path = dijkstra.calcLeastCostPath(fromNode, toNode, 3600.0, null, null); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode1 */ path = dijkstra.constructPath(fromNode, toNode1, 3600.0); - + Assert.assertEquals(1.0, path.travelCost, 0.0); Assert.assertEquals(300.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n3", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l2", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode2 */ path = dijkstra.constructPath(fromNode, toNode2, 3600.0); - + Assert.assertEquals(1.333, path.travelCost, 0.001); Assert.assertEquals(400.0, path.travelTime, 0.0); - + Assert.assertEquals(4, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n4", Node.class), path.nodes.get(3).getId()); - + Assert.assertEquals(3, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l3", Link.class), path.links.get(2).getId()); - + /* * test constructPath method which uses data from the previous routing operation - toNode3 */ path = dijkstra.constructPath(fromNode, toNode3, 3600.0); - + Assert.assertEquals(2.0, path.travelCost, 0.0); Assert.assertEquals(600.0, path.travelTime, 0.0); - + Assert.assertEquals(5, path.nodes.size()); Assert.assertEquals(Id.create("n0", Node.class), path.nodes.get(0).getId()); Assert.assertEquals(Id.create("n1", Node.class), path.nodes.get(1).getId()); Assert.assertEquals(Id.create("n2", Node.class), path.nodes.get(2).getId()); Assert.assertEquals(Id.create("n4", Node.class), path.nodes.get(3).getId()); Assert.assertEquals(Id.create("n5", Node.class), path.nodes.get(4).getId()); - + Assert.assertEquals(4, path.links.size()); Assert.assertEquals(Id.create("l0", Link.class), path.links.get(0).getId()); Assert.assertEquals(Id.create("l1", Link.class), path.links.get(1).getId()); Assert.assertEquals(Id.create("l3", Link.class), path.links.get(2).getId()); Assert.assertEquals(Id.create("l4", Link.class), path.links.get(3).getId()); } - + /* * Network structure - * + * * n0---l0---n1---l1---n2---l2---n3 * | * | @@ -333,7 +333,7 @@ private static void createNetwork( Scenario scenario ) { Node n4 = scenario.getNetwork().getFactory().createNode(Id.create("n4", Node.class), new Coord(2000.0, y1)); double y = -4000.0; Node n5 = scenario.getNetwork().getFactory().createNode(Id.create("n5", Node.class), new Coord(2000.0, y)); - + /* * create links */ @@ -342,7 +342,7 @@ private static void createNetwork( Scenario scenario ) { Link l2 = scenario.getNetwork().getFactory().createLink(Id.create("l2", Link.class), n2, n3); Link l3 = scenario.getNetwork().getFactory().createLink(Id.create("l3", Link.class), n2, n4); Link l4 = scenario.getNetwork().getFactory().createLink(Id.create("l4", Link.class), n4, n5); - + /* * set link parameter */ @@ -351,13 +351,13 @@ private static void createNetwork( Scenario scenario ) { l2.setLength(1000.0); l3.setLength(2000.0); l4.setLength(2000.0); - + l0.setFreespeed(10.0); l1.setFreespeed(10.0); l2.setFreespeed(10.0); l3.setFreespeed(10.0); l4.setFreespeed(10.0); - + /* * add nodes to network */ @@ -367,7 +367,7 @@ private static void createNetwork( Scenario scenario ) { scenario.getNetwork().addNode(n3); scenario.getNetwork().addNode(n4); scenario.getNetwork().addNode(n5); - + /* * add links to network */ diff --git a/matsim/src/test/java/org/matsim/core/router/MultiNodeDijkstraTest.java b/contribs/locationchoice/src/test/java/org/matsim/core/router/MultiNodeDijkstraTest.java similarity index 100% rename from matsim/src/test/java/org/matsim/core/router/MultiNodeDijkstraTest.java rename to contribs/locationchoice/src/test/java/org/matsim/core/router/MultiNodeDijkstraTest.java diff --git a/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/config2.xml b/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/config2.xml index 697dacbe945..63d03a5ccfa 100644 --- a/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/config2.xml +++ b/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/config2.xml @@ -10,7 +10,6 @@ - diff --git a/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/facilityload/config.xml b/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/facilityload/config.xml index 7a137c6a982..bfa8a03c984 100644 --- a/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/facilityload/config.xml +++ b/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/facilityload/config.xml @@ -7,13 +7,12 @@ - + - - - + + @@ -21,7 +20,7 @@ - + @@ -31,12 +30,12 @@ - + - - + + @@ -63,5 +62,5 @@ - + diff --git a/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/timegeography/config.xml b/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/timegeography/config.xml index 3c2fbac487d..e75b74bf2bf 100644 --- a/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/timegeography/config.xml +++ b/contribs/locationchoice/test/input/org/matsim/contrib/locationchoice/timegeography/config.xml @@ -10,10 +10,9 @@ - - + @@ -21,7 +20,7 @@ - + @@ -32,12 +31,12 @@ - + - - + + @@ -94,5 +93,5 @@ - + diff --git a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/MatrixBasedPtModule.java b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/MatrixBasedPtModule.java index 41366c39562..a4cedbff4cc 100644 --- a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/MatrixBasedPtModule.java +++ b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/MatrixBasedPtModule.java @@ -3,7 +3,7 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Network; import org.matsim.contrib.matrixbasedptrouter.utils.BoundingBox; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.AbstractModule; import com.google.inject.Provides; @@ -18,9 +18,9 @@ public void install() { } addRoutingModuleBinding(TransportMode.pt).to(MatrixBasedPtRoutingModule.class); } - + @Provides - PtMatrix createPtMatrix(PlansCalcRouteConfigGroup plansCalcRoute, MatrixBasedPtRouterConfigGroup ippcm, Network network) { + PtMatrix createPtMatrix(RoutingConfigGroup plansCalcRoute, MatrixBasedPtRouterConfigGroup ippcm, Network network) { return PtMatrix.createPtMatrix(plansCalcRoute, BoundingBox.createBoundingBox(network), ippcm); } -} \ No newline at end of file +} diff --git a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/PtMatrix.java b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/PtMatrix.java index d55741d5606..56d9a6dc6c4 100644 --- a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/PtMatrix.java +++ b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/PtMatrix.java @@ -35,8 +35,8 @@ import org.matsim.api.core.v01.network.Node; import org.matsim.api.core.v01.population.Person; import org.matsim.contrib.matrixbasedptrouter.utils.BoundingBox; -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.util.LeastCostPathCalculator; import org.matsim.core.utils.collections.QuadTree; import org.matsim.core.utils.geometry.CoordUtils; @@ -49,7 +49,7 @@ * Calculates travel times and distances from Coord to Coord based on a file containing transit stops with coordinates, * and, optionally, two files containing travel times and distances between each pair of stops. If files for travel times and distances are not provided, * they are calculated based on the teleportedModeSpeed of the pt mode, and the beelineDistanceFactor. - * + * * @author thomas */ public final class PtMatrix { @@ -60,20 +60,20 @@ public final class PtMatrix { /** * Creates an instance of this class. The config group contains the input file names, and whether speed/distance matrices are provided or not. * Speed and beeline distance factors are taken from the router configuration. - * - * A bounding box must be provided, which is used to filter the transit stop file while reading it. It is mandatory. If you just want to read the file, + * + * A bounding box must be provided, which is used to filter the transit stop file while reading it. It is mandatory. If you just want to read the file, * take the bounding box of your study area. - * + * * The transit stop file must always be provided, although it technically should not be necessary when you provide - * distance and speed matrices. It seems to be used only to give out warnings if transit stops are encountered which are not in the + * distance and speed matrices. It seems to be used only to give out warnings if transit stops are encountered which are not in the * transit stop file. - * + * * The calculated access/egress times are used without beeline distance correction, even though the pt travel times and distances are. - * - * Even though the parameters are taken from the teleportation router config, the teleportation router is not actually used to calculate + * + * Even though the parameters are taken from the teleportation router config, the teleportation router is not actually used to calculate * times and distances. I think this would be the more correct thing to do. */ - public static PtMatrix createPtMatrix(PlansCalcRouteConfigGroup plansCalcRoute, BoundingBox bb, MatrixBasedPtRouterConfigGroup ippcm) { + public static PtMatrix createPtMatrix(RoutingConfigGroup plansCalcRoute, BoundingBox bb, MatrixBasedPtRouterConfigGroup ippcm) { String ptStopInputFile = ippcm.getPtStopsInputFile(); QuadTree ptStops = FileUtils.readPtStops(ptStopInputFile, bb); @@ -138,26 +138,26 @@ public static PtMatrix createPtMatrix(PlansCalcRouteConfigGroup plansCalcRoute, private final QuadTree ptStops; private final double meterPerSecWalkSpeed; - private PtMatrix(PlansCalcRouteConfigGroup plansCalcRoute, QuadTree ptStops, Matrix originDestinationTravelTimeMatrix, Matrix originDestinationTravelDistanceMatrix){ + private PtMatrix(RoutingConfigGroup plansCalcRoute, QuadTree ptStops, Matrix originDestinationTravelTimeMatrix, Matrix originDestinationTravelDistanceMatrix){ this.meterPerSecWalkSpeed = plansCalcRoute.getTeleportedModeSpeeds().get(TransportMode.walk) ; - this.ptStops = ptStops; + this.ptStops = ptStops; this.originDestinationTravelTimeMatrix = originDestinationTravelTimeMatrix; this.originDestinationTravelDistanceMatrix = originDestinationTravelDistanceMatrix; } /** * total travel times (origin location > pt > destination location) in seconds. the travel times are composed as follows: - * + * * (O)-------(PT)===========(PT)--------(D) - * + * * O = origin location * D = destination location - * PT= next pt station - * + * PT= next pt station + * * total travel times = walk travel time from origin O to next pt stop + * pt travel time + * walk travel time from destination pt stop to destination D - * + * * @param fromFacilityCoord * @param toFacilityCoord * @return @@ -178,12 +178,12 @@ public double getTotalTravelTime_seconds(Coord fromFacilityCoord, Coord toFacili * returns the total walk travel times in seconds including * - walk travel time from given coordinate to next pt stop * - walk travel time from destination pt stop to given destination coordinate - * + * * @param fromFacilityCoord * @param toFacilityCoord * @return */ - public double getTotalWalkTravelTime_seconds(Coord fromFacilityCoord, Coord toFacilityCoord){ + public double getTotalWalkTravelTime_seconds(Coord fromFacilityCoord, Coord toFacilityCoord){ PtStop fromPtStop = this.ptStops.getClosest(fromFacilityCoord.getX(), fromFacilityCoord.getY()); PtStop toPtStop = this.ptStops.getClosest(toFacilityCoord.getX(), toFacilityCoord.getY()); @@ -219,17 +219,17 @@ public double getPtTravelTime_seconds(Coord fromFacilityCoord, Coord toFacilityC /** * total travel distance (origin location > pt > destination location) in seconds. the travel distances are composed as follows: - * + * * (O)-------(PT)===========(PT)--------(D) - * + * * O = origin location * D = destination location - * PT= next pt station - * + * PT= next pt station + * * total travel distance = walk travel distance from origin O to next pt stop + * pt travel distance + * walk travel distance from destination pt stop to destination D - * + * * travel distances in meter * @param fromFacilityCoord * @param toFacilityCoord @@ -238,7 +238,7 @@ public double getPtTravelTime_seconds(Coord fromFacilityCoord, Coord toFacilityC public double getTotalTravelDistance_meter(Coord fromFacilityCoord, Coord toFacilityCoord){ double totalWalkTravelDistance = getTotalWalkTravelDistance_meter(fromFacilityCoord, toFacilityCoord); - double ptTravelDistance = getPtTravelDistance_meter(fromFacilityCoord, toFacilityCoord); + double ptTravelDistance = getPtTravelDistance_meter(fromFacilityCoord, toFacilityCoord); double totalTravelDistance = totalWalkTravelDistance + ptTravelDistance; return totalTravelDistance; @@ -288,12 +288,12 @@ private static Map, PtStop> convertQuadTree2HashMap(QuadTree return ptStopHashMap; } - public LeastCostPathCalculator asPathCalculator(PlanCalcScoreConfigGroup planCalcScoreConfigGroup) { - final double betaWalkTT = planCalcScoreConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - planCalcScoreConfigGroup.getPerforming_utils_hr(); - final double betaWalkTD = planCalcScoreConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfDistance(); - final double betaPtTT = planCalcScoreConfigGroup.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() - planCalcScoreConfigGroup.getPerforming_utils_hr(); - final double betaPtTD = planCalcScoreConfigGroup.getMarginalUtilityOfMoney() * planCalcScoreConfigGroup.getModes().get(TransportMode.pt).getMonetaryDistanceRate(); - final double constPt = planCalcScoreConfigGroup.getModes().get(TransportMode.pt).getConstant(); + public LeastCostPathCalculator asPathCalculator(ScoringConfigGroup scoringConfigGroup) { + final double betaWalkTT = scoringConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - scoringConfigGroup.getPerforming_utils_hr(); + final double betaWalkTD = scoringConfigGroup.getModes().get(TransportMode.walk).getMarginalUtilityOfDistance(); + final double betaPtTT = scoringConfigGroup.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() - scoringConfigGroup.getPerforming_utils_hr(); + final double betaPtTD = scoringConfigGroup.getMarginalUtilityOfMoney() * scoringConfigGroup.getModes().get(TransportMode.pt).getMonetaryDistanceRate(); + final double constPt = scoringConfigGroup.getModes().get(TransportMode.pt).getConstant(); return new LeastCostPathCalculator() { @Override diff --git a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/example/RunMatrixBasedPTRouterExample.java b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/example/RunMatrixBasedPTRouterExample.java index 858298e4d4c..a26532a5c69 100644 --- a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/example/RunMatrixBasedPTRouterExample.java +++ b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/example/RunMatrixBasedPTRouterExample.java @@ -19,16 +19,11 @@ package org.matsim.contrib.matrixbasedptrouter.example; -import org.matsim.api.core.v01.Scenario; import org.matsim.contrib.matrixbasedptrouter.MatrixBasedPtModule; import org.matsim.contrib.matrixbasedptrouter.MatrixBasedPtRouterConfigGroup; -import org.matsim.contrib.matrixbasedptrouter.PtMatrix; -import org.matsim.contrib.matrixbasedptrouter.utils.BoundingBox; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; import org.matsim.core.controler.Controler; -import org.matsim.core.scenario.ScenarioUtils; /** * sets up a Matsim Scenario using example matrix based pt routing data @@ -46,7 +41,7 @@ public static void main(String[] args) //load config - check the config file for required PT Matrix input file data String path = "src/main/resources/example/"; Config config = ConfigUtils.loadConfig(path+"example_config.xml", new MatrixBasedPtRouterConfigGroup()); - + Controler controler = new Controler(config); controler.addOverridingModule(new MatrixBasedPtModule()); controler.run(); diff --git a/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/MatrixBasedPtRouterIT.java b/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/MatrixBasedPtRouterIT.java index a7d4aaf5ddd..2e10edddfa8 100644 --- a/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/MatrixBasedPtRouterIT.java +++ b/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/MatrixBasedPtRouterIT.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.matrixbasedptrouter; @@ -65,19 +65,19 @@ public class MatrixBasedPtRouterIT { */ @Test public void testIntegration() throws IOException { - + String path = utils.getOutputDirectory(); - - - + + + //a dummy network is created and written into the output directory Network network = CreateTestNetwork.createTestNetwork(); new NetworkWriter(network).write(path+"network.xml"); - + //a dummy population of one person is created and written into the output directory Population population = CreateTestPopulation.createTestPtPopulation(1, new Coord((double) 0, (double) 0), new Coord((double) 0, (double) 200)); new PopulationWriter(population, network).write(path+"plans.xml"); - + //dummy csv files for pt stops, travel times and travel distances fitting into the dummy network are created String stopsLocation = CreateTestNetwork.createTestPtStationCSVFile(folder.newFile("ptStops.csv")); String timesLocation = CreateTestNetwork.createTestPtTravelTimesAndDistancesCSVFile(folder.newFile("ptTravelInfo.csv")); @@ -95,40 +95,40 @@ public void testIntegration() throws IOException { config.addModule(matrixBasedPtRouterConfigGroup) ; - + //modification of the config according to what's needed - config.controler().setMobsim("qsim"); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(0); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setMobsim("qsim"); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(0); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); config.network().setInputFile(path+"network.xml"); config.plans().setInputFile(path+"plans.xml"); //add home and work activity to plansCalcScoreConfigGroup - config.planCalcScore().addParam("activityType_0", "home"); - config.planCalcScore().addParam("activityTypicalDuration_0", "43200"); - config.planCalcScore().addParam("activityType_1", "work"); - config.planCalcScore().addParam("activityTypicalDuration_1", "28800"); + config.scoring().addParam("activityType_0", "home"); + config.scoring().addParam("activityTypicalDuration_0", "43200"); + config.scoring().addParam("activityType_1", "work"); + config.scoring().addParam("activityTypicalDuration_1", "28800"); Scenario scenario = ScenarioUtils.loadScenario(config); BoundingBox nbb = BoundingBox.createBoundingBox(network); - final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.plansCalcRoute(), nbb, ConfigUtils.addOrGetModule(config, MatrixBasedPtRouterConfigGroup.GROUP_NAME, MatrixBasedPtRouterConfigGroup.class)); + final PtMatrix ptMatrix = PtMatrix.createPtMatrix(config.routing(), nbb, ConfigUtils.addOrGetModule(config, MatrixBasedPtRouterConfigGroup.GROUP_NAME, MatrixBasedPtRouterConfigGroup.class)); Controler controler = new Controler(scenario) ; controler.addOverridingModule(new MatrixBasedPtModule()); controler.run(); - + // compute the travel time from home to work activity double ttime = ptMatrix.getTotalTravelTime_seconds(new Coord((double) 0, (double) 0), new Coord((double) 0, (double) 200)); // get the actual travel time from the person's plan Person person = controler.getScenario().getPopulation().getPersons().values().iterator().next(); double actualTtime = ((Leg)person.getSelectedPlan().getPlanElements().get(1)).getTravelTime().seconds(); - + //compare computed and actual travel time Assert.assertEquals(ttime, actualTtime, 0); - + } } diff --git a/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/PtMatrixTest.java b/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/PtMatrixTest.java index aeebf4c30e7..0b029d1f749 100644 --- a/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/PtMatrixTest.java +++ b/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/PtMatrixTest.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.matrixbasedptrouter; @@ -46,30 +46,30 @@ /** * This class tests the pt simulation of MATSim for a simple network created with CreateTestNetwork.java. * It checks the values of pt distances and times from the pt matrix for this network. - * + * * MATSim always calculates the total pt time and distance respectively between origin and destination facility as a sum of the following three values: * 1. the walk time and distance respectively from the origin facility to the nearest pt stop, * 2. the pt time and distance respectively between this origin pt stop and the destination pt stop, which is the nearest one from the destination facility, * 3. the walk time and distance respectively from this destination pt stop to the destination facility. - * + * * MATSim offers to possibilities to use pt simulation, which differ in the information you have to provide: * 1. The calculation of pt times and distances only from the information about the coordinates of pt stops and facilities. * For this calculation the euclidean distance between the pt stops and a given pt speed is used. * 2. The pt simulation with the additional information about the pt times and distances between all possible pt stops. - * + * * The walk distances always are calculated as the euclidean distances between facilities and pt stops. The walk times corresponds to these distances for a given walk speed. - * + * * In our test network the euclidean distance between a facility and its nearest pt stop is always 50 m. So the total walk distance always is 100 m. * If origin and destination pt stop coincide, the agents still have to walk via the pt stop to their destination. Even if origin and destination facility are the same. * Moreover there are four pt stops ordered as a square with an euclidean distance of 180 m as the distance between to neighboring pt stops. * There are four facilities, each corresponding to one of the four pt stop. * The distance between to facilities is always bigger than the distance between their corresponding pt stops. So the euclidean distance between to facilities is an upper bound for the distance between to pt stops. - * + * * @author thomas * @author tthunig */ public class PtMatrixTest { - + private static final Logger log = LogManager.getLogger(PtMatrixTest.class); @Rule @@ -81,30 +81,30 @@ public void setUp() throws Exception { // (collect log messages internally before they can be written to file. Can be called multiple times without harm.) } - + /** * tests the pt matrix for the first case, when only the coordinates of the pt stops are known - * @throws IOException + * @throws IOException */ @Test public void testPtMatrixStops() throws IOException{ log.info("Start testing the pt matrix with information about the pt stops."); long start = System.currentTimeMillis(); - - + + // some default values double defaultWalkSpeed = 1.; // in m/s double defaultPtSpeed = 10.; // in m/s double beelineDistanceFactor = 2.; // a multiplier for the pt travel distance Config config = ConfigUtils.createConfig() ; - config.plansCalcRoute().setBeelineDistanceFactor(beelineDistanceFactor ) ; - config.plansCalcRoute().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed) ; - config.plansCalcRoute().setTeleportedModeSpeed(TransportMode.pt, defaultPtSpeed ) ; + config.routing().setBeelineDistanceFactor(beelineDistanceFactor ) ; + config.routing().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed) ; + config.routing().setTeleportedModeSpeed(TransportMode.pt, defaultPtSpeed ) ; Network network = CreateTestNetwork.createTestNetwork(); // creates a dummy network String location = CreateTestNetwork.createTestPtStationCSVFile(folder.newFile("ptStops.csv")); // creates a dummy csv file with pt stops fitting into the dummy network - + MatrixBasedPtRouterConfigGroup module = new MatrixBasedPtRouterConfigGroup(); module.setPtStopsInputFile(location); // this is to be compatible with real code config.addModule(module) ; @@ -112,98 +112,98 @@ public void testPtMatrixStops() throws IOException{ // determining the bounds minX/minY -- maxX/maxY. For optimal performance of the QuadTree. All pt stops should be evenly distributed within this rectangle. BoundingBox nbb = BoundingBox.createBoundingBox(network); // call and init the pt matrix - PtMatrix ptm = PtMatrix.createPtMatrix(config.plansCalcRoute(), nbb, module); + PtMatrix ptm = PtMatrix.createPtMatrix(config.routing(), nbb, module); // test the matrix List facilityList = CreateTestNetwork.getTestFacilityLocations(); - + for(int origin = 0; origin < facilityList.size(); origin++){ for(int destination = 0; destination < facilityList.size(); destination++){ - + // calculate travel times double totalTravelTime = ptm.getTotalTravelTime_seconds(facilityList.get( origin ), facilityList.get( destination )); double walkTravelTime = ptm.getTotalWalkTravelTime_seconds(facilityList.get( origin ), facilityList.get( destination )); double ptTravelTime = ptm.getPtTravelTime_seconds(facilityList.get( origin ), facilityList.get( destination )); - + // calculate travel distances double totalTravelDistance= ptm.getTotalTravelDistance_meter(facilityList.get( origin ), facilityList.get( destination )); double walkTravelDistance = ptm.getTotalWalkTravelDistance_meter(facilityList.get( origin ), facilityList.get( destination )); double ptTravelDistance = ptm.getPtTravelDistance_meter(facilityList.get( origin ), facilityList.get( destination )); - + log.info("From: " + facilityList.get( origin ).getX()+":"+facilityList.get( origin ).getY() + ", To: " + facilityList.get( destination ).getX()+":"+facilityList.get( destination ).getY() + ", TravelTime: " + totalTravelTime + ", Travel Distance: " + totalTravelDistance); - + // test travel time and distance for same origins and destinations // the agents will walk 50 m to the nearest pt stop and 50 m back to their origin facility, so the total travel distance have to be 100 m. if(origin == destination){ - + Assert.assertTrue(totalTravelTime == 100./defaultWalkSpeed); Assert.assertTrue(totalTravelDistance == 100.); } - + // test travel time and distance for neighboring origins and destinations else if( (origin + 1) % 4 == destination || (origin + 3) % 4 == destination){ - + // test total walk travel distance and time // in the test network the total walk distance always is 100 m, because the euclidean distance between a facility and its nearest pt stop always is 50 m Assert.assertTrue(walkTravelDistance == 100.); Assert.assertTrue(walkTravelTime == 100./defaultWalkSpeed); - + // test pt travel distance and time // in the test network the euclidean distance between neighboring pt stops always is 180 m Assert.assertTrue(ptTravelDistance == 180.*beelineDistanceFactor); Assert.assertTrue(ptTravelTime == (180./defaultPtSpeed)*beelineDistanceFactor); } - + // test travel times and distances for diagonal origin destination pairs else { // In our test network pt stops are closer to each other than facilities. // So an upper bound for the pt travel distance is the euclidean distance between the facilities (analog for the travel time). // A lower bound for pt travel distance and time are the values of neighboring origin destination pairs. - + double euclideanDistance= CoordUtils.calcEuclideanDistance(facilityList.get( origin ), facilityList.get( destination )); - + // test total walk travel distance and time // in the test network the total walk distance always is 100 m, because the euclidean distance between a facility and its nearest pt stop always is 50 m Assert.assertTrue(walkTravelDistance == 100.); Assert.assertTrue(walkTravelTime == 100./defaultWalkSpeed); - + // test upper bounds for pt travel distance and time (as described above) Assert.assertTrue(ptTravelDistance <= euclideanDistance*beelineDistanceFactor); Assert.assertTrue(ptTravelTime <= (euclideanDistance/defaultPtSpeed)*beelineDistanceFactor); - + // test lower bounds for pt travel distance and time (as described above) Assert.assertTrue(ptTravelDistance >= 180.*beelineDistanceFactor); Assert.assertTrue(ptTravelTime >= (180./defaultPtSpeed)*beelineDistanceFactor); } } } - + log.info("Creating pt matrix took " + ((System.currentTimeMillis() - start)/60000) + " minutes. Computation done!"); } - - + + /** * tests the pt matrix for the second case, when pt stops and pt travel times and distances are known - * + * * the values for the pt distances and times are given from a csv-file created with CreateTestNetwork.java - * For reasons of simplification we use the same csv-file for both informations (times and distances). Between all pt stops we set the pt distance to 100 m and the pt travel time to 100 min, except pairs of same pt stops, where we set both informations to zero. - * @throws IOException + * For reasons of simplification we use the same csv-file for both informations (times and distances). Between all pt stops we set the pt distance to 100 m and the pt travel time to 100 min, except pairs of same pt stops, where we set both informations to zero. + * @throws IOException */ @Test public void testPtMatrixTimesAndDistances() throws IOException{ log.info("Start testing the pt matrix with information about the pt stops, pt travel times and distances."); long start = System.currentTimeMillis(); - - + + // some default values double defaultWalkSpeed = 1.; // in m/s double defaultPtSpeed = 10.; // in m/s double beelineDistanceFactor = 2.; // a multiplier for the pt travel distance - + Config config = ConfigUtils.createConfig() ; - config.plansCalcRoute().setBeelineDistanceFactor(beelineDistanceFactor ) ; - config.plansCalcRoute().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed) ; - config.plansCalcRoute().setTeleportedModeSpeed(TransportMode.pt, defaultPtSpeed ) ; + config.routing().setBeelineDistanceFactor(beelineDistanceFactor ) ; + config.routing().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed) ; + config.routing().setTeleportedModeSpeed(TransportMode.pt, defaultPtSpeed ) ; Network network = CreateTestNetwork.createTestNetwork(); // creates a dummy network @@ -213,49 +213,49 @@ public void testPtMatrixTimesAndDistances() throws IOException{ MatrixBasedPtRouterConfigGroup module = new MatrixBasedPtRouterConfigGroup(); module.setUsingPtStops(true); module.setUsingTravelTimesAndDistances(true); - module.setPtStopsInputFile(stopsLocation); - module.setPtTravelTimesInputFile(timesLocation); + module.setPtStopsInputFile(stopsLocation); + module.setPtTravelTimesInputFile(timesLocation); module.setPtTravelDistancesInputFile(timesLocation); // determining the bounds minX/minY -- maxX/maxY. For optimal performance of the QuadTree. All pt stops should be evenly distributed within this rectangle. BoundingBox nbb = BoundingBox.createBoundingBox(network); // call and init the pt matrix - PtMatrix ptm = PtMatrix.createPtMatrix(config.plansCalcRoute(), nbb, module); + PtMatrix ptm = PtMatrix.createPtMatrix(config.routing(), nbb, module); // test the matrix List facilityList = CreateTestNetwork.getTestFacilityLocations(); - + for(int origin = 0; origin < facilityList.size(); origin++){ for(int destination = 0; destination < facilityList.size(); destination++){ - + // calculate travel times double totalTravelTime = ptm.getTotalTravelTime_seconds(facilityList.get( origin ), facilityList.get( destination )); double walkTravelTime = ptm.getTotalWalkTravelTime_seconds(facilityList.get( origin ), facilityList.get( destination )); double ptTravelTime = ptm.getPtTravelTime_seconds(facilityList.get( origin ), facilityList.get( destination )); - + // calculate travel distances double totalTravelDistance= ptm.getTotalTravelDistance_meter(facilityList.get( origin ), facilityList.get( destination )); double walkTravelDistance = ptm.getTotalWalkTravelDistance_meter(facilityList.get( origin ), facilityList.get( destination )); double ptTravelDistance = ptm.getPtTravelDistance_meter(facilityList.get( origin ), facilityList.get( destination )); - + log.info("From: " + facilityList.get( origin ).getX()+":"+facilityList.get( origin ).getY() + ", To: " + facilityList.get( destination ).getX()+":"+facilityList.get( destination ).getY() + ", TravelTime: " + totalTravelTime + ", Travel Distance: " + totalTravelDistance); - + // test travel time and distance for same origins and destinations // the agents will walk 50 m to the nearest pt stop and 50 m back to their origin facility, so the total travel distance have to be 100 m. if(origin == destination){ - + Assert.assertTrue(totalTravelDistance == 100.); Assert.assertTrue(totalTravelTime == 100./defaultWalkSpeed); } - + // test travel time and distance for different origins and destinations else { - + // test total walk travel distance and time // in the test network the total walk distance always is 100 m, because the euclidean distance between a facility and its nearest pt stop always is 50 m Assert.assertTrue(walkTravelDistance == 100.); Assert.assertTrue(walkTravelTime == 100./defaultWalkSpeed); - + // test pt travel distance and time // in the csv-file the pt travel distance is given as 100 m; the pt travel time as 100 min Assert.assertTrue(ptTravelDistance == 100.); @@ -263,8 +263,8 @@ public void testPtMatrixTimesAndDistances() throws IOException{ } } } - + log.info("Creating pt matrix took " + ((System.currentTimeMillis() - start)/60000) + " minutes. Computation done!"); } -} \ No newline at end of file +} diff --git a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/RunConfigurableMinibusExample.java b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/RunConfigurableMinibusExample.java index 1b0eb2e684b..399088ffdb7 100644 --- a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/RunConfigurableMinibusExample.java +++ b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/RunConfigurableMinibusExample.java @@ -26,9 +26,6 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.minibus.fare.StageContainer; -import org.matsim.contrib.minibus.fare.TicketMachineDefaultImpl; -import org.matsim.contrib.minibus.fare.TicketMachineI; import org.matsim.contrib.minibus.hook.PModule; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; @@ -39,7 +36,7 @@ /** * Entry point, registers all necessary hooks - * + * * @author aneumann */ public final class RunConfigurableMinibusExample { @@ -55,16 +52,16 @@ public static void main(final String[] args) { } Config config = ConfigUtils.loadConfig( args[0], new PConfigGroup() ) ; - final PConfigGroup pConfig = ConfigUtils.addOrGetModule(config, PConfigGroup.class) ; + final PConfigGroup pConfig = ConfigUtils.addOrGetModule(config, PConfigGroup.class) ; Scenario scenario = ScenarioUtils.loadScenario(config); final Set> subsidizedStops = new TreeSet<>() ; // subsidizedStops.add(...) ; // add subsidized stops - + Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - + controler.getConfig().controller().setCreateGraphs(false); + if ( true ) { throw new RuntimeException("the following is not possibly any more; just copy PModule and modify it to your needs. kai, jan'17") ; } @@ -73,18 +70,18 @@ public static void main(final String[] args) { // @Override public double getFare(StageContainer stageContainer) { // double fare = delegate.getFare(stageContainer) ; // if ( subsidizedStops.contains( stageContainer.getStopEntered() ) ) { -// fare+=1. ; +// fare+=1. ; // // this would increase the fare for the subsidized stops ... // // ... but I fear that this also means that the passengers have to pay this. kai, jan'17 // } // return fare ; // } // }) ; - - + + controler.addOverridingModule(new PModule()) ; controler.run(); - } -} \ No newline at end of file + } +} diff --git a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/hook/PBox.java b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/hook/PBox.java index df5a721b2e1..795398d69fe 100644 --- a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/hook/PBox.java +++ b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/hook/PBox.java @@ -129,7 +129,7 @@ void notifyStartup(StartupEvent event) { this.operators.addAll(operatorsFromSchedule); // init initial set of operators - reduced by the number of preset operators - LinkedList initialOperators = this.operatorInitializer.createAdditionalOperators(this.strategyManager, event.getServices().getConfig().controler().getFirstIteration(), (this.pConfig.getNumberOfOperators() - operatorsFromSchedule.size())); + LinkedList initialOperators = this.operatorInitializer.createAdditionalOperators(this.strategyManager, event.getServices().getConfig().controller().getFirstIteration(), (this.pConfig.getNumberOfOperators() - operatorsFromSchedule.size())); this.operators.addAll(initialOperators); // collect the transit schedules from all operators diff --git a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/hook/PControlerListener.java b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/hook/PControlerListener.java index ee1e253771a..efe0a4c45e3 100644 --- a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/hook/PControlerListener.java +++ b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/hook/PControlerListener.java @@ -53,7 +53,7 @@ /** * Hook to register paratransit black box with MATSim - * + * * @author aneumann */ final class PControlerListener implements IterationStartsListener, StartupListener, ScoringListener { @@ -66,7 +66,7 @@ final class PControlerListener implements IterationStartsListener, StartupListen private final POperators operators ; @Inject(optional=true) private PersonReRouteStuckFactory stuckFactory; - + @Inject private TimeInterpretation timeInterpretation; @@ -92,7 +92,7 @@ public void notifyStartup(StartupEvent event) { public void notifyIterationStarts(IterationStartsEvent event) { PBox pBox = (PBox) operators ; final MatsimServices controler = event.getServices(); - if(event.getIteration() == controler.getConfig().controler().getFirstIteration()){ + if(event.getIteration() == controler.getConfig().controller().getFirstIteration()){ log.info("This is the first iteration. All lines were added by notifyStartup event."); } else { pBox.notifyIterationStarts(event); diff --git a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/Line2GexfPStat.java b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/Line2GexfPStat.java index 9da373eb053..f711a97b72b 100644 --- a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/Line2GexfPStat.java +++ b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/Line2GexfPStat.java @@ -120,7 +120,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { public void notifyShutdown(ShutdownEvent event) { // call shutdown for all remaining gexf for (SimpleGexfPStat gexf : this.lineId2GexfPStat.values()) { - gexf.notifyShutdown(event.getServices().getConfig().controler().getLastIteration()); + gexf.notifyShutdown(event.getServices().getConfig().controller().getLastIteration()); } log.info("terminated the last " + this.lineId2GexfPStat.values().size() + " gexf handlers..."); } diff --git a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/PStatsOverview.java b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/PStatsOverview.java index 97fb6ea8fe5..1cdc24a12f5 100644 --- a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/PStatsOverview.java +++ b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/PStatsOverview.java @@ -21,6 +21,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; @@ -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 at the end of each iteration the following statistics: @@ -155,8 +155,8 @@ public void notifyStartup(final StartupEvent event) { this.pStatsWriter = null; } - 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; if (iterations > 10000) iterations = 10000; // limit the history size this.history = new double[29][iterations+1]; diff --git a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/operatorLogger/POperatorLogger.java b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/operatorLogger/POperatorLogger.java index 16fe42875af..11732305d60 100644 --- a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/operatorLogger/POperatorLogger.java +++ b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/stats/operatorLogger/POperatorLogger.java @@ -21,6 +21,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; @@ -42,7 +43,6 @@ import org.matsim.core.controler.listener.ShutdownListener; import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.pt.transitSchedule.api.TransitStopFacility; diff --git a/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/PControlerTestIT.java b/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/PControlerTestIT.java index e61556b89b6..3429d672745 100644 --- a/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/PControlerTestIT.java +++ b/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/PControlerTestIT.java @@ -21,7 +21,6 @@ import java.io.File; import java.util.ArrayList; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; @@ -43,7 +42,7 @@ /** * Integration test of the minibus package - * + * * @author aneumann */ public class PControlerTestIT implements TabularFileHandler{ @@ -63,23 +62,23 @@ public final void testPControler() { final String outputPath = utils.getOutputDirectory() + scenarioName + "/"; final String configFile = inputPath + "config_" + scenarioName + ".xml"; - + // --- Config config = ConfigUtils.loadConfig(configFile, new PConfigGroup()); - config.controler().setLastIteration(numberOfIterations); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setCreateGraphs(false); - config.controler().setOutputDirectory(outputPath); - + config.controller().setLastIteration(numberOfIterations); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setCreateGraphs(false); + config.controller().setOutputDirectory(outputPath); + // --- Scenario scenario = ScenarioUtils.createScenario(config); ScenarioUtils.loadScenario(scenario); - + // --- - + Controler controler = new Controler(scenario); // manipulate config @@ -90,14 +89,14 @@ public final void testPControler() { controler.run(); - // Check standard output files + // Check standard output files List filesToCheckFor = new LinkedList<>(); filesToCheckFor.add(outputPath + scenarioName + ".0.actsFromParatransitUsers.txt"); filesToCheckFor.add(outputPath + scenarioName + ".pOperatorLogger.txt"); filesToCheckFor.add(outputPath + scenarioName + ".pStats.txt"); - filesToCheckFor.add(outputPath + scenarioName + ".scorestats.txt"); - filesToCheckFor.add(outputPath + scenarioName + ".stopwatch.txt"); - filesToCheckFor.add(outputPath + scenarioName + ".traveldistancestats.txt"); + filesToCheckFor.add(outputPath + scenarioName + ".scorestats.csv"); + filesToCheckFor.add(outputPath + scenarioName + ".stopwatch.csv"); + filesToCheckFor.add(outputPath + scenarioName + ".traveldistancestats.csv"); filesToCheckFor.add(outputPath + scenarioName + ".pStat_light.gexf.gz"); filesToCheckFor.add(outputPath + scenarioName + ".pStat.gexf.gz"); @@ -145,6 +144,6 @@ public final void testPControler() { @Override public void startRow(String[] row) { - this.pStatsResults.add(row); - } + this.pStatsResults.add(row); + } } diff --git a/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/SubsidyContextTestIT.java b/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/SubsidyContextTestIT.java index c23722e3123..f9881ed715e 100644 --- a/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/SubsidyContextTestIT.java +++ b/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/SubsidyContextTestIT.java @@ -42,50 +42,50 @@ import org.matsim.testcases.MatsimTestUtils; /** - * + * * Tests the functionality of adding subsidies to the operator's score. - * + * * @author ikaddoura */ public class SubsidyContextTestIT implements TabularFileHandler { - + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); private final ArrayList pStatsResults = new ArrayList<>(); private String gridScenarioDirectory ="../../example-scenario/input/"; - + @Ignore @Test public final void testDefaultPControler() { - + Config config1 = ConfigUtils.loadConfig( utils.getClassInputDirectory() + "config.xml", new PConfigGroup() ) ; - + config1.network().setInputFile(gridScenarioDirectory + "network.xml"); config1.transit().setVehiclesFile(gridScenarioDirectory + "transitVehicles.xml"); config1.transit().setTransitScheduleFile(gridScenarioDirectory + "transitSchedule_10min.xml"); config1.plans().setInputFile(gridScenarioDirectory + "population_1000_per_hour_each_from_6_to_10.xml.gz"); - config1.controler().setOutputDirectory(utils.getOutputDirectory()); - - Scenario scenario1 = ScenarioUtils.loadScenario(config1); + config1.controller().setOutputDirectory(utils.getOutputDirectory()); + + Scenario scenario1 = ScenarioUtils.loadScenario(config1); Controler controler1 = new Controler(scenario1); - - controler1.getConfig().controler().setCreateGraphs(true); - controler1.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); - + + controler1.getConfig().controller().setCreateGraphs(true); + controler1.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + controler1.addOverridingModule(new PModule()) ; controler1.run(); - - // Check standard output files - + + // Check standard output files + List filesToCheckFor = new LinkedList<>(); filesToCheckFor.add(utils.getOutputDirectory() + "0.actsFromParatransitUsers.txt"); filesToCheckFor.add(utils.getOutputDirectory() + "pOperatorLogger.txt"); filesToCheckFor.add(utils.getOutputDirectory() + "pStats.txt"); - filesToCheckFor.add(utils.getOutputDirectory() + "scorestats.txt"); - filesToCheckFor.add(utils.getOutputDirectory() + "stopwatch.txt"); - filesToCheckFor.add(utils.getOutputDirectory() + "traveldistancestats.txt"); + filesToCheckFor.add(utils.getOutputDirectory() + "scorestats.csv"); + filesToCheckFor.add(utils.getOutputDirectory() + "stopwatch.csv"); + filesToCheckFor.add(utils.getOutputDirectory() + "traveldistancestats.csv"); filesToCheckFor.add(utils.getOutputDirectory() + "pStat_light.gexf.gz"); filesToCheckFor.add(utils.getOutputDirectory() + "pStat.gexf.gz"); @@ -112,42 +112,42 @@ public final void testDefaultPControler() { Assert.assertEquals("Number of +coops (final iteration)", "4", this.pStatsResults.get(31)[2]); Assert.assertEquals("Number of +routes (final iteration)", "6", this.pStatsResults.get(31)[4]); Assert.assertEquals("Number of +pax (final iteration)", "3610", this.pStatsResults.get(31)[6]); - Assert.assertEquals("Number of +veh (final iteration)", "16", this.pStatsResults.get(31)[8]); + Assert.assertEquals("Number of +veh (final iteration)", "16", this.pStatsResults.get(31)[8]); } - + @Ignore @Test public final void testSubsidyPControler() { - + Config config2 = ConfigUtils.loadConfig( utils.getClassInputDirectory() + "config.xml", new PConfigGroup() ) ; - + PConfigGroup pConfig2 = (PConfigGroup) config2.getModules().get(PConfigGroup.GROUP_NAME); pConfig2.setSubsidyApproach("perPassenger"); - + config2.network().setInputFile(gridScenarioDirectory + "network.xml"); config2.transit().setVehiclesFile(gridScenarioDirectory + "transitVehicles.xml"); config2.transit().setTransitScheduleFile(gridScenarioDirectory + "transitSchedule_10min.xml"); config2.plans().setInputFile(gridScenarioDirectory + "population_1000_per_hour_each_from_6_to_10.xml.gz"); - config2.controler().setOutputDirectory(utils.getOutputDirectory()); - - Scenario scenario2 = ScenarioUtils.loadScenario(config2); + config2.controller().setOutputDirectory(utils.getOutputDirectory()); + + Scenario scenario2 = ScenarioUtils.loadScenario(config2); Controler controler2 = new Controler(scenario2); - - controler2.getConfig().controler().setCreateGraphs(true); - controler2.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); - + + controler2.getConfig().controller().setCreateGraphs(true); + controler2.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + controler2.addOverridingModule(new PModule()) ; controler2.run(); - - // Check standard output files - + + // Check standard output files + List filesToCheckFor = new LinkedList<>(); filesToCheckFor.add(utils.getOutputDirectory() + "0.actsFromParatransitUsers.txt"); filesToCheckFor.add(utils.getOutputDirectory() + "pOperatorLogger.txt"); filesToCheckFor.add(utils.getOutputDirectory() + "pStats.txt"); - filesToCheckFor.add(utils.getOutputDirectory() + "scorestats.txt"); - filesToCheckFor.add(utils.getOutputDirectory() + "stopwatch.txt"); - filesToCheckFor.add(utils.getOutputDirectory() + "traveldistancestats.txt"); + filesToCheckFor.add(utils.getOutputDirectory() + "scorestats.csv"); + filesToCheckFor.add(utils.getOutputDirectory() + "stopwatch.csv"); + filesToCheckFor.add(utils.getOutputDirectory() + "traveldistancestats.csv"); filesToCheckFor.add(utils.getOutputDirectory() + "pStat_light.gexf.gz"); filesToCheckFor.add(utils.getOutputDirectory() + "pStat.gexf.gz"); @@ -175,13 +175,13 @@ public final void testSubsidyPControler() { Assert.assertEquals("Number of +coops (final iteration)", "4", this.pStatsResults.get(31)[2]); Assert.assertEquals("Number of +routes (final iteration)", "51", this.pStatsResults.get(31)[4]); Assert.assertEquals("Number of +pax (final iteration)", "9951", this.pStatsResults.get(31)[6]); - Assert.assertEquals("Number of +veh (final iteration)", "260", this.pStatsResults.get(31)[8]); + Assert.assertEquals("Number of +veh (final iteration)", "260", this.pStatsResults.get(31)[8]); } - + @Override public void startRow(String[] row) { - this.pStatsResults.add(row); + this.pStatsResults.add(row); } - + } diff --git a/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/SubsidyTestIT.java b/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/SubsidyTestIT.java index 10116f29b0c..07089958ca3 100644 --- a/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/SubsidyTestIT.java +++ b/contribs/minibus/src/test/java/org/matsim/contrib/minibus/integration/SubsidyTestIT.java @@ -38,27 +38,25 @@ import org.matsim.core.utils.io.tabularFileParser.TabularFileHandler; import org.matsim.core.utils.io.tabularFileParser.TabularFileParser; import org.matsim.core.utils.io.tabularFileParser.TabularFileParserConfig; -import org.matsim.pt.config.TransitConfigGroup.TransitRoutingAlgorithmType; import org.matsim.testcases.MatsimTestUtils; /** - * + * * Tests the functionality of adding subsidies to the operator's score. - * + * * @author ikaddoura */ public class SubsidyTestIT implements TabularFileHandler { - + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); private final ArrayList pStatsResults = new ArrayList<>(); @Test public final void testSubsidyPControler() { - + Config config = ConfigUtils.loadConfig( utils.getClassInputDirectory() + "config.xml", new PConfigGroup() ) ; - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); PConfigGroup pConfig = (PConfigGroup) config.getModules().get(PConfigGroup.GROUP_NAME); pConfig.setSubsidyApproach("perPassenger"); @@ -67,27 +65,27 @@ public final void testSubsidyPControler() { config.transit().setVehiclesFile(gridScenarioDirectory + "transitVehicles.xml"); config.transit().setTransitScheduleFile(gridScenarioDirectory + "transitSchedule_10min.xml"); config.plans().setInputFile(gridScenarioDirectory + "population_1000_per_hour_each_from_6_to_10.xml.gz"); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setWriteEventsInterval(0); - Scenario scenario = ScenarioUtils.loadScenario(config); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setWriteEventsInterval(0); + Scenario scenario = ScenarioUtils.loadScenario(config); Controler controler = new Controler(scenario); - - controler.getConfig().controler().setCreateGraphs(true); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); - + + controler.getConfig().controller().setCreateGraphs(true); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + controler.addOverridingModule(new PModule()) ; controler.run(); - - // Check standard output files - + + // Check standard output files + List filesToCheckFor = new LinkedList<>(); filesToCheckFor.add(utils.getOutputDirectory() + "0.actsFromParatransitUsers.txt"); filesToCheckFor.add(utils.getOutputDirectory() + "pOperatorLogger.txt"); filesToCheckFor.add(utils.getOutputDirectory() + "pStats.txt"); - filesToCheckFor.add(utils.getOutputDirectory() + "scorestats.txt"); - filesToCheckFor.add(utils.getOutputDirectory() + "stopwatch.txt"); - filesToCheckFor.add(utils.getOutputDirectory() + "traveldistancestats.txt"); + filesToCheckFor.add(utils.getOutputDirectory() + "scorestats.csv"); + filesToCheckFor.add(utils.getOutputDirectory() + "stopwatch.csv"); + filesToCheckFor.add(utils.getOutputDirectory() + "traveldistancestats.csv"); filesToCheckFor.add(utils.getOutputDirectory() + "pStat_light.gexf.gz"); filesToCheckFor.add(utils.getOutputDirectory() + "pStat.gexf.gz"); @@ -105,13 +103,16 @@ public final void testSubsidyPControler() { new TabularFileParser().parse(tabFileParserConfig, this); // Check final iteration - Assert.assertEquals("Number of budget (final iteration)", "202319997.4909444700", this.pStatsResults.get(2)[9]); + String actual = this.pStatsResults.get(2)[9]; + // flaky (non-deterministic) test... allow multiple results + Assert.assertTrue("Number of budget (final iteration)", + List.of("174413625.6239444000", "174413625.7708889500", "174413625.7022777500").contains(actual)); } - + @Override public void startRow(String[] row) { - this.pStatsResults.add(row); + this.pStatsResults.add(row); } - + } diff --git a/contribs/minibus/test/input/org/matsim/contrib/minibus/raptor/TransferAtAccessStopRaptorTest/NPETest/config-in-original-coords-minibus-w-transit.xml b/contribs/minibus/test/input/org/matsim/contrib/minibus/raptor/TransferAtAccessStopRaptorTest/NPETest/config-in-original-coords-minibus-w-transit.xml index 9b4ed1bafe3..794e81bbbe5 100644 --- a/contribs/minibus/test/input/org/matsim/contrib/minibus/raptor/TransferAtAccessStopRaptorTest/NPETest/config-in-original-coords-minibus-w-transit.xml +++ b/contribs/minibus/test/input/org/matsim/contrib/minibus/raptor/TransferAtAccessStopRaptorTest/NPETest/config-in-original-coords-minibus-w-transit.xml @@ -37,7 +37,7 @@ - + @@ -506,9 +506,6 @@ - - - diff --git a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/MultiModalModule.java b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/MultiModalModule.java index d785e63042c..2b6d39a2ec0 100644 --- a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/MultiModalModule.java +++ b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/MultiModalModule.java @@ -33,8 +33,8 @@ import org.matsim.contrib.multimodal.router.util.BikeTravelTimeFactory; import org.matsim.contrib.multimodal.router.util.UnknownTravelTimeFactory; import org.matsim.contrib.multimodal.router.util.WalkTravelTimeFactory; -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.AbstractModule; import org.matsim.core.router.NetworkRoutingProvider; import org.matsim.core.router.RoutingModule; @@ -63,14 +63,14 @@ public void install() { // would just operate on that sub-network. // kai, dec'19 - PlansCalcRouteConfigGroup plansCalcRouteConfigGroup = getConfig().plansCalcRoute(); - PlanCalcScoreConfigGroup cnScoringGroup = getConfig().planCalcScore(); + RoutingConfigGroup routingConfigGroup = getConfig().routing(); + ScoringConfigGroup cnScoringGroup = getConfig().scoring(); MultiModalConfigGroup multiModalConfigGroup = (MultiModalConfigGroup) getConfig().getModule(MultiModalConfigGroup.GROUP_NAME); Set simulatedModes = CollectionUtils.stringToSet(multiModalConfigGroup.getSimulatedModes()); for (String mode : simulatedModes) { switch( mode ){ case TransportMode.walk:{ - Provider factory = new WalkTravelTimeFactory( plansCalcRouteConfigGroup, linkSlopes ); + Provider factory = new WalkTravelTimeFactory(routingConfigGroup, linkSlopes ); addTravelTimeBinding( mode ).toProvider( factory ); addTravelDisutilityFactoryBinding( mode ).toInstance( new RandomizingTimeDistanceTravelDisutilityFactory( mode, getConfig() ) ); addRoutingModuleBinding( mode ).toProvider( new NetworkRoutingProvider( mode ) ); @@ -83,7 +83,7 @@ public void install() { addRoutingModuleBinding( mode ).to( Key.get( RoutingModule.class, Names.named( TransportMode.walk ) ) ); break; case TransportMode.bike:{ - Provider factory = new BikeTravelTimeFactory( plansCalcRouteConfigGroup, linkSlopes ); + Provider factory = new BikeTravelTimeFactory(routingConfigGroup, linkSlopes ); addTravelTimeBinding( mode ).toProvider( factory ); addTravelDisutilityFactoryBinding( mode ).toInstance( new RandomizingTimeDistanceTravelDisutilityFactory( mode, getConfig() ) ); addRoutingModuleBinding( mode ).toProvider( new NetworkRoutingProvider( mode ) ); @@ -96,7 +96,7 @@ public void install() { "Use a constructor where you provide the travel time objects. " + "Using an UnknownTravelTime calculator based on constant speed." + "Agent specific attributes are not taken into account!" ); - factory = new UnknownTravelTimeFactory( mode, plansCalcRouteConfigGroup ); + factory = new UnknownTravelTimeFactory( mode, routingConfigGroup); } else{ log.info( "Found additional travel time factory from type " + factory.getClass().toString() + " for mode " + mode + "." ); diff --git a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/BikeTravelTime.java b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/BikeTravelTime.java index 69a4565d23a..c6a5cad91ba 100644 --- a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/BikeTravelTime.java +++ b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/BikeTravelTime.java @@ -24,7 +24,7 @@ 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.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.vehicles.Vehicle; import java.util.Map; @@ -33,15 +33,15 @@ * Data to calculate a person's travel time on a link is taken from: * John Parkin and Jonathon Rotheram (2010): Design speeds and acceleration characteristics * of bicycle traffic for use in planning and appraisal. - * + * * The default downhill speed is limited to 35 km/h. The value is scaled for each person * based on age, gender and scatter. - * + * * On steep links, a person is faster by walking than by biking. For such links, the * walk travel time is returned. */ public class BikeTravelTime extends WalkTravelTime { - + /* * Cache variables for each thread accessing the object separately. */ @@ -49,31 +49,31 @@ public class BikeTravelTime extends WalkTravelTime { /*package*/ private final ThreadLocal maxPersonBikeSpeedCache; /*package*/ private final ThreadLocal personUphillFactorCache; /*package*/ private final ThreadLocal personDownhillFactorCache; - + /* * If the set reference speed does not match the default reference speed, - * the up- and downhill factors are scaled accordingly. + * the up- and downhill factors are scaled accordingly. */ private final double defaultReferenceSpeed = 6.01; // [m/s] - + private final double referenceBikeSpeed; // 6.01 according to Prakin and Rotheram private final double maxBikeSpeed = 35.0 / 3.6; // according to Parkin and Rotheram - + private final double downhillFactor = 0.2379; // 0%..-15% private final double uphillFactor = -0.4002; // 0%..12% - - public BikeTravelTime(PlansCalcRouteConfigGroup plansCalcGroup, Map, Double> linkSlopes) { + + public BikeTravelTime(RoutingConfigGroup plansCalcGroup, Map, Double> linkSlopes) { super(plansCalcGroup, linkSlopes); - + this.referenceBikeSpeed = plansCalcGroup.getTeleportedModeSpeeds().get(TransportMode.bike); - + this.personBikeSpeedCache = new ThreadLocal<>(); this.maxPersonBikeSpeedCache = new ThreadLocal<>(); this.personUphillFactorCache = new ThreadLocal<>(); this.personDownhillFactorCache = new ThreadLocal<>(); } - - public BikeTravelTime(PlansCalcRouteConfigGroup plansCalcGroup) { + + public BikeTravelTime(RoutingConfigGroup plansCalcGroup) { this(plansCalcGroup, null); } @@ -82,22 +82,22 @@ public BikeTravelTime(PlansCalcRouteConfigGroup plansCalcGroup) { public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) { setPerson(person); double walkTravelTime = super.getLinkTravelTime(link, time, person, vehicle); - + double slope = super.getSlope(link); double slopeShift = getSlopeShift(slope); - + // double linkSpeed = this.personBikeSpeed + slopeShift; double linkSpeed = this.personBikeSpeedCache.get() + slopeShift; - + // limit min and max speed // if (linkSpeed > maxPersonBikeSpeed) linkSpeed = maxPersonBikeSpeed; if (linkSpeed > this.maxPersonBikeSpeedCache.get()) linkSpeed = this.maxPersonBikeSpeedCache.get(); else if (linkSpeed < 0.0) linkSpeed = Double.MIN_VALUE; - + double bikeTravelTime = link.getLength() / linkSpeed; return Math.min(walkTravelTime, bikeTravelTime); } - + /* * It is assumed, that there is a linear relation between speed and slope. * The returned values shifts the speed on a flat area. @@ -107,20 +107,20 @@ public double getLinkTravelTime(Link link, double time, Person person, Vehicle v if (slope > 0.0) return this.personUphillFactorCache.get() * slope; else return this.personDownhillFactorCache.get() * slope; } - + @Override void setPerson(Person person) { - /* - * Only recalculate the person's speed factor if the person has + /* + * Only recalculate the person's speed factor if the person has * changed. This check has to be performed before super.setPerson(...) * is called because there the personId is already updated! */ - /* + /* * Only recalculate the person's walk speed factor if * the person has changed and is not in the map. */ if (this.personCache.get() != null && person.getId().equals(this.personCache.get().getId())) return; - + /* * If the person's walk speed is already in the map, use that value. * Otherwise calculate it and add it to the map. @@ -137,9 +137,9 @@ void setPerson(Person person) { super.setPerson(person); return; } - + super.setPerson(person); - + // this.personBikeSpeed = this.referenceBikeSpeed * this.personFactor; // this.maxPersonBikeSpeed = maxBikeSpeed * personFactor; // this.personUphillFactor = uphillFactor * personFactor * referenceBikeSpeed / defaultReferenceSpeed; diff --git a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/BikeTravelTimeFactory.java b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/BikeTravelTimeFactory.java index 47a3087b3ed..045dcefae3f 100644 --- a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/BikeTravelTimeFactory.java +++ b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/BikeTravelTimeFactory.java @@ -23,7 +23,7 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.router.util.TravelTime; import jakarta.inject.Provider; @@ -31,26 +31,26 @@ public class BikeTravelTimeFactory implements Provider { - private final PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; + private final RoutingConfigGroup routingConfigGroup; private final Map, Double> linkSlopes; // slope information in % - public BikeTravelTimeFactory(PlansCalcRouteConfigGroup plansCalcRouteConfigGroup) { - this(plansCalcRouteConfigGroup, null); + public BikeTravelTimeFactory(RoutingConfigGroup routingConfigGroup) { + this(routingConfigGroup, null); } - public BikeTravelTimeFactory(PlansCalcRouteConfigGroup plansCalcRouteConfigGroup, - Map, Double> linkSlopes) { - this.plansCalcRouteConfigGroup = plansCalcRouteConfigGroup; + public BikeTravelTimeFactory(RoutingConfigGroup routingConfigGroup, + Map, Double> linkSlopes) { + this.routingConfigGroup = routingConfigGroup; this.linkSlopes = linkSlopes; - if (plansCalcRouteConfigGroup.getTeleportedModeSpeeds().get(TransportMode.bike) == null) { + if (routingConfigGroup.getTeleportedModeSpeeds().get(TransportMode.bike) == null) { throw new RuntimeException("No speed was found for mode bike! Aborting."); } } @Override public TravelTime get() { - return new BikeTravelTime(this.plansCalcRouteConfigGroup, this.linkSlopes); + return new BikeTravelTime(this.routingConfigGroup, this.linkSlopes); } } diff --git a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/MultiModalTravelTimeFactory.java b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/MultiModalTravelTimeFactory.java index 8a32bbd561b..008b9d58406 100644 --- a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/MultiModalTravelTimeFactory.java +++ b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/MultiModalTravelTimeFactory.java @@ -28,7 +28,7 @@ import org.matsim.contrib.multimodal.config.MultiModalConfigGroup; import org.matsim.core.api.internal.MatsimFactory; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.router.util.TravelTime; import org.matsim.core.utils.collections.CollectionUtils; @@ -79,19 +79,19 @@ public Map createTravelTimes() { private void initMultiModalTravelTimeFactories(Config config) { - PlansCalcRouteConfigGroup plansCalcRouteConfigGroup = config.plansCalcRoute(); + RoutingConfigGroup routingConfigGroup = config.routing(); MultiModalConfigGroup multiModalConfigGroup = (MultiModalConfigGroup) config.getModule(MultiModalConfigGroup.GROUP_NAME); Set simulatedModes = CollectionUtils.stringToSet(multiModalConfigGroup.getSimulatedModes()); for (String mode : simulatedModes) { if (mode.equals(TransportMode.walk)) { - Provider factory = new WalkTravelTimeFactory(plansCalcRouteConfigGroup, linkSlopes); + Provider factory = new WalkTravelTimeFactory(routingConfigGroup, linkSlopes); this.factories.put(mode, factory); } else if (mode.equals(TransportMode.transit_walk)) { - Provider factory = new TransitWalkTravelTimeFactory(plansCalcRouteConfigGroup, linkSlopes); + Provider factory = new TransitWalkTravelTimeFactory(routingConfigGroup, linkSlopes); this.factories.put(mode, factory); } else if (mode.equals(TransportMode.bike)) { - Provider factory = new BikeTravelTimeFactory(plansCalcRouteConfigGroup, linkSlopes); + Provider factory = new BikeTravelTimeFactory(routingConfigGroup, linkSlopes); this.factories.put(mode, factory); } else { Provider factory = getTravelTimeFactory(mode); @@ -101,7 +101,7 @@ private void initMultiModalTravelTimeFactories(Config config) { "Use a constructor where you provide the travel time objects. " + "Using a UnknownTravelTime calculator based on constant speed." + "Agent specific attributes are not taken into account!"); - factory = new UnknownTravelTimeFactory(mode, plansCalcRouteConfigGroup); + factory = new UnknownTravelTimeFactory(mode, routingConfigGroup); this.factories.put(mode, factory); } else { log.info("Found additional travel time factory from type " + factory.getClass().toString() + diff --git a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/TransitWalkTravelTimeFactory.java b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/TransitWalkTravelTimeFactory.java index f991751c15c..efc8570216f 100644 --- a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/TransitWalkTravelTimeFactory.java +++ b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/TransitWalkTravelTimeFactory.java @@ -23,7 +23,7 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.router.util.TravelTime; import jakarta.inject.Provider; @@ -31,26 +31,26 @@ public class TransitWalkTravelTimeFactory implements Provider { - private final PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; + private final RoutingConfigGroup routingConfigGroup; private final Map, Double> linkSlopes; // slope information in % - public TransitWalkTravelTimeFactory(PlansCalcRouteConfigGroup plansCalcRouteConfigGroup) { - this(plansCalcRouteConfigGroup, null); + public TransitWalkTravelTimeFactory(RoutingConfigGroup routingConfigGroup) { + this(routingConfigGroup, null); } - public TransitWalkTravelTimeFactory(PlansCalcRouteConfigGroup plansCalcRouteConfigGroup, - Map, Double> linkSlopes) { - this.plansCalcRouteConfigGroup = plansCalcRouteConfigGroup; + public TransitWalkTravelTimeFactory(RoutingConfigGroup routingConfigGroup, + Map, Double> linkSlopes) { + this.routingConfigGroup = routingConfigGroup; this.linkSlopes = linkSlopes; - if (plansCalcRouteConfigGroup.getTeleportedModeSpeeds().get(TransportMode.transit_walk) == null) { + if (routingConfigGroup.getTeleportedModeSpeeds().get(TransportMode.transit_walk) == null) { throw new RuntimeException("No speed was found for mode transit_walk! Aborting."); } } @Override public TravelTime get() { - return new WalkTravelTime(plansCalcRouteConfigGroup.getTeleportedModeSpeeds().get(TransportMode.transit_walk), this.linkSlopes); + return new WalkTravelTime(routingConfigGroup.getTeleportedModeSpeeds().get(TransportMode.transit_walk), this.linkSlopes); } } diff --git a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/UnknownTravelTime.java b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/UnknownTravelTime.java index 0d6112bf75d..519cce73a34 100644 --- a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/UnknownTravelTime.java +++ b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/UnknownTravelTime.java @@ -22,7 +22,7 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.router.util.TravelTime; import org.matsim.vehicles.Vehicle; @@ -31,18 +31,18 @@ * agent specific parameters are taken into account. */ public class UnknownTravelTime implements TravelTime { - + private final boolean speed; private final boolean speedFactor; private final double value; - - public UnknownTravelTime(String mode, PlansCalcRouteConfigGroup plansCalcRouteConfigGroup) { - - Double speed = plansCalcRouteConfigGroup.getTeleportedModeSpeeds().get(mode); - Double speedFactor = plansCalcRouteConfigGroup.getTeleportedModeFreespeedFactors().get(mode); - + + public UnknownTravelTime(String mode, RoutingConfigGroup routingConfigGroup) { + + Double speed = routingConfigGroup.getTeleportedModeSpeeds().get(mode); + Double speedFactor = routingConfigGroup.getTeleportedModeFreespeedFactors().get(mode); + if (speed != null && speedFactor != null) { - throw new RuntimeException("Speed as well as speed factor was found for mode " + mode + + throw new RuntimeException("Speed as well as speed factor was found for mode " + mode + "! Don't know which should be used. Aborting."); } else if (speed == null && speedFactor == null) { throw new RuntimeException("Neither speed nor speed factor was found for mode " + mode + "! Aborting."); @@ -56,10 +56,10 @@ public UnknownTravelTime(String mode, PlansCalcRouteConfigGroup plansCalcRouteCo this.speedFactor = true; } } - + @Override public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) { - if (speed) return link.getLength() / this.value; + if (speed) return link.getLength() / this.value; else if (speedFactor) return (link.getLength() / link.getFreespeed()) * this.value; else throw new RuntimeException("Neither speed nor speed factor was found! Aborting."); } diff --git a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/UnknownTravelTimeFactory.java b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/UnknownTravelTimeFactory.java index d78e8f2dd60..bf92cb5a15f 100644 --- a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/UnknownTravelTimeFactory.java +++ b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/UnknownTravelTimeFactory.java @@ -20,7 +20,7 @@ package org.matsim.contrib.multimodal.router.util; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.router.util.TravelTime; import jakarta.inject.Provider; @@ -28,15 +28,15 @@ public class UnknownTravelTimeFactory implements Provider { private final String mode; - private final PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; + private final RoutingConfigGroup routingConfigGroup; - public UnknownTravelTimeFactory(String mode, PlansCalcRouteConfigGroup plansCalcRouteConfigGroup) { + public UnknownTravelTimeFactory(String mode, RoutingConfigGroup routingConfigGroup) { this.mode = mode; - this.plansCalcRouteConfigGroup = plansCalcRouteConfigGroup; + this.routingConfigGroup = routingConfigGroup; - Double speed = plansCalcRouteConfigGroup.getTeleportedModeSpeeds().get(mode); - Double speedFactor = plansCalcRouteConfigGroup.getTeleportedModeFreespeedFactors().get(mode); + Double speed = routingConfigGroup.getTeleportedModeSpeeds().get(mode); + Double speedFactor = routingConfigGroup.getTeleportedModeFreespeedFactors().get(mode); if (speed != null && speedFactor != null) { throw new RuntimeException("Speed as well as speed factor was found for mode " + mode + @@ -48,7 +48,7 @@ public UnknownTravelTimeFactory(String mode, PlansCalcRouteConfigGroup plansCalc @Override public TravelTime get() { - return new UnknownTravelTime(this.mode, this.plansCalcRouteConfigGroup); + return new UnknownTravelTime(this.mode, this.routingConfigGroup); } } diff --git a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/WalkTravelTime.java b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/WalkTravelTime.java index 34bbf805a7e..773a4fa81fb 100644 --- a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/WalkTravelTime.java +++ b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/WalkTravelTime.java @@ -26,8 +26,7 @@ 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.api.core.v01.population.Person; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.population.PersonUtils; import org.matsim.core.router.util.TravelTime; import org.matsim.vehicles.Vehicle; @@ -40,33 +39,33 @@ /** * Data to calculate a person's travel time on a link is taken from: - * Weidmann, Ulrich (1992) Transporttechnik der Fussgänger - Transporttechnische Eigenschaften des Fussgängerverkehrs, + * Weidmann, Ulrich (1992) Transporttechnik der Fussgänger - Transporttechnische Eigenschaften des Fussgängerverkehrs, * Literaturauswertung, Schriftenreihe des IVT (90), Institut für Verkehrsplanung und Transportsysteme, Zürich. - * + * * Age data from 0..3 and from 80..100 is extrapolated. */ public class WalkTravelTime implements TravelTime { private static final Logger log = LogManager.getLogger(WalkTravelTime.class); - + /* * Cache variables for each thread accessing the object separately. */ /*package*/ final ThreadLocal personCache; /*package*/ final ThreadLocal personFactorCache; private final ThreadLocal personWalkSpeedCache; - + // Map shared between all threads accessing this object. /*package*/ final Map personFactors; - + private final double referenceWalkSpeed; // 1.34 according to Weidmann, [m/s] - + private final double maleScaleFactor = 1.41 / 1.34; // according to Weidmann private final double femaleScaleFactor = 1.27 / 1.34; // according to Weidmann - + private final double weidmannReferenceWalkSpeed = 1.34; // 1.34 according to Weidmann, [m/s] private final double weidmannScatterStandardDeviation = 0.26; // 0.26 according to Weidmann, [m/s] - + // age from 0 .. 100 private final double[] ageFactors = { 0.1940, 0.2776, 0.3582, 0.4328, 0.5075, 0.5821, 0.6567, 0.7090, 0.7687, 0.8284, @@ -96,47 +95,47 @@ public class WalkTravelTime implements TravelTime { 1.0133, 1.0033, 0.9922, 0.9801, 0.9670, 0.9530, 0.9382, 0.9227, 0.9067, 0.8903, 0.8737, 0.8570, 0.8405, 0.8242, 0.8085, 0.7935, 0.7795, 0.7667, 0.7555, 0.7460, 0.7386}; - + private final AtomicBoolean warnGender = new AtomicBoolean(true); private final AtomicBoolean warnSlopeRange = new AtomicBoolean(true); private final AtomicBoolean warnSlopeNotFound = new AtomicBoolean(true); private final AtomicBoolean warnAge = new AtomicBoolean(true); - + private final AtomicInteger genderWarnCount = new AtomicInteger(0); private final AtomicInteger slopeRangeWarnCount = new AtomicInteger(0); private final AtomicInteger slopeNotFoundWarnCount = new AtomicInteger(0); private final AtomicInteger ageWarnCount = new AtomicInteger(0); - + private final Map, Double> linkSlopes; - - public WalkTravelTime(PlansCalcRouteConfigGroup plansCalcGroup, Map, Double> linkSlopes) { + + public WalkTravelTime(RoutingConfigGroup plansCalcGroup, Map, Double> linkSlopes) { this.referenceWalkSpeed = plansCalcGroup.getTeleportedModeSpeeds().get(TransportMode.walk); this.personCache = new ThreadLocal<>(); this.personFactorCache = new ThreadLocal<>(); this.personWalkSpeedCache = new ThreadLocal<>(); - + this.personFactors = new ConcurrentHashMap<>(); this.linkSlopes = linkSlopes; } - + // when used for transit_walk /*package*/ WalkTravelTime(double referenceWalkSpeed, Map, Double> linkSlopes) { this.referenceWalkSpeed = referenceWalkSpeed; this.personCache = new ThreadLocal<>(); this.personFactorCache = new ThreadLocal<>(); this.personWalkSpeedCache = new ThreadLocal<>(); - + this.personFactors = new ConcurrentHashMap<>(); this.linkSlopes = linkSlopes; } - public WalkTravelTime(PlansCalcRouteConfigGroup plansCalcGroup) { + public WalkTravelTime(RoutingConfigGroup plansCalcGroup) { this(plansCalcGroup, null); } - + @Override - public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) { + public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) { setPerson(person); double slope = getSlope(link); double slopeFactor = getSlopeFactor(slope); @@ -147,7 +146,7 @@ public double getLinkTravelTime(Link link, double time, Person person, Vehicle v /*package*/ double getSlopeFactor(double slope) { double slopeFactor; - + if (slope > 80.0) { if (slopeRangeWarnCount.get() < 10) { incSlopeRangeWarnCount("Slope is out of expected range (-40% .. -80%). Found slope of " + slope + ". Use 80.0 instead."); @@ -159,18 +158,18 @@ public double getLinkTravelTime(Link link, double time, Person person, Vehicle v } slope = -40.0; } - slopeFactor = slopeFactors[-(int)Math.round(slope) + 80]; + slopeFactor = slopeFactors[-(int)Math.round(slope) + 80]; return slopeFactor; } - + /* * Returns the slope of a link in %. */ /*package*/ final double getSlope(Link link) { - + // if no slope information is available if (this.linkSlopes == null) return 0.0; - + Double slope = this.linkSlopes.get(link.getId()); if (slope == null) { incSlopeNotFoundWarnCount("No slope information for link " + link.getId().toString() + @@ -186,7 +185,7 @@ private void incGenderWarnCount(String text) { if (genderWarnCount.get() >= 10) warnGender.set(false); } } - + private void incSlopeRangeWarnCount(String text) { slopeRangeWarnCount.incrementAndGet(); if (warnSlopeRange.get()) { @@ -194,7 +193,7 @@ private void incSlopeRangeWarnCount(String text) { if (slopeRangeWarnCount.get() >= 10) warnSlopeRange.set(false); } } - + private void incSlopeNotFoundWarnCount(String text) { slopeNotFoundWarnCount.incrementAndGet(); if (warnSlopeNotFound.get()) { @@ -202,7 +201,7 @@ private void incSlopeNotFoundWarnCount(String text) { if (slopeNotFoundWarnCount.get() >= 10) warnSlopeNotFound.set(false); } } - + private void incAgeWarnCount(String text) { ageWarnCount.incrementAndGet(); if (warnAge.get()) { @@ -210,19 +209,19 @@ private void incAgeWarnCount(String text) { if (ageWarnCount.get() >= 10) warnAge.set(false); } } - + private void printWarning(String text, int count) { if (count >= 10) log.warn(text + " No further warnings from this type will be given!"); else log.warn(text); } - + /*package*/ void setPerson(Person person) { - /* + /* * Only recalculate the person's walk speed factor if * the person has changed and is not in the map. */ if (this.personCache.get() != null && person.getId().equals(this.personCache.get().getId())) return; - + /* * If the person's walk speed is already in the map, use that value. * Otherwise calculate it and add it to the map. @@ -235,7 +234,7 @@ private void printWarning(String text, int count) { this.personWalkSpeedCache.set(this.referenceWalkSpeed * personFactor); return; } - + double scatterFactor; double ageFactor = 1.0; double genderFactor = 1.0; @@ -244,7 +243,7 @@ private void printWarning(String text, int count) { Random random = new Random(); random.setSeed(person.getId().toString().hashCode()); for (int i = 0; i < 5; i++) random.nextDouble(); - + /* * Limit scatter factor to +/- 4 times the standard deviation. * Therefore, the scatter factor is 0.224 ... 1.777 @@ -257,10 +256,10 @@ private void printWarning(String text, int count) { scatterSpeed = weidmannReferenceWalkSpeed + scatterLimit; } scatterFactor = scatterSpeed / weidmannReferenceWalkSpeed; - + if (person instanceof Person) { Person p = person; - + // get gender factor if (PersonUtils.getSex(p) == null) { if (genderWarnCount.get() < 10) { @@ -273,9 +272,9 @@ private void printWarning(String text, int count) { incGenderWarnCount("Person's gender is not defined. Ignoring gender dependent walk speed factor."); } } - + Integer age = PersonUtils.getAge(p); - + if (age == null) { if (ageWarnCount.get() < 10) { incAgeWarnCount("Person's age is not defined. Ignoring age dependent walk speed factor."); @@ -295,12 +294,12 @@ else if (age < 0) { ageFactor = ageFactors[PersonUtils.getAge(p)]; } } - + double personFactor = scatterFactor * ageFactor * genderFactor; this.personCache.set(person); this.personFactorCache.set(personFactor); this.personWalkSpeedCache.set(this.referenceWalkSpeed * personFactor); - + this.personFactors.put(person.getId(), personFactor); } diff --git a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/WalkTravelTimeFactory.java b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/WalkTravelTimeFactory.java index 6498a1524b7..8520d65f3c3 100644 --- a/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/WalkTravelTimeFactory.java +++ b/contribs/multimodal/src/main/java/org/matsim/contrib/multimodal/router/util/WalkTravelTimeFactory.java @@ -23,7 +23,7 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.router.util.TravelTime; import jakarta.inject.Provider; @@ -31,26 +31,26 @@ public class WalkTravelTimeFactory implements Provider { - private final PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; + private final RoutingConfigGroup routingConfigGroup; private final Map, Double> linkSlopes; // slope information in % - public WalkTravelTimeFactory(PlansCalcRouteConfigGroup plansCalcRouteConfigGroup) { - this(plansCalcRouteConfigGroup, null); + public WalkTravelTimeFactory(RoutingConfigGroup routingConfigGroup) { + this(routingConfigGroup, null); } - public WalkTravelTimeFactory(PlansCalcRouteConfigGroup plansCalcRouteConfigGroup, - Map, Double> linkSlopes) { - this.plansCalcRouteConfigGroup = plansCalcRouteConfigGroup; + public WalkTravelTimeFactory(RoutingConfigGroup routingConfigGroup, + Map, Double> linkSlopes) { + this.routingConfigGroup = routingConfigGroup; this.linkSlopes = linkSlopes; - if (plansCalcRouteConfigGroup.getTeleportedModeSpeeds().get(TransportMode.walk) == null) { + if (routingConfigGroup.getTeleportedModeSpeeds().get(TransportMode.walk) == null) { throw new RuntimeException("No speed was found for mode walk! Aborting."); } } @Override public TravelTime get() { - return new WalkTravelTime(this.plansCalcRouteConfigGroup, this.linkSlopes); + return new WalkTravelTime(this.routingConfigGroup, this.linkSlopes); } } diff --git a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/MultiModalControlerListenerTest.java b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/MultiModalControlerListenerTest.java index ad0fd81a5cb..28c96b9e39d 100644 --- a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/MultiModalControlerListenerTest.java +++ b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/MultiModalControlerListenerTest.java @@ -52,8 +52,8 @@ import org.matsim.contrib.multimodal.tools.PrepareMultiModalScenario; 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.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.config.groups.PlansConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; @@ -69,7 +69,7 @@ public class MultiModalControlerListenerTest { private static final Logger log = LogManager.getLogger(MultiModalControlerListenerTest.class); - @Rule + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); @SuppressWarnings("static-method") @@ -89,10 +89,10 @@ static void runSimpleScenario(int numberOfThreads) { config.qsim().setEndTime(24 * 3600); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); // doesn't matter - MultiModalModule sets the mobsim unconditionally. it just can't be something // which the ControlerDefaultsModule knows about. Try it, you will get an error. Quite safe. - config.controler().setMobsim("myMobsim"); + config.controller().setMobsim("myMobsim"); MultiModalConfigGroup multiModalConfigGroup = new MultiModalConfigGroup(); multiModalConfigGroup.setMultiModalSimulationEnabled(true); @@ -102,19 +102,19 @@ static void runSimpleScenario(int numberOfThreads) { ActivityParams homeParams = new ActivityParams("home"); homeParams.setTypicalDuration(16*3600); - config.planCalcScore().addActivityParams(homeParams); + config.scoring().addActivityParams(homeParams); // set default walk speed; according to Weidmann 1.34 [m/s] double defaultWalkSpeed = 1.34; - config.plansCalcRoute().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); + config.routing().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); // set default bike speed; Parkin and Rotheram according to 6.01 [m/s] double defaultBikeSpeed = 6.01; - config.plansCalcRoute().setTeleportedModeSpeed(TransportMode.bike, defaultBikeSpeed); + config.routing().setTeleportedModeSpeed(TransportMode.bike, defaultBikeSpeed); // set unkown mode speed double unknownModeSpeed = 2.0; - config.plansCalcRoute().setTeleportedModeSpeed("other", unknownModeSpeed); + config.routing().setTeleportedModeSpeed("other", unknownModeSpeed); config.travelTimeCalculator().setFilterModes(true); @@ -164,10 +164,10 @@ static void runSimpleScenario(int numberOfThreads) { scenario.getPopulation().addPerson(createPerson(scenario, "p3", "other")); Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setWriteEventsInterval(0); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setWriteEventsInterval(0); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); // controler listener that initializes the multi-modal simulation controler.addOverridingModule(new MultiModalModule()); @@ -211,11 +211,11 @@ void runBerlinScenario(int numberOfThreads) { Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("berlin"), "config.xml")); ConfigUtils.loadConfig(config, inputDir + "config_berlin_multimodal.xml"); config.addModule(new MultiModalConfigGroup()); - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); // doesn't matter - MultiModalModule sets the mobsim unconditionally. it just can't be something // which the ControlerDefaultsModule knows about. Try it, you will get an error. Quite safe. - config.controler().setMobsim("myMobsim"); + config.controller().setMobsim("myMobsim"); // config.qsim().setRemoveStuckVehicles(true); // but why? kai, feb'16 config.qsim().setRemoveStuckVehicles(false); @@ -251,10 +251,10 @@ void runBerlinScenario(int numberOfThreads) { PrepareMultiModalScenario.run(scenario); Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setWriteEventsInterval(0); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setWriteEventsInterval(0); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); // controler listener that initializes the multi-modal simulation controler.addOverridingModule(new MultiModalModule()); @@ -268,16 +268,16 @@ public void install() { LinkModeChecker linkModeChecker = new LinkModeChecker(controler.getScenario().getNetwork()); controler.getEvents().addHandler(linkModeChecker); - + controler.run(); - - /* NOTE: When I introduced access/egress legs, nearly everything in the following (besides bikeCount) changed. + + /* NOTE: When I introduced access/egress legs, nearly everything in the following (besides bikeCount) changed. * After setting removeStuckVehicles from true to false, the counts were stable. So with access/egress legs, a * different number of vehicles got lost ... which makes sense, because they enter/leave the traffic at different times. - * + * * Also, after not losing vehicles vehicles any more, the travel times for the uncongested modes bike and walk were stable. * Predictably, the travel time for the congested mode changes. - * + * * kai, feb'16 */ @@ -310,7 +310,7 @@ public void install() { LogManager.getLogger( this.getClass() ).warn( "carTravelTime: " + carTravelTime ) ; LogManager.getLogger( this.getClass() ).warn( "bikeTravelTime: " + bikeTravelTime ) ; LogManager.getLogger( this.getClass() ).warn( "walkTravelTime: " + walkTravelTime ) ; - if ( !config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { Assert.assertEquals( "unexpected total travel time for car mode with number of threads "+numberOfThreads, 1.1186864E8, carTravelTime, MatsimTestUtils.EPSILON); @@ -407,7 +407,7 @@ public void handleEvent(VehicleEntersTrafficEvent event) { public void handleEvent(LinkLeaveEvent event) { Link link = this.network.getLinks().get(event.getLinkId()); String mode = this.vehModes.get(event.getVehicleId()); - + if (!link.getAllowedModes().contains(mode)) { log.error(mode); } diff --git a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/MultiModalTripRouterTest.java b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/MultiModalTripRouterTest.java index 74c236690d5..45c6e6ece37 100644 --- a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/MultiModalTripRouterTest.java +++ b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/MultiModalTripRouterTest.java @@ -39,7 +39,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.AbstractModule; import org.matsim.core.controler.Injector; import org.matsim.core.events.EventsUtils; @@ -66,23 +66,23 @@ public class MultiModalTripRouterTest { @Test public void testRouteLeg() { - + final Config config = ConfigUtils.createConfig(); - config.plansCalcRoute().addParam("teleportedModeSpeed_bike", "6.01"); - config.plansCalcRoute().addParam("teleportedModeFreespeedFactor_pt", "2.0"); - config.plansCalcRoute().addParam("teleportedModeSpeed_ride", "15.0"); - config.plansCalcRoute().addParam("teleportedModeSpeed_undefined", "13.88888888888889"); - config.plansCalcRoute().addParam("teleportedModeSpeed_walk", "1.34"); + config.routing().addParam("teleportedModeSpeed_bike", "6.01"); + config.routing().addParam("teleportedModeFreespeedFactor_pt", "2.0"); + config.routing().addParam("teleportedModeSpeed_ride", "15.0"); + config.routing().addParam("teleportedModeSpeed_undefined", "13.88888888888889"); + config.routing().addParam("teleportedModeSpeed_walk", "1.34"); - config.planCalcScore().addModeParams( new PlanCalcScoreConfigGroup.ModeParams( TransportMode.ride ) ); + config.scoring().addModeParams( new ScoringConfigGroup.ModeParams( TransportMode.ride ) ); final Scenario scenario = ScenarioUtils.createScenario(config); - + createNetwork(scenario); - + MultiModalConfigGroup multiModalConfigGroup = new MultiModalConfigGroup(); config.addModule(multiModalConfigGroup); multiModalConfigGroup.setSimulatedModes(TransportMode.bike + ", " + TransportMode.walk + ", " + TransportMode.ride + ", " + TransportMode.pt); - + Map, Double> linkSlopes = new LinkSlopesReader().getLinkSlopes(multiModalConfigGroup, scenario.getNetwork()); /* @@ -90,7 +90,7 @@ public void testRouteLeg() { * - defaultDelegateFactory for the QNetsim modes * - multiModalTripRouterFactory for the multi-modal modes * - transitTripRouterFactory for transit trips - * + * * Note that a FastDijkstraFactory is used for the multiModalTripRouterFactory * since ... * - only "fast" router implementations handle sub-networks correct @@ -116,14 +116,14 @@ public void install() { TripRouter tripRouter = injector.getInstance(TripRouter.class); PlanRouter planRouter = new PlanRouter(tripRouter, injector.getInstance(TimeInterpretation.class)); - + /* * Create travel time object */ // pre-initialize the travel time calculator to be able to use it in the wrapper // TravelTimeCalculatorFactory travelTimeCalculatorFactory = new TravelTimeCalculatorFactoryImpl(); // TravelTimeCalculator travelTimeCalculator = travelTimeCalculatorFactory.createTravelTimeCalculator(scenario.getNetwork(), config.travelTimeCalculator()); - + // PlansCalcRouteConfigGroup configGroup = config.plansCalcRoute(); // Map multiModalTravelTimes = new HashMap(); // multiModalTravelTimes.put(TransportMode.car, travelTimeCalculator.getLinkTravelTimes()); @@ -131,16 +131,16 @@ public void install() { // multiModalTravelTimes.put(TransportMode.bike, new BikeTravelTimeOld(configGroup, new WalkTravelTimeOld(configGroup))); // multiModalTravelTimes.put(TransportMode.ride, new RideTravelTime(travelTimeCalculator.getLinkTravelTimes(), new WalkTravelTimeOld(configGroup))); // multiModalTravelTimes.put(TransportMode.pt, new PTTravelTime(configGroup, travelTimeCalculator.getLinkTravelTimes(), new WalkTravelTimeOld(configGroup))); - + // Map legRouters = createLegRouters(config, scenario.getNetwork(), multiModalTravelTimes); - - + + /* * check car mode */ checkMode(scenario, TransportMode.car, planRouter); - + /* * check pt mode */ @@ -150,47 +150,47 @@ public void install() { * check walk mode */ checkMode(scenario, TransportMode.walk, planRouter); - + /* * check bike mode */ checkMode(scenario, TransportMode.bike, planRouter); - + /* * check ride mode */ checkMode(scenario, TransportMode.ride, planRouter); } - + private void checkMode(Scenario scenario, String transportMode, PlanRouter planRouter) { // XXX transportMode parameter is NOT USED, hence this test is NOT DOING WHAT IT SHOULD! td oct 15 Person person = createPerson(scenario); planRouter.run(person); checkRoute((Leg) person.getSelectedPlan().getPlanElements().get(1), scenario.getNetwork()); } - + private Person createPerson(Scenario scenario) { - + Person person = scenario.getPopulation().getFactory().createPerson(Id.create("person", Person.class)); Plan plan = scenario.getPopulation().getFactory().createPlan(); person.addPlan(plan); - + Activity startActivity = scenario.getPopulation().getFactory().createActivityFromLinkId("start", Id.create("startLink", Link.class)); startActivity.setEndTime(8*3600); Leg leg = scenario.getPopulation().getFactory().createLeg(TransportMode.car); Activity endActivity = scenario.getPopulation().getFactory().createActivityFromLinkId("end", Id.create("endLink", Link.class)); - + plan.addActivity(startActivity); plan.addLeg(leg); plan.addActivity(endActivity); - + return person; } - - + + private void checkRoute(Leg leg, Network network) { NetworkRoute route = (NetworkRoute) leg.getRoute(); - + for (Id id : route.getLinkIds()) { Link link = network.getLinks().get(id); boolean validMode = false; @@ -201,10 +201,10 @@ private void checkRoute(Leg leg, Network network) { } } Assert.assertTrue(validMode); - + } } - + private void createNetwork(Scenario scenario) { /* @@ -223,12 +223,12 @@ private void createNetwork(Scenario scenario) { Node joinNode = scenario.getNetwork().getFactory().createNode(Id.create("joinNode", Node.class), new Coord(1.0, 0.0)); Node endNode = scenario.getNetwork().getFactory().createNode(Id.create("endNode", Node.class), new Coord(0.0, 0.0)); - + /* * create links */ Link startLink = scenario.getNetwork().getFactory().createLink(Id.create("startLink", Link.class), startNode, splitNode); - + Link toCarLink = scenario.getNetwork().getFactory().createLink(Id.create("toCarLink", Link.class), splitNode, carNode); Link toPtLink = scenario.getNetwork().getFactory().createLink(Id.create("toPtLink", Link.class), splitNode, ptNode); Link toWalkLink = scenario.getNetwork().getFactory().createLink(Id.create("toWalkLink", Link.class), splitNode, walkNode); @@ -240,9 +240,9 @@ private void createNetwork(Scenario scenario) { Link fromWalkLink = scenario.getNetwork().getFactory().createLink(Id.create("fromWalkLink", Link.class), walkNode, joinNode); Link fromBikeLink = scenario.getNetwork().getFactory().createLink(Id.create("fromBikeLink", Link.class), bikeNode, joinNode); Link fromRideLink = scenario.getNetwork().getFactory().createLink(Id.create("fromRideLink", Link.class), rideNode, joinNode); - + Link endLink = scenario.getNetwork().getFactory().createLink(Id.create("endLink", Link.class), joinNode, endNode); - + /* * set link parameter */ @@ -258,7 +258,7 @@ private void createNetwork(Scenario scenario) { fromBikeLink.setLength(10.0); fromRideLink.setLength(10.0); endLink.setLength(1.0); - + startLink.setFreespeed(120.0/3.6); toCarLink.setFreespeed(120.0/3.6); toPtLink.setFreespeed(120.0/3.6); @@ -282,7 +282,7 @@ private void createNetwork(Scenario scenario) { fromWalkLink.setAllowedModes(createSet(new String[]{TransportMode.walk})); fromBikeLink.setAllowedModes(createSet(new String[]{TransportMode.bike})); fromRideLink.setAllowedModes(createSet(new String[]{TransportMode.ride})); - + /* * add nodes to network */ @@ -295,7 +295,7 @@ private void createNetwork(Scenario scenario) { scenario.getNetwork().addNode(rideNode); scenario.getNetwork().addNode(joinNode); scenario.getNetwork().addNode(endNode); - + /* * add links to network */ @@ -310,9 +310,9 @@ private void createNetwork(Scenario scenario) { scenario.getNetwork().addLink(fromWalkLink); scenario.getNetwork().addLink(fromBikeLink); scenario.getNetwork().addLink(fromRideLink); - scenario.getNetwork().addLink(endLink); + scenario.getNetwork().addLink(endLink); } - + private Set createSet(String[] entries) { Set set = new HashSet<>(); Collections.addAll(set, entries); diff --git a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/pt/MultiModalPTCombinationTest.java b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/pt/MultiModalPTCombinationTest.java index e4398aaaf6b..c4bb7388e2c 100644 --- a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/pt/MultiModalPTCombinationTest.java +++ b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/pt/MultiModalPTCombinationTest.java @@ -49,8 +49,8 @@ import org.matsim.contrib.multimodal.MultiModalModule; import org.matsim.contrib.multimodal.config.MultiModalConfigGroup; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.events.algorithms.Vehicle2DriverEventHandler; import org.matsim.core.events.handler.BasicEventHandler; @@ -59,72 +59,72 @@ public class MultiModalPTCombinationTest { private static final Logger log = LogManager.getLogger(MultiModalPTCombinationTest.class); - + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - + /** * Two things are tested here: * - Multi-modal simulation can handle TransitAgents (previously, the TransitAgent class did not implement * the HasPerson interface. As a result, the multi-modal simulation crashed since it could not access * the person). * - Multi-modal simulation can handle transit_walk legs (not yet ready...). - * ---> in nov'19 we are trying to replace transit_walk by normal walk and routingMode=pt, so this test is + * ---> in nov'19 we are trying to replace transit_walk by normal walk and routingMode=pt, so this test is * probably no longer very useful, there is no more special walk mode for pt agents - gl-nov'19 */ @Test public void testMultiModalPtCombination() { - + Fixture f = new Fixture(); f.init(); - + // Person ptPerson = f.createPersonAndAdd(f.scenario, "0", TransportMode.transit_walk); Person ptPerson = f.createPersonAndAdd(f.scenario, "0", TransportMode.walk, TransportMode.pt); Person walkPerson = f.createPersonAndAdd(f.scenario, "1", TransportMode.walk, TransportMode.walk); - + Scenario scenario = f.scenario; Config config = scenario.getConfig(); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - + config.controller().setOutputDirectory(utils.getOutputDirectory()); + MultiModalConfigGroup mmcg = new MultiModalConfigGroup(); mmcg.setMultiModalSimulationEnabled(true); mmcg.setSimulatedModes(TransportMode.walk + "," + TransportMode.transit_walk);//TODO: is this still useful if no agent can still use transit_walk? config.addModule(mmcg); - + config.qsim().setEndTime(24*3600); - - config.controler().setLastIteration(0); + + config.controller().setLastIteration(0); // doesn't matter - MultiModalModule sets the mobsim unconditionally. it just can't be something // which the ControlerDefaultsModule knows about. Try it, you will get an error. Quite safe. - config.controler().setMobsim("myMobsim"); + config.controller().setMobsim("myMobsim"); ActivityParams homeParams = new ActivityParams("home"); homeParams.setTypicalDuration(16*3600); - config.planCalcScore().addActivityParams(homeParams); - + config.scoring().addActivityParams(homeParams); + // set default walk speed; according to Weidmann 1.34 [m/s] double defaultWalkSpeed = 1.34; - config.plansCalcRoute().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); - final PlansCalcRouteConfigGroup.TeleportedModeParams pt = new PlansCalcRouteConfigGroup.TeleportedModeParams( TransportMode.pt ); + config.routing().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); + final RoutingConfigGroup.TeleportedModeParams pt = new RoutingConfigGroup.TeleportedModeParams( TransportMode.pt ); pt.setTeleportedModeFreespeedFactor( 2.0 ); - config.plansCalcRoute().addParameterSet( pt ); + config.routing().addParameterSet( pt ); config.travelTimeCalculator().setFilterModes(true); Controler controler = new Controler(scenario); - 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.setOverwriteFiles(true); - + controler.addOverridingModule(new MultiModalModule()); LinkModeChecker linkModeChecker = new LinkModeChecker(scenario.getNetwork()); controler.getEvents().addHandler(linkModeChecker); - + controler.run(); - + /* * Assume that the agent's plan was changed from "home-pt-home" to * "home-transit_walk-pt_interact-pt-pt_interact-transit_walk-home" @@ -133,12 +133,12 @@ public void testMultiModalPtCombination() { Assert.assertEquals(ptPlan.getPlanElements().toString(), 7, ptPlan.getPlanElements().size()); Plan walkPlan = walkPerson.getSelectedPlan(); - if ( !config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { Assert.assertEquals(walkPlan.getPlanElements().toString(), 7, walkPlan.getPlanElements().size()); } else { Assert.assertEquals(walkPlan.getPlanElements().toString(), 3, walkPlan.getPlanElements().size()); } - + /* * These tests fail since the TransitRouter (?) does not create NetworkRoutes. * As a result, the multi-modal simulation removes the pt agent from the simulation. @@ -146,16 +146,16 @@ public void testMultiModalPtCombination() { // assume that the transit_walk legs have network routes // Assert.assertEquals(true, ((Leg) plan.getPlanElements().get(1)).getRoute() instanceof NetworkRoute); // Assert.assertEquals(true, ((Leg) plan.getPlanElements().get(5)).getRoute() instanceof NetworkRoute); - + // assume that the number of arrival events is correct // Assert.assertEquals(4, linkModeChecker.arrivalCount); - + // assume that the number of link left events is correct // Assert.assertEquals(8, linkModeChecker.linkLeftCount); } - - + + private static class LinkModeChecker implements BasicEventHandler, LinkLeaveEventHandler, PersonDepartureEventHandler, PersonArrivalEventHandler, VehicleEntersTrafficEventHandler, VehicleLeavesTrafficEventHandler { @@ -164,29 +164,29 @@ private static class LinkModeChecker implements BasicEventHandler, LinkLeaveEven private final Map, Double> departures = new HashMap<>(); final Map leftCountPerMode = new HashMap<>(); final Map travelTimesPerMode = new HashMap<>(); - + private Vehicle2DriverEventHandler delegate = new Vehicle2DriverEventHandler(); - + public LinkModeChecker(Network network) { this.network = network; - + leftCountPerMode.put(TransportMode.pt, 0); leftCountPerMode.put(TransportMode.car, 0); leftCountPerMode.put(TransportMode.walk, 0); leftCountPerMode.put(TransportMode.transit_walk, 0); - + travelTimesPerMode.put(TransportMode.pt, 0.0); travelTimesPerMode.put(TransportMode.car, 0.0); travelTimesPerMode.put(TransportMode.walk, 0.0); travelTimesPerMode.put(TransportMode.transit_walk, 0.0); } - + @Override public void reset(int iteration) { delegate.reset(iteration); // nothing else to do here } - + @Override public void handleEvent(PersonDepartureEvent event) { this.modes.put(event.getPersonId(), event.getLegMode()); @@ -197,14 +197,14 @@ public void handleEvent(PersonDepartureEvent event) { public void handleEvent(LinkLeaveEvent event) { Link link = this.network.getLinks().get(event.getLinkId()); Id driverId = delegate.getDriverOfVehicle(event.getVehicleId()); - + if (!link.getAllowedModes().contains(this.modes.get(driverId))) { log.error("Found mode " + this.modes.get(driverId) + " on link " + link.getId()); } - + // assume that the agent is allowed to travel on the link Assert.assertEquals(true, link.getAllowedModes().contains(this.modes.get(driverId))); - + String mode = this.modes.get(driverId); int count = this.leftCountPerMode.get(mode); this.leftCountPerMode.put(mode, count + 1); @@ -216,7 +216,7 @@ public void handleEvent(PersonArrivalEvent event) { if ( mode.contains(TransportMode.non_network_walk ) || mode.contains(TransportMode.non_network_walk ) ) { return ; } - + double tripTravelTime = event.getTime() - this.departures.remove(event.getPersonId()); Double modeTravelTime = this.travelTimesPerMode.get(mode); if ( modeTravelTime==null ) { diff --git a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/router/util/BikeTravelTimeTest.java b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/router/util/BikeTravelTimeTest.java index 412825f7af3..7f95d342870 100644 --- a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/router/util/BikeTravelTimeTest.java +++ b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/router/util/BikeTravelTimeTest.java @@ -75,11 +75,11 @@ public class BikeTravelTimeTest { // set default walk speed; according to Weidmann 1.34 [m/s] double defaultWalkSpeed = 1.34; - scenario.getConfig().plansCalcRoute().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); + scenario.getConfig().routing().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); // set default bike speed; Prakin and Rotheram according to 6.01 [m/s] double defaultBikeSpeed = 6.01; - scenario.getConfig().plansCalcRoute().setTeleportedModeSpeed(TransportMode.bike, defaultBikeSpeed); + scenario.getConfig().routing().setTeleportedModeSpeed(TransportMode.bike, defaultBikeSpeed); BikeTravelTime bikeTravelTime; @@ -88,7 +88,7 @@ public class BikeTravelTimeTest { double calculatedTravelTime; // reference speed * person factor * slope factor - bikeTravelTime = new BikeTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + bikeTravelTime = new BikeTravelTime(scenario.getConfig().routing(), linkSlopes); calculatedTravelTime = bikeTravelTime.getLinkTravelTime(link, 0.0, person, null); speed = defaultBikeSpeed * bikeTravelTime.personFactorCache.get() * 1.0; expectedTravelTime = link.getLength() / speed; @@ -98,7 +98,7 @@ public class BikeTravelTimeTest { // increase age PersonUtils.setAge(person, 80); - bikeTravelTime = new BikeTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + bikeTravelTime = new BikeTravelTime(scenario.getConfig().routing(), linkSlopes); calculatedTravelTime = bikeTravelTime.getLinkTravelTime(link, 0.0, person, null); speed = defaultBikeSpeed * bikeTravelTime.personFactorCache.get() * 1.0; expectedTravelTime = link.getLength() / speed; @@ -108,7 +108,7 @@ public class BikeTravelTimeTest { // change gender PersonUtils.setSex(person, "f"); - bikeTravelTime = new BikeTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + bikeTravelTime = new BikeTravelTime(scenario.getConfig().routing(), linkSlopes); calculatedTravelTime = bikeTravelTime.getLinkTravelTime(link, 0.0, person, null); speed = defaultBikeSpeed * bikeTravelTime.personFactorCache.get() * 1.0; expectedTravelTime = link.getLength() / speed; @@ -120,7 +120,7 @@ public class BikeTravelTimeTest { h2 = 0.1; slope = 100 * (h2 - h1) / link.getLength(); linkSlopes.put(link.getId(), slope); - bikeTravelTime = new BikeTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + bikeTravelTime = new BikeTravelTime(scenario.getConfig().routing(), linkSlopes); calculatedTravelTime = bikeTravelTime.getLinkTravelTime(link, 0.0, person, null); double slope2 = bikeTravelTime.getSlope(link); @@ -135,7 +135,7 @@ public class BikeTravelTimeTest { h2 = -0.1; slope = 100 * (h2 - h1) / link.getLength(); linkSlopes.put(link.getId(), slope); - bikeTravelTime = new BikeTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + bikeTravelTime = new BikeTravelTime(scenario.getConfig().routing(), linkSlopes); calculatedTravelTime = bikeTravelTime.getLinkTravelTime(link, 0.0, person, null); slope2 = bikeTravelTime.getSlope(link); @@ -150,9 +150,9 @@ public class BikeTravelTimeTest { h2 = 0.25; slope = 100 * (h2 - h1) / link.getLength(); linkSlopes.put(link.getId(), slope); - bikeTravelTime = new BikeTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + bikeTravelTime = new BikeTravelTime(scenario.getConfig().routing(), linkSlopes); - WalkTravelTime walkTravelTime = new WalkTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + WalkTravelTime walkTravelTime = new WalkTravelTime(scenario.getConfig().routing(), linkSlopes); calculatedTravelTime = bikeTravelTime.getLinkTravelTime(link, 0.0, person, null); expectedTravelTime = walkTravelTime.getLinkTravelTime(link, 0.0, person, null); printInfo(person, expectedTravelTime, calculatedTravelTime, slope); @@ -211,7 +211,7 @@ private void printInfo(Person p, double expected, double calculated, double slop double slope = 100 * (h2 - h1) / link.getLength(); linkSlopes.put(link.getId(), slope); - BikeTravelTime bikeTravelTime = new BikeTravelTime(config.plansCalcRoute(), linkSlopes); + BikeTravelTime bikeTravelTime = new BikeTravelTime(config.routing(), linkSlopes); double tt1 = bikeTravelTime.getLinkTravelTime(link, 0.0, p1, null); double tt2 = bikeTravelTime.getLinkTravelTime(link, 0.0, p2, null); diff --git a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/router/util/WalkTravelTimeTest.java b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/router/util/WalkTravelTimeTest.java index 5c79bf513e1..ca66b5a25d5 100644 --- a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/router/util/WalkTravelTimeTest.java +++ b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/router/util/WalkTravelTimeTest.java @@ -75,10 +75,10 @@ public class WalkTravelTimeTest { // set default walk speed; according to Weidmann 1.34 [m/s] double defaultWalkSpeed = 1.34; - scenario.getConfig().plansCalcRoute().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); + scenario.getConfig().routing().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); WalkTravelTime walkTravelTime; - walkTravelTime = new WalkTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + walkTravelTime = new WalkTravelTime(scenario.getConfig().routing(), linkSlopes); double speed; double expectedTravelTime; @@ -95,7 +95,7 @@ public class WalkTravelTimeTest { // increase age PersonUtils.setAge(person, 80); - walkTravelTime = new WalkTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + walkTravelTime = new WalkTravelTime(scenario.getConfig().routing(), linkSlopes); calculatedTravelTime = walkTravelTime.getLinkTravelTime(link, 0.0, person, null); speed = defaultWalkSpeed * walkTravelTime.personFactors.get(person.getId()) * 1.0; expectedTravelTime = link.getLength() / speed; @@ -105,7 +105,7 @@ public class WalkTravelTimeTest { // change gender PersonUtils.setSex(person, "f"); - walkTravelTime = new WalkTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + walkTravelTime = new WalkTravelTime(scenario.getConfig().routing(), linkSlopes); calculatedTravelTime = walkTravelTime.getLinkTravelTime(link, 0.0, person, null); speed = defaultWalkSpeed * walkTravelTime.personFactors.get(person.getId()) * 1.0; expectedTravelTime = link.getLength() / speed; @@ -117,7 +117,7 @@ public class WalkTravelTimeTest { h2 = -0.1; slope = 100 * (h2 - h1) / link.getLength(); linkSlopes.put(link.getId(), slope); - walkTravelTime = new WalkTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + walkTravelTime = new WalkTravelTime(scenario.getConfig().routing(), linkSlopes); double slope2 = walkTravelTime.getSlope(link); double slopeFactor = walkTravelTime.getSlopeFactor(slope2); calculatedTravelTime = walkTravelTime.getLinkTravelTime(link, 0.0, person, null); @@ -131,7 +131,7 @@ public class WalkTravelTimeTest { h2 = 0.1; slope = 100 * (h2 - h1) / link.getLength(); linkSlopes.put(link.getId(), slope); - walkTravelTime = new WalkTravelTime(scenario.getConfig().plansCalcRoute(), linkSlopes); + walkTravelTime = new WalkTravelTime(scenario.getConfig().routing(), linkSlopes); slopeFactor = walkTravelTime.getSlopeFactor(slope); calculatedTravelTime = walkTravelTime.getLinkTravelTime(link, 0.0, person, null); speed = defaultWalkSpeed * walkTravelTime.personFactors.get(person.getId()) * slopeFactor; @@ -192,7 +192,7 @@ private void printInfo(Person p, double expected, double calculated, double slop double slope = 100 * (h2 - h1) / link.getLength(); linkSlopes.put(link.getId(), slope); - WalkTravelTime walkTravelTime = new WalkTravelTime(config.plansCalcRoute(), linkSlopes); + WalkTravelTime walkTravelTime = new WalkTravelTime(config.routing(), linkSlopes); double tt1 = walkTravelTime.getLinkTravelTime(link, 0.0, p1, null); double tt2 = walkTravelTime.getLinkTravelTime(link, 0.0, p2, null); diff --git a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/simengine/StuckAgentTest.java b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/simengine/StuckAgentTest.java index 046c86a2087..ffb8924a15c 100644 --- a/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/simengine/StuckAgentTest.java +++ b/contribs/multimodal/src/test/java/org/matsim/contrib/multimodal/simengine/StuckAgentTest.java @@ -46,7 +46,7 @@ import org.matsim.contrib.multimodal.config.MultiModalConfigGroup; 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.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.Controler; import org.matsim.core.events.handler.BasicEventHandler; import org.matsim.core.population.PersonUtils; @@ -61,21 +61,21 @@ public class StuckAgentTest { private static final Logger log = LogManager.getLogger(StuckAgentTest.class); - - @Rule + + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); @Test public void testStuckEvents() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.qsim().setEndTime(24*3600); - - config.controler().setLastIteration(0); + + config.controller().setLastIteration(0); // doesn't matter - MultiModalModule sets the mobsim unconditionally. it just can't be something // which the ControlerDefaultsModule knows about. Try it, you will get an error. Quite safe. - config.controler().setMobsim("myMobsim"); + config.controller().setMobsim("myMobsim"); MultiModalConfigGroup multiModalConfigGroup = new MultiModalConfigGroup(); @@ -85,19 +85,19 @@ public void testStuckEvents() { ActivityParams homeParams = new ActivityParams("home"); homeParams.setTypicalDuration(16*3600); - config.planCalcScore().addActivityParams(homeParams); - + config.scoring().addActivityParams(homeParams); + // set default walk speed; according to Weidmann 1.34 [m/s] double defaultWalkSpeed = 1.34; - config.plansCalcRoute().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); - + config.routing().setTeleportedModeSpeed(TransportMode.walk, defaultWalkSpeed); + // set default bike speed; Parkin and Rotheram according to 6.01 [m/s] double defaultBikeSpeed = 6.01; - config.plansCalcRoute().setTeleportedModeSpeed(TransportMode.bike, defaultBikeSpeed); - + config.routing().setTeleportedModeSpeed(TransportMode.bike, defaultBikeSpeed); + // set unkown mode speed double unknownModeSpeed = 2.0; - config.plansCalcRoute().setTeleportedModeSpeed("other", unknownModeSpeed); + config.routing().setTeleportedModeSpeed("other", unknownModeSpeed); config.travelTimeCalculator().setFilterModes(true); @@ -108,22 +108,22 @@ public void testStuckEvents() { Node node2 = scenario.getNetwork().getFactory().createNode(Id.create("n2", Node.class), new Coord(2.0, 0.0)); Node node3 = scenario.getNetwork().getFactory().createNode(Id.create("n3", Node.class), new Coord(3.0, 0.0)); Node node4 = scenario.getNetwork().getFactory().createNode(Id.create("n4", Node.class), new Coord(4.0, 0.0)); - + Link link0 = scenario.getNetwork().getFactory().createLink(Id.create("l0", Link.class), node0, node1); Link link1 = scenario.getNetwork().getFactory().createLink(Id.create("l1", Link.class), node1, node2); Link link2 = scenario.getNetwork().getFactory().createLink(Id.create("l2", Link.class), node2, node3); Link link3 = scenario.getNetwork().getFactory().createLink(Id.create("l3", Link.class), node3, node4); - + link0.setLength(10000.0); link1.setLength(10000.0); link2.setLength(10000.0); link3.setLength(10000.0); - + link0.setAllowedModes(CollectionUtils.stringToSet("bike,walk")); link1.setAllowedModes(CollectionUtils.stringToSet("bike,walk")); link2.setAllowedModes(CollectionUtils.stringToSet("bike,walk")); link3.setAllowedModes(CollectionUtils.stringToSet("bike,walk")); - + scenario.getNetwork().addNode(node0); scenario.getNetwork().addNode(node1); scenario.getNetwork().addNode(node2); @@ -133,7 +133,7 @@ public void testStuckEvents() { scenario.getNetwork().addLink(link1); scenario.getNetwork().addLink(link2); scenario.getNetwork().addLink(link3); - + RouteFactory routeFactory = new LinkNetworkRouteFactory(); Route route0 = routeFactory.createRoute(Id.create("l0", Link.class), Id.create("l3", Link.class)); // missing l1 & l2 Route route1 = routeFactory.createRoute(Id.create("l0", Link.class), Id.create("l3", Link.class)); // missing l2 @@ -146,26 +146,26 @@ public void testStuckEvents() { scenario.getPopulation().addPerson(createPerson(scenario, "p2", "walk", null, 8.5*3600)); // regular scenario.getPopulation().addPerson(createPerson(scenario, "p3", "walk", null, 23.5*3600)); // en-route when simulation ends scenario.getPopulation().addPerson(createPerson(scenario, "p4", "walk", null, 24.5*3600)); // departs after simulation has ended - + Controler controler = new Controler(scenario); - 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.addOverridingModule(new MultiModalModule()); EventsCollector collector = new EventsCollector(); controler.getEvents().addHandler(collector); controler.getEvents().addHandler(new EventsPrinter()); - + controler.run(); - + int stuckCnt = 0; int stuckBeforeSimulationEnd = 0; for (Event e : collector.getEvents()) { if (e instanceof PersonStuckEvent) { stuckCnt++; - + if (e.getTime() < config.qsim().getEndTime().seconds()) stuckBeforeSimulationEnd++; } } @@ -173,10 +173,10 @@ public void testStuckEvents() { Assert.assertEquals(2, stuckBeforeSimulationEnd); Assert.assertEquals(4, stuckCnt); } - + private Person createPerson(Scenario scenario, String id, String mode, Route route, double departureTime) { Person person = scenario.getPopulation().getFactory().createPerson(Id.create(id, Person.class)); - + PersonUtils.setAge(person, 20); PersonUtils.setSex(person, "m"); @@ -187,17 +187,17 @@ private Person createPerson(Scenario scenario, String id, String mode, Route rou from.setEndTime(departureTime); leg.setDepartureTime(departureTime); - + Plan plan = scenario.getPopulation().getFactory().createPlan(); plan.addActivity(from); plan.addLeg(leg); plan.addActivity(to); - + person.addPlan(plan); - + return person; } - + // for debugging private static class EventsPrinter implements BasicEventHandler { @@ -217,8 +217,8 @@ public void handleEvent(final Event event) { eventXML.append("\" "); } eventXML.append("/>"); - + log.info(eventXML.toString()); } } -} \ No newline at end of file +} diff --git a/contribs/multimodal/src/test/resources/test/input/org/matsim/contrib/multimodal/MultiModalControlerListenerTest/config_berlin_multimodal.xml b/contribs/multimodal/src/test/resources/test/input/org/matsim/contrib/multimodal/MultiModalControlerListenerTest/config_berlin_multimodal.xml index dd9be970d79..81e2b81f0e8 100644 --- a/contribs/multimodal/src/test/resources/test/input/org/matsim/contrib/multimodal/MultiModalControlerListenerTest/config_berlin_multimodal.xml +++ b/contribs/multimodal/src/test/resources/test/input/org/matsim/contrib/multimodal/MultiModalControlerListenerTest/config_berlin_multimodal.xml @@ -25,18 +25,18 @@ - + - - diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseCalculationOnline.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseCalculationOnline.java index 5be0fa5465b..5a9f11d301e 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseCalculationOnline.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseCalculationOnline.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.noise; @@ -35,24 +35,24 @@ /** - * + * * @author ikaddoura * */ final class NoiseCalculationOnline implements BeforeMobsimListener, AfterMobsimListener, StartupListener { private static final Logger log = LogManager.getLogger(NoiseCalculationOnline.class); - + @Inject private NoiseContext noiseContext; - + @Inject private NoiseTimeTracker timeTracker; - + @Override public void notifyStartup(StartupEvent event) { - NoiseWriter.writeReceiverPoints(noiseContext, event.getServices().getConfig().controler().getOutputDirectory() + "/receiverPoints/", false); + NoiseWriter.writeReceiverPoints(noiseContext, event.getServices().getConfig().controller().getOutputDirectory() + "/receiverPoints/", false); } - + @Override public void notifyBeforeMobsim(BeforeMobsimEvent event) { @@ -60,12 +60,12 @@ public void notifyBeforeMobsim(BeforeMobsimEvent event) { this.noiseContext.getNoiseLinks().clear(); this.noiseContext.getTimeInterval2linkId2noiseLinks().clear(); - + for (NoiseReceiverPoint rp : this.noiseContext.getReceiverPoints().values()) { rp.reset(); } } - + @Override public void notifyAfterMobsim(AfterMobsimEvent event) { timeTracker.computeFinalTimeIntervals(); @@ -75,5 +75,5 @@ public void notifyAfterMobsim(AfterMobsimEvent event) { NoiseContext getNoiseContext() { return noiseContext; } - + } diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseOfflineCalculation.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseOfflineCalculation.java index 62ea785acf9..8f54b37c270 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseOfflineCalculation.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseOfflineCalculation.java @@ -110,10 +110,10 @@ public void run() { EventWriterXML eventWriter = null; if (noiseContext.getNoiseParams().isThrowNoiseEventsAffected() || noiseContext.getNoiseParams().isThrowNoiseEventsCaused()) { String eventsFile; - if (this.scenario.getConfig().controler().getRunId() == null || this.scenario.getConfig().controler().getRunId().equals("")) { + if (this.scenario.getConfig().controller().getRunId() == null || this.scenario.getConfig().controller().getRunId().equals("")) { eventsFile = outputFilePath + "noise.output_events.offline.xml.gz"; } else { - eventsFile = outputFilePath + this.scenario.getConfig().controler().getRunId() + ".noise.output_events.offline.xml.gz"; + eventsFile = outputFilePath + this.scenario.getConfig().controller().getRunId() + ".noise.output_events.offline.xml.gz"; } eventWriter = new EventWriterXML(eventsFile); events.addHandler(eventWriter); @@ -123,10 +123,10 @@ public void run() { log.info("Reading events file..."); MatsimEventsReader reader = new MatsimEventsReader(events); String eventsFile; - if (this.scenario.getConfig().controler().getRunId() == null || this.scenario.getConfig().controler().getRunId().equals("")) { - eventsFile = this.scenario.getConfig().controler().getOutputDirectory() + "output_events.xml.gz"; + if (this.scenario.getConfig().controller().getRunId() == null || this.scenario.getConfig().controller().getRunId().equals("")) { + eventsFile = this.scenario.getConfig().controller().getOutputDirectory() + "output_events.xml.gz"; } else { - eventsFile = this.scenario.getConfig().controler().getOutputDirectory() + this.scenario.getConfig().controler().getRunId() + ".output_events.xml.gz"; + eventsFile = this.scenario.getConfig().controller().getOutputDirectory() + this.scenario.getConfig().controller().getRunId() + ".output_events.xml.gz"; } reader.readFile(eventsFile); log.info("Reading events file... Done."); diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseTimeTracker.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseTimeTracker.java index ff31f713b26..de6589fa205 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseTimeTracker.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseTimeTracker.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.noise; @@ -50,7 +50,7 @@ /** * A handler which computes noise emissions, immisions, affected agent units and damages for each receiver point and time interval. * Throws noise damage events for each affected and causing agent. - * + * * @author ikaddoura * */ @@ -58,12 +58,12 @@ class NoiseTimeTracker implements VehicleEntersTrafficEventHandler, PersonEnters private static final Logger log = LogManager.getLogger(NoiseTimeTracker.class); private static final boolean printLog = true; - + private NoiseContext noiseContext; private String outputDirectory; private int iteration; - + private boolean useCompression = false ; private int cWarn1 = 0; @@ -127,15 +127,15 @@ private void setRelevantLinkInfo() { @Override public void reset(int iteration) { - - String outputDir = noiseContext.getScenario().getConfig().controler().getOutputDirectory(); + + String outputDir = noiseContext.getScenario().getConfig().controller().getOutputDirectory(); if (!outputDir.endsWith("/")) { outputDir = outputDir + "/"; } - + this.outputDirectory = outputDir + "ITERS/" + "it." + iteration + "/"; log.info("Setting the output directory to " + outputDirectory); - + this.iteration = iteration; this.damageCalculation.reset(iteration); this.noiseContext.reset(); @@ -144,16 +144,16 @@ public void reset(int iteration) { rp.reset(); } } - + private void resetCurrentTimeIntervalInfo() { this.noiseContext.getNoiseLinks().clear(); for (NoiseReceiverPoint rp : this.noiseContext.getReceiverPoints().values()) { rp.resetTimeInterval(); } } - + private void processTimeBin() { - + if (printLog) { log.info("##############################################"); } @@ -184,12 +184,12 @@ private void updateActivityInformation() { for (NoiseReceiverPoint rp : this.noiseContext.getReceiverPoints().values()) { for (Id personId : rp.getPersonId2actInfos().keySet()) { rp.getPersonId2actInfos().get(personId).removeIf(personActivityInfo -> personActivityInfo.getEndTime() < (timeBinEnd)); - } + } } } private void computeNoiseForCurrentTimeInterval() { - + if (printLog) { log.info("Calculating noise emissions..."); } @@ -214,7 +214,7 @@ private void computeNoiseForCurrentTimeInterval() { } } } - + private boolean writeOutput() { if (this.noiseContext.getNoiseParams().getWriteOutputIteration() == 0) { return false; @@ -230,7 +230,7 @@ private void updateCurrentTimeInterval() { + this.noiseContext.getNoiseParams().getTimeBinSizeNoiseComputation(); this.noiseContext.setCurrentTimeBinEndTime(newTimeInterval); } - + /* * Emission */ @@ -269,7 +269,7 @@ private void calculateNoiseImmissionsAndDamages() { void computeFinalTimeIntervals() { while (this.noiseContext.getCurrentTimeBinEndTime() <= Math.max(24. * 3600., this.noiseContext.getScenario().getConfig().qsim().getEndTime().orElse(0))) { - processTimeBin(); + processTimeBin(); } } diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseTollTimeDistanceTravelDisutilityFactory.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseTollTimeDistanceTravelDisutilityFactory.java index 684eaf53428..ae2773363d9 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseTollTimeDistanceTravelDisutilityFactory.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseTollTimeDistanceTravelDisutilityFactory.java @@ -19,7 +19,7 @@ * *********************************************************************** */ package org.matsim.contrib.noise; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.router.costcalculators.RandomizingTimeDistanceTravelDisutilityFactory; import org.matsim.core.router.costcalculators.TravelDisutilityFactory; import org.matsim.core.router.util.TravelDisutility; @@ -35,9 +35,9 @@ public final class NoiseTollTimeDistanceTravelDisutilityFactory implements TravelDisutilityFactory { private TravelDisutilityFactory travelDisutilityFactoryDelegate; - + @Inject private NoiseContext noiseContext; - @Inject private PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; + @Inject private RoutingConfigGroup routingConfigGroup; public NoiseTollTimeDistanceTravelDisutilityFactory( TravelDisutilityFactory travelDisutilityFactoryDelegate ) { this.travelDisutilityFactoryDelegate = travelDisutilityFactoryDelegate; @@ -48,12 +48,12 @@ public final TravelDisutility createTravelDisutility(TravelTime timeCalculator) if ( travelDisutilityFactoryDelegate instanceof RandomizingTimeDistanceTravelDisutilityFactory ){ } - + return new NoiseTollTimeDistanceTravelDisutility( travelDisutilityFactoryDelegate.createTravelDisutility(timeCalculator ), - new NoiseTollCalculator(noiseContext), this.noiseContext.getScenario().getConfig().planCalcScore().getMarginalUtilityOfMoney(), - plansCalcRouteConfigGroup.getRoutingRandomness()!=0. + new NoiseTollCalculator(noiseContext), this.noiseContext.getScenario().getConfig().scoring().getMarginalUtilityOfMoney(), + routingConfigGroup.getRoutingRandomness()!=0. ); } - + } diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/ProcessNoiseImmissions.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/ProcessNoiseImmissions.java index 25ad915d084..7010df609cf 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/ProcessNoiseImmissions.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/ProcessNoiseImmissions.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.noise; @@ -31,11 +31,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Envelope; -import org.matsim.analysis.XYTRecord; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.contrib.analysis.vsp.qgis.*; -import org.matsim.core.router.priorityqueue.BinaryMinHeap; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.core.utils.io.IOUtils; import org.matsim.core.utils.misc.Time; @@ -45,7 +43,7 @@ * */ public final class ProcessNoiseImmissions { - + private static final Logger log = LogManager.getLogger(ProcessNoiseImmissions.class); private final double receiverPointGap; @@ -71,12 +69,12 @@ public static void main(String[] args) { ProcessNoiseImmissions readNoiseFile = new ProcessNoiseImmissions(workingDirectory, receiverPointsFile, 100); readNoiseFile.run(); } - + public void run() { String label = "immission"; String outputFile = outputPath + label + "_processed.csv"; - + try { double startTime = 3600.; @@ -84,12 +82,12 @@ public void run() { double endTime = 24. * 3600.; String separator = ";"; for ( double time = startTime ; time <= endTime ; time = time + timeBinSize ) { - + log.info("Reading time bin: " + time); String fileName = workingDirectory + label + "_" + time + ".csv"; BufferedReader br = IOUtils.getBufferedReader(fileName); - + String line = null; line = br.readLine(); @@ -97,11 +95,11 @@ public void run() { int lineCounter = 0; log.info("Reading lines "); while ((line = br.readLine()) != null) { - + if (lineCounter % 10000 == 0.) { log.info("# " + lineCounter); } - + String[] columns = line.split( separator ); Id rp = null; Double value = null; @@ -109,41 +107,41 @@ public void run() { if (column == 0) { rp = Id.create(columns[column], ReceiverPoint.class); } else if (column == 1) { - value = Double.valueOf(columns[column]); + value = Double.valueOf(columns[column]); } else { // throw new RuntimeException("More than two columns. Aborting..."); } rp2value.put(rp, value); - + } lineCounter++; time2rp2value.put(time, rp2value); } } - + BufferedReader br = IOUtils.getBufferedReader(this.receiverPointsFile); String line = br.readLine(); - + Map, Coord> rp2Coord = new HashMap, Coord>(); int lineCounter = 0; - + log.info("Reading receiver points file"); - + while( (line = br.readLine()) != null){ - + if (lineCounter % 10000 == 0.) { log.info("# " + lineCounter); } - + String[] columns = line.split( separator ); Id rpId = null; double x = 0; double y = 0; - + for(int i = 0; i < columns.length; i++){ - + switch(i){ - + case 0: rpId = Id.create(columns[i], ReceiverPoint.class); break; case 1: x = Double.valueOf(columns[i]); @@ -151,25 +149,25 @@ public void run() { case 2: y = Double.valueOf(columns[i]); break; default: throw new RuntimeException("More than three columns. Aborting..."); - + } - + } - + lineCounter++; rp2Coord.put(rpId, new Coord(x, y)); - + } BufferedWriter bw = new BufferedWriter( new FileWriter( outputFile ) ); - + // write headers bw.write("Receiver Point Id;x;y" ); - + for ( double time = startTime ; time <= endTime ; time = time + timeBinSize ) { bw.write(";" + label + "_" + Time.writeTime(time, Time.TIMEFORMAT_HHMMSS ) ); } - + bw.write(";Lden;L_6-9;L_16-19" ); bw.newLine(); @@ -177,19 +175,19 @@ public void run() { // fill table for (Id rp : time2rp2value.get( endTime ).keySet()) { bw.write(rp.toString() + ";" + rp2Coord.get(rp ).getX() + ";" + rp2Coord.get(rp ).getY() ); - + for ( double time = startTime ; time <= endTime ; time = time + timeBinSize ) { bw.write(";" + time2rp2value.get(time ).get(rp ) ); } - + // aggregate time intervals - + double termDay = 0.; // day: 7-19 for (double time = 8 * 3600.; time <= 19 * 3600.; time = time + timeBinSize ) { termDay = termDay + Math.pow(10, time2rp2value.get(time).get(rp) / 10); } - + double termEvening = 0.; // evening: 19-23 for (double time = 20 * 3600.; time <= 23 * 3600.; time = time + timeBinSize ) { @@ -198,7 +196,7 @@ public void run() { double termNight = 0.; // night: 23-7 - + // nightA: 23-24 for (double time = 24 * 3600.; time <= 24 * 3600.; time = time + timeBinSize ) { termNight = termNight + Math.pow(10, (time2rp2value.get(time).get(rp) + 10) / 10); @@ -207,24 +205,24 @@ public void run() { for (double time = 1 * 3600.; time <= 7 * 3600.; time = time + timeBinSize ) { termNight = termNight + Math.pow(10, (time2rp2value.get(time).get(rp) + 10) / 10); } - + double Lden = 10 * Math.log10(1./24. * (termDay + termEvening + termNight)); bw.write(";" + Lden ); - + double term69 = 0.; for (double time = 7 * 3600.; time <= 9 * 3600.; time = time + timeBinSize ) { term69 = term69 + Math.pow(10, (time2rp2value.get(time).get(rp)) / 10); } double L_69 = 10 * Math.log10(1./3. * term69); bw.write(";" + L_69 ); - + double term1619 = 0.; for (double time = 17 * 3600.; time <= 19 * 3600.; time = time + timeBinSize ) { term1619 = term1619 + Math.pow(10, (time2rp2value.get(time).get(rp)) / 10); } double L_1619 = 10 * Math.log10(1./3. * term1619); bw.write(";" + L_1619 ); - + bw.newLine(); // TODO // for( NoiseModule.NoiseListener listener : listeners ){ @@ -235,24 +233,24 @@ public void run() { // listener.newRecord( record ); // } - } - + } + bw.close(); log.info("Output written to " + outputFile); } - + catch (IOException e1) { e1.printStackTrace(); } String qGisProjectFile = "immission.qgs"; - + QGisWriter writer = new QGisWriter(TransformationFactory.DHDN_GK4, workingDirectory); - + // ################################################################################################################################################ Envelope envelope = new Envelope(4568808,5803042,4622772,5844280); writer.setEnvelope(envelope); - + VectorLayer noiseLayer = new VectorLayer("noise", outputFile, QGisConstants.geometryType.Point, true); noiseLayer.setDelimiter(";"); noiseLayer.setXField("x"); @@ -260,13 +258,13 @@ public void run() { GraduatedSymbolRenderer renderer = RendererFactory.createNoiseRenderer(noiseLayer, this.receiverPointGap ); renderer.setRenderingAttribute("Lden"); - + writer.addLayer(noiseLayer); - + // ################################################################################################################################################ - + writer.write(qGisProjectFile); - + } public void addListener( NoiseModule.NoiseListener noiseListener ){ diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/examples/NoiseOfflineCalculationExample.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/examples/NoiseOfflineCalculationExample.java index 91827345ec8..27628d7c405 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/examples/NoiseOfflineCalculationExample.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/examples/NoiseOfflineCalculationExample.java @@ -29,43 +29,43 @@ import org.matsim.core.scenario.ScenarioUtils; /** - * - * An example how to compute noise levels, damages etc. for a single iteration (= offline noise computation). - * + * + * An example how to compute noise levels, damages etc. for a single iteration (= offline noise computation). + * * @author ikaddoura * */ public class NoiseOfflineCalculationExample { - + private static String runDirectory = "pathTo/RunDirectory/"; private static String outputDirectory = "pathTo/analysis-output-directory/"; private static String runId = "runXYZ"; - + public static void main(String[] args) { - + Config config = ConfigUtils.createConfig(new NoiseConfigGroup()); - config.controler().setRunId(runId); + config.controller().setRunId(runId); config.network().setInputFile(runDirectory + runId + ".output_network.xml.gz"); config.plans().setInputFile(runDirectory + runId + ".output_plans.xml.gz"); - config.controler().setOutputDirectory(runDirectory); - + config.controller().setOutputDirectory(runDirectory); + // adjust the default noise parameters NoiseConfigGroup noiseParameters = ConfigUtils.addOrGetModule(config,NoiseConfigGroup.class) ; noiseParameters.setReceiverPointGap(12345789.); // ... - + Scenario scenario = ScenarioUtils.loadScenario(config); - + NoiseOfflineCalculation noiseCalculation = new NoiseOfflineCalculation(scenario, outputDirectory); noiseCalculation.run(); - + // some processing of the output data if (!outputDirectory.endsWith("/")) outputDirectory = outputDirectory + "/"; - + String outputFilePath = outputDirectory + "noise-analysis/"; ProcessNoiseImmissions process = new ProcessNoiseImmissions(outputFilePath + "immissions/", outputFilePath + "receiverPoints/receiverPoints.csv", noiseParameters.getReceiverPointGap()); process.run(); - + final String[] labels = { "immission", "consideredAgentUnits" , "damages_receiverPoint" }; final String[] workingDirectories = { outputFilePath + "/immissions/" , outputFilePath + "/consideredAgentUnits/" , outputFilePath + "/damages_receiverPoint/" }; diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/examples/NoiseOnlineControlerExample.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/examples/NoiseOnlineControlerExample.java index 5aa94aaa304..4f8fb1a59bf 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/examples/NoiseOnlineControlerExample.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/examples/NoiseOnlineControlerExample.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.noise.examples; @@ -34,35 +34,35 @@ /** * An example how to use the noise module during a MATSim run (= online noise computation). - * + * * The {@link NoiseConfigGroup} specifies parameters that are relevant for the noise computation and if noise damages are internalized. * For the internalization of noise damages, there is an average and a marginal cost pricing approach, see {@link NoiseConfigGroup.NoiseAllocationApproach}. - * - * For an example of how to compute noise levels, damages etc. for a final iteration (= offline noise computation), see {@link NoiseOfflineCalculationExample}. - * + * + * For an example of how to compute noise levels, damages etc. for a final iteration (= offline noise computation), see {@link NoiseOfflineCalculationExample}. + * * @author ikaddoura * */ public class NoiseOnlineControlerExample { - + private static final String configFile = "./contribs/noise/test/input/org/matsim/contrib/noise/config.xml"; public static void main(String[] args) { - + Config config = ConfigUtils.loadConfig(configFile, new NoiseConfigGroup()); Scenario scenario = ScenarioUtils.loadScenario(config); - + Controler controler = new Controler(scenario); controler.addOverridingModule(new NoiseModule()); - - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); controler.run(); - + // optionally process the output data - String workingDirectory = controler.getConfig().controler().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controler().getLastIteration() + "/immissions/"; - String receiverPointsFile = controler.getConfig().controler().getOutputDirectory() + "/receiverPoints/receiverPoints.csv"; + String workingDirectory = controler.getConfig().controller().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controller().getLastIteration() + "/immissions/"; + String receiverPointsFile = controler.getConfig().controller().getOutputDirectory() + "/receiverPoints/receiverPoints.csv"; NoiseConfigGroup noiseParameters = ConfigUtils.addOrGetModule(config, NoiseConfigGroup.class ) ; ProcessNoiseImmissions processNoiseImmissions = new ProcessNoiseImmissions(workingDirectory, receiverPointsFile, noiseParameters.getReceiverPointGap()); - processNoiseImmissions.run(); + processNoiseImmissions.run(); } } diff --git a/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseConfigGroupIT.java b/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseConfigGroupIT.java index 512440cab25..7e07654ace8 100644 --- a/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseConfigGroupIT.java +++ b/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseConfigGroupIT.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.noise; @@ -39,58 +39,58 @@ */ public class NoiseConfigGroupIT { - + @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); - + @Test public final void test0(){ - + String configFile = testUtils.getPackageInputDirectory() + "NoiseConfigGroupTest/config0.xml"; Config config = ConfigUtils.loadConfig(configFile, new NoiseConfigGroup()); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); - + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + NoiseConfigGroup noiseParameters = (NoiseConfigGroup) config.getModule("noise"); // test the config parameters Assert.assertEquals("wrong config parameter", 12345., noiseParameters.getReceiverPointGap(), MatsimTestUtils.EPSILON); - + String actForRecPtGrid = noiseParameters.getConsideredActivitiesForReceiverPointGridArray()[0] + "," + noiseParameters.getConsideredActivitiesForReceiverPointGridArray()[1] + "," + noiseParameters.getConsideredActivitiesForReceiverPointGridArray()[2]; - Assert.assertEquals("wrong config parameter", "home,sleep,eat", actForRecPtGrid); - + Assert.assertEquals("wrong config parameter", "home,sleep,eat", actForRecPtGrid); + String actForSpatFct = noiseParameters.getConsideredActivitiesForDamageCalculationArray()[0] + "," + noiseParameters.getConsideredActivitiesForDamageCalculationArray()[1] + "," + noiseParameters.getConsideredActivitiesForDamageCalculationArray()[2]; - Assert.assertEquals("wrong config parameter", "work,leisure,other", actForSpatFct); - + Assert.assertEquals("wrong config parameter", "work,leisure,other", actForSpatFct); + Assert.assertEquals("wrong config parameter", 12345789., noiseParameters.getRelevantRadius(), MatsimTestUtils.EPSILON); Assert.assertFalse("wrong config parameter", noiseParameters.isComputeNoiseDamages()); String hgvIdPrefixes = noiseParameters.getHgvIdPrefixesArray()[0] + "," + noiseParameters.getHgvIdPrefixesArray()[1] + "," + noiseParameters.getHgvIdPrefixesArray()[2] + "," + noiseParameters.getHgvIdPrefixesArray()[3]; - Assert.assertEquals("wrong config parameter", "lkw,LKW,HGV,hgv", hgvIdPrefixes); - + Assert.assertEquals("wrong config parameter", "lkw,LKW,HGV,hgv", hgvIdPrefixes); + String tunnelLinkIds = noiseParameters.getTunnelLinkIDsSet().toArray()[0] + "," + noiseParameters.getTunnelLinkIDsSet().toArray()[1]; Assert.assertEquals("wrong config parameter", "link1,link2", tunnelLinkIds); } - + @Test public final void test1(){ - + String configFile = testUtils.getPackageInputDirectory() + "NoiseConfigGroupTest/config1.xml"; Config config = ConfigUtils.loadConfig(configFile, new NoiseConfigGroup()); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); - + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + NoiseConfigGroup noiseParameters = (NoiseConfigGroup) config.getModule("noise"); - + // see if the custom config group is written into the output config file Scenario scenario = ScenarioUtils.loadScenario(config); Controler controler = new Controler(scenario); controler.addOverridingModule(new NoiseModule()); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); controler.run(); - - Config outputConfig = ConfigUtils.loadConfig(controler.getConfig().controler().getOutputDirectory() + "/output_config.xml", new NoiseConfigGroup()); + + Config outputConfig = ConfigUtils.loadConfig(controler.getConfig().controller().getOutputDirectory() + "/output_config.xml", new NoiseConfigGroup()); NoiseConfigGroup outputNoiseParameters = (NoiseConfigGroup) outputConfig.getModule("noise"); - + Assert.assertEquals("input and output config parameters are not the same", noiseParameters.toString(), outputNoiseParameters.toString()); } diff --git a/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseIT.java b/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseIT.java index 57523196709..aa179afd113 100644 --- a/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseIT.java +++ b/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseIT.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.noise; @@ -46,8 +46,8 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.Injector; @@ -74,23 +74,23 @@ public class NoiseIT { @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); - + // Tests the NoisSpatialInfo functionality separately for each function @Test public final void test1(){ - + String configFile = testUtils.getPackageInputDirectory() + "NoiseTest/config1.xml"; Config config = ConfigUtils.loadConfig(configFile, new NoiseConfigGroup()); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); - + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + Scenario scenario = ScenarioUtils.loadScenario(config); - + NoiseConfigGroup noiseParameters = (NoiseConfigGroup) scenario.getConfig().getModules().get(NoiseConfigGroup.GROUP_NAME); - - noiseParameters.setReceiverPointGap(250.); + + noiseParameters.setReceiverPointGap(250.); noiseParameters.setScaleFactor(1.); - + String[] consideredActivities = {"home", "work"}; noiseParameters.setConsideredActivitiesForDamageCalculationArray(consideredActivities); @@ -104,31 +104,31 @@ public final void test1(){ // NoiseContext noiseContext = new NoiseContext(scenario); NoiseContext noiseContext = injector.getInstance( NoiseContext.class ) ; - + // test the grid of receiver points Assert.assertEquals("wrong number of receiver points", 16, noiseContext.getReceiverPoints().size(), MatsimTestUtils.EPSILON); Assert.assertEquals("wrong coord for receiver point Id '10'", new Coord((double) 500, (double) 100).toString(), noiseContext.getReceiverPoints().get(Id.create(10, ReceiverPoint.class)).getCoord().toString()); - + // test the allocation of activity coordinates to the nearest receiver point Assert.assertEquals("wrong nearest receiver point Id for coord 300/300 (x/y)", "5", noiseContext.getGrid().getActivityCoord2receiverPointId().get(new Coord((double) 300, (double) 300)).toString()); Assert.assertEquals("wrong nearest receiver point Id for coord 150/150 (x/y)", "9", noiseContext.getGrid().getActivityCoord2receiverPointId().get(new Coord((double) 150, (double) 150)).toString()); Assert.assertEquals("wrong nearest receiver point Id for coord 100/100 (x/y)", "8", noiseContext.getGrid().getActivityCoord2receiverPointId().get(new Coord((double) 100, (double) 100)).toString()); Assert.assertEquals("wrong nearest receiver point Id for coord 500/500 (x/y)", "2", noiseContext.getGrid().getActivityCoord2receiverPointId().get(new Coord((double) 500, (double) 500)).toString()); - + // test the allocation of relevant links to the receiver point Assert.assertEquals("wrong relevant link for receiver point Id '15'", 3, noiseContext.getReceiverPoints().get(Id.create("15", Link.class)).getRelevantLinks().size()); // Assert.assertEquals("wrong relevant link for receiver point Id '15'", 3, noiseContext.getReceiverPoints().get(Id.create("15", Link.class)).getLinkId2angleCorrection().size()); // test the distance correction term // Assert.assertEquals("wrong distance between receiver point Id '8' and link Id '1'", 8.749854822140838, noiseContext.getReceiverPoints().get(Id.create("8", ReceiverPoint.class)).getLinkId2distanceCorrection().get(Id.create("link0", Link.class)), MatsimTestUtils.EPSILON); - + // test the angle correction term // Assert.assertEquals("wrong immission angle correction for receiver point 14 and link1", -0.8913405699036482, noiseContext.getReceiverPoints().get(Id.create("14", ReceiverPoint.class)).getLinkId2angleCorrection().get(Id.create("link1", Link.class)), MatsimTestUtils.EPSILON); double angle0 = 180.; double immissionCorrection0 = 10 * Math.log10((angle0) / (180)); // Assert.assertEquals("wrong immission angle correction for receiver point 12 and link5", immissionCorrection0, noiseContext.getReceiverPoints().get(Id.create("12", ReceiverPoint.class)).getLinkId2angleCorrection().get(Id.create("link5", Link.class)), MatsimTestUtils.EPSILON); - + double angle = 65.39222026185993; double immissionCorrection = 10 * Math.log10((angle) / (180)); // Assert.assertEquals("wrong immission angle correction for receiver point 9 and link5", immissionCorrection, noiseContext.getReceiverPoints().get(Id.create("9", ReceiverPoint.class)).getLinkId2angleCorrection().get(Id.create("link5", Link.class)), MatsimTestUtils.EPSILON); @@ -137,16 +137,16 @@ public final void test1(){ double angle2 = 0.0000000001; double immissionCorrection2 = 10 * Math.log10((angle2) / (180)); // Assert.assertEquals("wrong immission angle correction for receiver point 8 and link5", immissionCorrection2, noiseContext.getReceiverPoints().get(Id.create("8", ReceiverPoint.class)).getLinkId2angleCorrection().get(Id.create("link5", Link.class)), MatsimTestUtils.EPSILON); - + double angle3 = 84.28940686250034; double immissionCorrection3 = 10 * Math.log10((angle3) / (180)); // Assert.assertEquals("wrong immission angle correction for receiver point 8 and link1", immissionCorrection3, noiseContext.getReceiverPoints().get(Id.create("8", ReceiverPoint.class)).getLinkId2angleCorrection().get(Id.create("link1", Link.class)), MatsimTestUtils.EPSILON); - + double angle4 = 180; double immissionCorrection4 = 10 * Math.log10((angle4) / (180)); // Assert.assertEquals("wrong immission angle correction for receiver point 8 and link0", immissionCorrection4, noiseContext.getReceiverPoints().get(Id.create("8", ReceiverPoint.class)).getLinkId2angleCorrection().get(Id.create("link0", Link.class)), MatsimTestUtils.EPSILON); } - + // tests the noise emissions, immissions, considered agent units, damages (receiver points), damages (per link), damages (per vehicle) based on the generated *.csv output // tests the noise events applying the average cost allocation approach @Test @@ -154,8 +154,8 @@ public final void test2a(){ // start a simple MATSim run with a single iteration String configFile = testUtils.getPackageInputDirectory() + "NoiseTest/config2.xml"; Config config = ConfigUtils.loadConfig(configFile ) ; - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.none); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.none); runTest2a( config ) ; } @Test @@ -163,8 +163,8 @@ public final void test2aWAccessEgress(){ // start a simple MATSim run with a single iteration String configFile = testUtils.getPackageInputDirectory() + "NoiseTest/config2.xml"; Config config = ConfigUtils.loadConfig(configFile ) ; - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); - config.plansCalcRoute().setAccessEgressType(AccessEgressType.accessEgressModeToLink); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + config.routing().setAccessEgressType(AccessEgressType.accessEgressModeToLink); // { // ModeRoutingParams params = new ModeRoutingParams( TransportMode.non_network_walk ); // params.setTeleportedModeSpeed( 2.0 ); @@ -173,289 +173,289 @@ public final void test2aWAccessEgress(){ // } runTest2a( config ) ; } - + private static void runTest2a( Config runConfig ) { Controler controler = new Controler(runConfig); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); controler.run(); - + // run the noise analysis for the final iteration (offline) - - String runDirectory = controler.getConfig().controler().getOutputDirectory(); + + String runDirectory = controler.getConfig().controller().getOutputDirectory(); if (!runDirectory.endsWith("/")) runDirectory = runDirectory + "/"; - + Config config = ConfigUtils.createConfig(new NoiseConfigGroup()); config.network().setInputFile(runDirectory + "output_network.xml.gz"); config.plans().setInputFile(runDirectory + "output_plans.xml.gz"); - config.controler().setOutputDirectory(runDirectory); - config.controler().setLastIteration(controler.getConfig().controler().getLastIteration()); - + config.controller().setOutputDirectory(runDirectory); + config.controller().setLastIteration(controler.getConfig().controller().getLastIteration()); + NoiseConfigGroup noiseParameters = (NoiseConfigGroup) config.getModules().get(NoiseConfigGroup.GROUP_NAME); - - noiseParameters.setReceiverPointGap(250.); - + + noiseParameters.setReceiverPointGap(250.); + String[] consideredActivities = {"home", "work"}; noiseParameters.setConsideredActivitiesForDamageCalculationArray(consideredActivities); - + noiseParameters.setScaleFactor(1.); noiseParameters.setUseActualSpeedLevel(false); noiseParameters.setAllowForSpeedsOutsideTheValidRange(true); - + Scenario scenario = ScenarioUtils.loadScenario(config); - + NoiseOfflineCalculation noiseCalculation = new NoiseOfflineCalculation(scenario, runDirectory); - noiseCalculation.run(); - + noiseCalculation.run(); + EventsManager events = new ParallelEventsManager(false,1,65536); - + final Map, List> eventsPerPersonId = new HashMap, List>(); - + events.addHandler(new ActivityStartEventHandler() { - + @Override public void reset(int iteration) { - + } - + @Override public void handleEvent(ActivityStartEvent event) { - + if(!eventsPerPersonId.containsKey(event.getPersonId())){ eventsPerPersonId.put(event.getPersonId(), new ArrayList()); } eventsPerPersonId.get(event.getPersonId()).add(event); - + } }); - + events.addHandler(new ActivityEndEventHandler() { - + @Override public void reset(int iteration) { - + } - + @Override public void handleEvent(ActivityEndEvent event) { - + if(!eventsPerPersonId.containsKey(event.getPersonId())){ eventsPerPersonId.put(event.getPersonId(), new ArrayList()); } eventsPerPersonId.get(event.getPersonId()).add(event); - + } }); events.initProcessing(); MatsimEventsReader reader = new MatsimEventsReader(events); - reader.readFile(runDirectory + "ITERS/it." + config.controler().getLastIteration() + "/" + config.controler().getLastIteration() + ".events.xml.gz"); + reader.readFile(runDirectory + "ITERS/it." + config.controller().getLastIteration() + "/" + config.controller().getLastIteration() + ".events.xml.gz"); events.finishProcessing(); // ############################ // test considered agent units // ############################ - + double sevenOclock = 25200; double endTime = 39600; double ttOclock = 79200; - + String separator = ";"; String line = null; - + double[] timeSlots = {sevenOclock, endTime, ttOclock}; String pathToConsideredAgentUnitsFile; Map, List> consideredAgentsPerReceiverPoint = new HashMap, List>(); Map idxFromKey = new ConcurrentHashMap<>(); BufferedReader br; - + for(double currentTimeSlot : timeSlots){ - + pathToConsideredAgentUnitsFile = runDirectory + "noise-analysis/consideredAgentUnits/consideredAgentUnits_" + Double.toString(currentTimeSlot) + ".csv"; - + br = IOUtils.getBufferedReader(pathToConsideredAgentUnitsFile); - + try { - + line = br.readLine(); - + String[] keys = line.split(separator); for(int i = 0; i < keys.length; i++){ idxFromKey.put(keys[i], i); } - + int idxReceiverPointId = idxFromKey.get("Receiver Point Id"); int idxConsideredAgentUnits = idxFromKey.get("Considered Agent Units " + Time.writeTime(currentTimeSlot, Time.TIMEFORMAT_HHMMSS)); - + while((line = br.readLine()) != null){ - + keys = line.split(separator); if(!consideredAgentsPerReceiverPoint.containsKey(Id.create(keys[idxReceiverPointId], ReceiverPoint.class))){ consideredAgentsPerReceiverPoint.put(Id.create(keys[idxReceiverPointId], ReceiverPoint.class), new ArrayList()); } - + consideredAgentsPerReceiverPoint.get(Id.create(keys[idxReceiverPointId], ReceiverPoint.class)).add(Double.parseDouble(keys[idxConsideredAgentUnits])); - + } - + } catch (IOException e) { e.printStackTrace(); } - + } int index = 0; - + for(double currentTimeSlot : timeSlots){ final Map, Double> affectedPersonsPerReceiverPointTest = new HashMap, Double>(); - + double affectedPersons = 0.; - + for(Id personId : scenario.getPopulation().getPersons().keySet()){ - + double start = 0.; - + for(Event e : eventsPerPersonId.get(personId)){ boolean activityEnded = false; - + PersonActivityInfo actInfo = null; - + if(e.getEventType().equals("actend")){ - + ActivityEndEvent event = (ActivityEndEvent)e; - + if(event.getActType().equals("home")){ - + actInfo = new PersonActivityInfo(); actInfo.setActivityType("home"); actInfo.setStartTime(start); double end= index == 2 ? 30*3600 : event.getTime(); actInfo.setEndTime(end); - + activityEnded = true; - + } - + else if(event.getActType().equals("work")){ - + actInfo = new PersonActivityInfo(); actInfo.setActivityType("work"); actInfo.setStartTime(start); actInfo.setEndTime(event.getTime()); - + activityEnded = true; - + } - + } else if(e.getEventType().equals("actstart")){ - + ActivityStartEvent event = (ActivityStartEvent)e; - + if(event.getActType().equals("home")){ - + if(index == 0){ - + continue; - + } - + start = event.getTime(); - + } else if(event.getActType().equals("work")){ - + start = event.getTime(); - + } - + } - + if(activityEnded){ - + // test code of getDurationInWithinInterval from actInfo - + double durationInThisInterval = 0.; double timeIntervalStart = currentTimeSlot - noiseParameters.getTimeBinSizeNoiseComputation(); - + if (( actInfo.getStartTime() < currentTimeSlot) && ( actInfo.getEndTime() >= timeIntervalStart )) { - + if ((actInfo.getStartTime() <= timeIntervalStart) && actInfo.getEndTime() >= currentTimeSlot) { - + durationInThisInterval = noiseParameters.getTimeBinSizeNoiseComputation(); - + } else if (actInfo.getStartTime() <= timeIntervalStart && actInfo.getEndTime() <= currentTimeSlot) { - + durationInThisInterval = actInfo.getEndTime() - timeIntervalStart; - + } else if (actInfo.getStartTime() >= timeIntervalStart && actInfo.getEndTime() >= currentTimeSlot) { - + durationInThisInterval = currentTimeSlot - actInfo.getStartTime(); - + } else if (actInfo.getStartTime() >= timeIntervalStart && actInfo.getEndTime() <= currentTimeSlot) { - + durationInThisInterval = actInfo.getEndTime() - actInfo.getStartTime(); - - + + } else { - + throw new RuntimeException("Unknown case. Aborting..."); } - + } - - double durationInThisIntervalMethod = actInfo.getDurationWithinInterval(currentTimeSlot, noiseParameters.getTimeBinSizeNoiseComputation()); - + + double durationInThisIntervalMethod = actInfo.getDurationWithinInterval(currentTimeSlot, noiseParameters.getTimeBinSizeNoiseComputation()); + Assert.assertEquals("Durations of activities do not match!", durationInThisIntervalMethod, durationInThisInterval, MatsimTestUtils.EPSILON); - - double unitsThisPersonActivityInfo = durationInThisInterval / noiseParameters.getTimeBinSizeNoiseComputation(); + + double unitsThisPersonActivityInfo = durationInThisInterval / noiseParameters.getTimeBinSizeNoiseComputation(); affectedPersons = ( unitsThisPersonActivityInfo * noiseParameters.getScaleFactor() ); - + int outOfHomeActIdx = 2 ; - if ( !runConfig.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !runConfig.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { outOfHomeActIdx = 6 ; } Coord coord = actInfo.getActivityType().equals("home") ? ((Activity) scenario.getPopulation().getPersons().get(personId).getSelectedPlan().getPlanElements().get(0)).getCoord() : ((Activity) scenario.getPopulation().getPersons().get(personId).getSelectedPlan().getPlanElements().get(outOfHomeActIdx)).getCoord(); - + Id rpId = noiseCalculation.getNoiseContext().getGrid().getActivityCoord2receiverPointId().get(coord); if ( rpId==null ) { log.warn( "coord=" + coord ); Gbl.assertNotNull( rpId ); } - - if(!affectedPersonsPerReceiverPointTest.containsKey(rpId)){ + + if(!affectedPersonsPerReceiverPointTest.containsKey(rpId)){ affectedPersonsPerReceiverPointTest.put(rpId, affectedPersons); - - } else{ + + } else{ double n = affectedPersonsPerReceiverPointTest.get(rpId); - affectedPersonsPerReceiverPointTest.put(rpId, n + affectedPersons); + affectedPersonsPerReceiverPointTest.put(rpId, n + affectedPersons); } - + } - + } - + } - + if(currentTimeSlot == endTime){ - - if ( !runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + + if ( !runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { Assert.assertEquals("Wrong number of affected persons at receiver point 16", 2.3447222222222224, affectedPersonsPerReceiverPointTest.get(Id.create("16", ReceiverPoint.class)), MatsimTestUtils.EPSILON); // result changed after changing where agents are walking to in access/egress (July 20) - Assert.assertEquals("Wrong number of affected persons at receiver point 0", 0.479722222222222, + Assert.assertEquals("Wrong number of affected persons at receiver point 0", 0.479722222222222, affectedPersonsPerReceiverPointTest.get(Id.create("0", ReceiverPoint.class)), MatsimTestUtils.EPSILON); } else { - Assert.assertEquals("Wrong number of affected persons at receiver point 16", 2.35305555555555, + Assert.assertEquals("Wrong number of affected persons at receiver point 16", 2.35305555555555, affectedPersonsPerReceiverPointTest.get(Id.create("16", ReceiverPoint.class)), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong number of affected persons at receiver point 0", 0.479722222222222, + Assert.assertEquals("Wrong number of affected persons at receiver point 0", 0.479722222222222, affectedPersonsPerReceiverPointTest.get(Id.create("0", ReceiverPoint.class)), MatsimTestUtils.EPSILON); } - + } - + for(Id receiverPointId : affectedPersonsPerReceiverPointTest.keySet()){ final Double expected = affectedPersonsPerReceiverPointTest.get(receiverPointId); if ( expected==null ) { @@ -473,16 +473,16 @@ else if(event.getActType().equals("work")){ log.warn( "receiverPointId:" + receiverPointId ); log.warn( "affected:" + list ) ; } - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { Assert.assertEquals("Wrong number of affected persons", expected, actual, MatsimTestUtils.EPSILON); } else { Assert.assertEquals("Wrong number of affected persons", expected, actual, MatsimTestUtils.EPSILON); } - + } - + index++; - + } // ################################# @@ -490,120 +490,120 @@ else if(event.getActType().equals("work")){ // ################################# line = null; - + String pathToEmissionsFile = runDirectory + "noise-analysis/emissions/emission_" + Double.toString(endTime) + ".csv"; - + Map, Double> emissionsPerLink = new HashMap, Double>(); idxFromKey = new ConcurrentHashMap(); - + br = IOUtils.getBufferedReader(pathToEmissionsFile); - + try { - + line = br.readLine(); String[] keys = line.split(separator); for(int i = 0; i < keys.length; i++){ idxFromKey.put(keys[i], i); } - + int idxLinkId = idxFromKey.get("Link Id"); int idxNoiseEmission = idxFromKey.get("Noise Emission " + Time.writeTime(endTime, Time.TIMEFORMAT_HHMMSS)); - + while((line = br.readLine()) != null){ - + keys = line.split(separator); emissionsPerLink.put(Id.create(keys[idxLinkId], Link.class), Double.parseDouble(keys[idxNoiseEmission])); - + } - + } catch (IOException e) { e.printStackTrace(); } - + Map, Integer> amountOfVehiclesPerLink = new HashMap<>(); - + for(NoiseEventCaused event: noiseCalculation.getTimeTracker().getDamageCalculation().getNoiseEventsCaused()){ - + if(event.getTimeBinEndTime() >= endTime - 3600 && event.getTimeBinEndTime() <= endTime){ - + Id linkId = event.getLinkId(); int amount = 1; - + if(amountOfVehiclesPerLink.containsKey(linkId)){ - + amount = amountOfVehiclesPerLink.get(linkId) + 1; amountOfVehiclesPerLink.put(linkId, amount); - + } else{ - + amountOfVehiclesPerLink.put(linkId, amount); - + } - + } - + } - + Map,Double> noiseEmissionsPerLink = new HashMap,Double>(); - + for(Id linkId : scenario.getNetwork().getLinks().keySet()){ noiseEmissionsPerLink.put(linkId, 0.); } - + for(Id linkId : amountOfVehiclesPerLink.keySet()){ double vCar = (scenario.getNetwork().getLinks().get(linkId).getFreespeed()) * 3.6; double vHdv = vCar; double p = 0; int n = amountOfVehiclesPerLink.size(); - + double mittelungspegel = RLS90NoiseEmission.calculateMittelungspegelLm(n, p); double Dv = RLS90NoiseEmission.calculateGeschwindigkeitskorrekturDv(vCar, vHdv, p); double noiseEmission = mittelungspegel + Dv; - + Assert.assertEquals("Wrong amount of emission!", noiseEmission, emissionsPerLink.get(linkId), MatsimTestUtils.EPSILON); noiseEmissionsPerLink.put(linkId, noiseEmission); - + } - + Assert.assertEquals("Wrong amount of emission!", 56.4418948379387, noiseEmissionsPerLink.get(Id.create("link2", Link.class)), MatsimTestUtils.EPSILON); Assert.assertEquals("Wrong amount of emission!", 86.4302864851097, noiseEmissionsPerLink.get(Id.create("linkA5", Link.class)), MatsimTestUtils.EPSILON); Assert.assertEquals("Wrong amount of emission!", 0., noiseEmissionsPerLink.get(Id.create("link4", Link.class)), MatsimTestUtils.EPSILON); - - + + // ############################################ // test immissions per receiver point and time // ############################################ line = null; - + String pathToImmissionsFile = runDirectory + "noise-analysis/immissions/immission_" + Double.toString(endTime) + ".csv"; - + Map, Double> immissionPerReceiverPointId = new HashMap, Double>(); - + idxFromKey = new ConcurrentHashMap(); - + br = IOUtils.getBufferedReader(pathToImmissionsFile); - + try { - + line = br.readLine(); - + String[] keys = line.split(separator); for(int i = 0; i < keys.length; i++){ idxFromKey.put(keys[i], i); } - + int idxReceiverPointId = idxFromKey.get("Receiver Point Id"); int idxImmission = idxFromKey.get("Immission " + Time.writeTime(endTime, Time.TIMEFORMAT_HHMMSS)); - + while((line = br.readLine()) != null){ - + keys = line.split(separator); immissionPerReceiverPointId.put(Id.create(keys[idxReceiverPointId], ReceiverPoint.class), Double.parseDouble(keys[idxImmission])); - + } - + } catch (IOException e) { e.printStackTrace(); } @@ -611,81 +611,81 @@ else if(event.getActType().equals("work")){ final RLS90NoiseImmission rls90NoiseImmission = new RLS90NoiseImmission(noiseCalculation.getNoiseContext(), null); for(NoiseReceiverPoint rp : noiseCalculation.getNoiseContext().getReceiverPoints().values()){ - + Map, Double> linkId2IsolatedImmission = new HashMap, Double>(); - + for(Id linkId : rp.getRelevantLinks()){ - + double noiseImmission = 0; - + if(emissionsPerLink.get(linkId) > 0){ - + noiseImmission = emissionsPerLink.get(linkId) + rp.getLinkCorrection(linkId); - + if(noiseImmission < 0) noiseImmission = 0; - + } - + linkId2IsolatedImmission.put(linkId, noiseImmission); - + } - + Assert.assertEquals("Wrong amount of immission!", rls90NoiseImmission.calculateResultingNoiseImmission(linkId2IsolatedImmission.values()), immissionPerReceiverPointId.get(rp.getId()), MatsimTestUtils.EPSILON); - + } - + Assert.assertEquals("Wrong amount of immission!", 77.25915342419277, immissionPerReceiverPointId.get(Id.create("15", ReceiverPoint.class)), MatsimTestUtils.EPSILON); Assert.assertEquals("Wrong amount of immission!", 67.9561670074151, immissionPerReceiverPointId.get(Id.create("31", ReceiverPoint.class)), MatsimTestUtils.EPSILON); Assert.assertEquals("Wrong amount of immission!", 0., immissionPerReceiverPointId.get(Id.create("0", ReceiverPoint.class)), MatsimTestUtils.EPSILON); - + // ############################################ // test damages per receiver point and time // ############################################ line = null; - + String pathToDamagesFile = runDirectory + "noise-analysis/damages_receiverPoint/damages_receiverPoint_" + Double.toString(endTime) + ".csv"; - + Map, Double> damagesPerReceiverPointId = new HashMap, Double>(); - + idxFromKey = new ConcurrentHashMap(); - + br = IOUtils.getBufferedReader(pathToDamagesFile); - + try { - + line = br.readLine(); - + String[] keys = line.split(separator); for(int i = 0; i < keys.length; i++){ idxFromKey.put(keys[i], i); } - + int idxReceiverPointId = idxFromKey.get("Receiver Point Id"); int idxDamages = idxFromKey.get("Damages " + Time.writeTime(endTime, Time.TIMEFORMAT_HHMMSS)); - + while((line = br.readLine()) != null){ - + keys = line.split(separator); damagesPerReceiverPointId.put(Id.create(keys[idxReceiverPointId], ReceiverPoint.class), Double.parseDouble(keys[idxDamages])); - + } - + } catch (IOException e) { e.printStackTrace(); } - + for(ReceiverPoint rp : noiseCalculation.getNoiseContext().getReceiverPoints().values()){ - + double noiseImmission = immissionPerReceiverPointId.get(rp.getId()); double affectedAgentUnits = consideredAgentsPerReceiverPoint.get(rp.getId()).get(1); - + Assert.assertEquals("Wrong damage!", NoiseDamageCalculation.calculateDamageCosts(noiseImmission, affectedAgentUnits, endTime, noiseParameters.getAnnualCostRate(), noiseParameters.getTimeBinSizeNoiseComputation()), damagesPerReceiverPointId.get(rp.getId()), MatsimTestUtils.EPSILON); - + } - - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("Wrong damage!", 0.0664164095284536, + + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("Wrong damage!", 0.0664164095284536, damagesPerReceiverPointId.get(Id.create("16", ReceiverPoint.class)), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("Wrong damage!", 0.06618119616706872 , @@ -693,55 +693,55 @@ else if(event.getActType().equals("work")){ // result changed after changing walk distances } Assert.assertEquals("Wrong damage!", 0., damagesPerReceiverPointId.get(Id.create("0", ReceiverPoint.class)), MatsimTestUtils.EPSILON); - + // ############################################ // test average damages per link and time // ############################################ - + // noise level at receiver point '16': 69.65439464 - + // relevant link IDs - // link2: noise contribution: 50.45464287410944 --> share: 0.01202333 --> damage costs: 0.00079855 + // link2: noise contribution: 50.45464287410944 --> share: 0.01202333 --> damage costs: 0.00079855 // linkA5: noise contribution: 69.60186152606298 ---> share: 0.98797667 --> damage costs: 0.06561786 // linkB5: noise contribution: 0 - + line = null; - + String pathToDamageLinkFile = runDirectory + "noise-analysis/average_damages_link/average_damages_link_" + Double.toString(endTime) + ".csv"; - + Map, Double> damagesPerlinkId = new HashMap, Double>(); - + idxFromKey = new ConcurrentHashMap(); - + br = IOUtils.getBufferedReader(pathToDamageLinkFile); - + try { - + line = br.readLine(); - + String[] keys = line.split(separator); for(int i = 0; i < keys.length; i++){ idxFromKey.put(keys[i], i); } - + int idxLinkId = idxFromKey.get("Link Id"); int idxDamages = idxFromKey.get("Damages " + Time.writeTime(endTime, Time.TIMEFORMAT_HHMMSS)); - + while((line = br.readLine()) != null){ - + keys = line.split(separator); damagesPerlinkId.put(Id.create(keys[idxLinkId], Link.class), Double.parseDouble(keys[idxDamages])); - + } - + } catch (IOException e) { e.printStackTrace(); } - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("Wrong link's damage contribution!", 0.00079854651258, + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("Wrong link's damage contribution!", 0.00079854651258, damagesPerlinkId.get(Id.create("link2", Link.class)), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong link's damage contribution!", 0.06561786301587, + Assert.assertEquals("Wrong link's damage contribution!", 0.06561786301587, damagesPerlinkId.get(Id.create("linkA5", Link.class)), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("Wrong link's damage contribution!", 7.957184286235844E-4, @@ -750,48 +750,48 @@ else if(event.getActType().equals("work")){ damagesPerlinkId.get(Id.create("linkA5", Link.class)), MatsimTestUtils.EPSILON); } Assert.assertEquals("Wrong link's damage contribution!", 0., damagesPerlinkId.get(Id.create("linkB5", Link.class)), MatsimTestUtils.EPSILON); - + // ############################################ // test average damages per link, car and time // ############################################ - + line = null; - + String pathToDamageLinkCar = runDirectory + "noise-analysis/average_damages_link_car/average_damages_link_car_" + Double.toString(endTime) + ".csv"; - + Map, Double> damagesPerCar = new HashMap, Double>(); - + idxFromKey = new ConcurrentHashMap(); - + br = IOUtils.getBufferedReader(pathToDamageLinkCar); - + try { - + line = br.readLine(); - + String[] keys = line.split(separator); for(int i = 0; i < keys.length; i++){ idxFromKey.put(keys[i], i); } - + int idxlinkId = idxFromKey.get("Link Id"); int idxDamages = idxFromKey.get("Average damages per car " + Time.writeTime(endTime, Time.TIMEFORMAT_HHMMSS)); - + while((line = br.readLine()) != null){ - + keys = line.split(separator); damagesPerCar.put(Id.create(keys[idxlinkId], Link.class), Double.parseDouble(keys[idxDamages])); - + } - + } catch (IOException e) { e.printStackTrace(); } - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("Wrong damage per car per link!", 0.00079854651258 / 2.0, + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("Wrong damage per car per link!", 0.00079854651258 / 2.0, damagesPerCar.get(Id.create("link2", Link.class)), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong damage per car per link!", 0.06561786301587 / 2.0, + Assert.assertEquals("Wrong damage per car per link!", 0.06561786301587 / 2.0, damagesPerCar.get(Id.create("linkA5", Link.class)), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("Wrong damage per car per link!", 3.978592143117922E-4, @@ -799,48 +799,48 @@ else if(event.getActType().equals("work")){ Assert.assertEquals("Wrong damage per car per link!", 0.03269273886922247, damagesPerCar.get(Id.create("linkA5", Link.class)), MatsimTestUtils.EPSILON); } - Assert.assertEquals("Wrong damage per car per link!", 0., + Assert.assertEquals("Wrong damage per car per link!", 0., damagesPerCar.get(Id.create("linkB5", Link.class)), MatsimTestUtils.EPSILON); - + line = null; - + String pathToMarginalDamageLinkCar = runDirectory + "noise-analysis/marginal_damages_link_car/marginal_damages_link_car_" + Double.toString(endTime) + ".csv"; - + Map, Double> marginaldamagesPerCar = new HashMap, Double>(); - + idxFromKey = new ConcurrentHashMap(); - + br = IOUtils.getBufferedReader(pathToMarginalDamageLinkCar); - + try { - + line = br.readLine(); - + String[] keys = line.split(separator); for(int i = 0; i < keys.length; i++){ idxFromKey.put(keys[i], i); } - + int idxlinkId = idxFromKey.get("Link Id"); int idxDamages = idxFromKey.get("Marginal damages per car " + Time.writeTime(endTime, Time.TIMEFORMAT_HHMMSS)); - + while((line = br.readLine()) != null){ - + keys = line.split(separator); marginaldamagesPerCar.put(Id.create(keys[idxlinkId], Link.class), Double.parseDouble(keys[idxDamages])); - + } - + } catch (IOException e) { e.printStackTrace(); } - - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("Wrong damage per car per link!", 0.00011994155845965193, + + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("Wrong damage per car per link!", 0.00011994155845965193, marginaldamagesPerCar.get(Id.create("link2", Link.class)), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong damage per car per link!", 0.008531432493391652, + Assert.assertEquals("Wrong damage per car per link!", 0.008531432493391652, marginaldamagesPerCar.get(Id.create("linkA5", Link.class)), MatsimTestUtils.EPSILON); - Assert.assertEquals("Wrong damage per car per link!", 3.440988380343235E-8, + Assert.assertEquals("Wrong damage per car per link!", 3.440988380343235E-8, marginaldamagesPerCar.get(Id.create("linkB5", Link.class)), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("Wrong damage per car per link!", 1.1951678071236982E-4, @@ -850,7 +850,7 @@ else if(event.getActType().equals("work")){ Assert.assertEquals("Wrong damage per car per link!", 3.428802136662412E-8, marginaldamagesPerCar.get(Id.create("linkB5", Link.class)), MatsimTestUtils.EPSILON); } - + // ############################################ // test the noise-specific events // ############################################ @@ -861,8 +861,8 @@ else if(event.getActType().equals("work")){ tested = true; if (event.getTimeBinEndTime() == 11 * 3600. && event.getLinkId().toString().equals(Id.create("linkA5", Link.class).toString()) && event.getCausingVehicleId().toString().equals((Id.create("person_car_test1", Vehicle.class).toString()))) { - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("wrong cost per car for the given link and time interval", 0.0328089315079348, + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("wrong cost per car for the given link and time interval", 0.0328089315079348, event.getAmount(), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("wrong cost per car for the given link and time interval", 0.03269273886922247, @@ -870,8 +870,8 @@ else if(event.getActType().equals("work")){ } counter++; } else if (event.getTimeBinEndTime() == 11 * 3600. && event.getLinkId().toString().equals(Id.create("linkA5", Link.class).toString()) && event.getCausingVehicleId().toString().equals((Id.create("person_car_test2", Vehicle.class).toString()))) { - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("wrong cost per car for the given link and time interval", 0.0328089315079348, + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("wrong cost per car for the given link and time interval", 0.0328089315079348, event.getAmount(), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("wrong cost per car for the given link and time interval", 0.03269273886922247, @@ -879,8 +879,8 @@ else if(event.getActType().equals("work")){ } counter++; } else if (event.getTimeBinEndTime() == 11 * 3600. && event.getLinkId().toString().equals(Id.create("link2", Link.class).toString()) && event.getCausingVehicleId().toString().equals((Id.create("person_car_test1", Vehicle.class).toString()))) { - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("wrong cost per car for the given link and time interval", 3.992732562920194E-4, + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("wrong cost per car for the given link and time interval", 3.992732562920194E-4, event.getAmount(), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("wrong cost per car for the given link and time interval", 3.978592143117922E-4, @@ -888,8 +888,8 @@ else if(event.getActType().equals("work")){ } counter++; } else if (event.getTimeBinEndTime() == 11 * 3600. && event.getLinkId().toString().equals(Id.create("link2", Link.class).toString()) && event.getCausingVehicleId().toString().equals((Id.create("person_car_test2", Vehicle.class).toString()))) { - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("wrong cost per car for the given link and time interval", 3.992732562920194E-4, + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("wrong cost per car for the given link and time interval", 3.992732562920194E-4, event.getAmount(), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("wrong cost per car for the given link and time interval", 3.978592143117922E-4, @@ -900,18 +900,18 @@ else if(event.getActType().equals("work")){ log.warn(event.toString()); Assert.assertEquals("There should either be no further events, or the amount should be zero.", 0., event.getAmount(), MatsimTestUtils.EPSILON); } - } + } Assert.assertTrue("No event found to be tested.", tested); Assert.assertEquals("Wrong number of total events.", 4, counter, MatsimTestUtils.EPSILON); - + boolean tested2 = false; int counter2 = 0; for (NoiseEventAffected event : noiseCalculation.getTimeTracker().getDamageCalculation().getNoiseEventsAffected()) { tested2 = true; if (event.getTimeBinEndTime() == 11 * 3600. && event.getrReceiverPointId().toString().equals(Id.create("16", ReceiverPoint.class).toString()) && event.getAffectedAgentId().toString().equals((Id.create("person_car_test1", Person.class).toString())) && event.getActType().equals("work") ) { - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("wrong cost per car for the given link and time interval", 0.020745817449213576, + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("wrong cost per car for the given link and time interval", 0.020745817449213576, event.getAmount(), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("wrong cost per car for the given link and time interval", 0.02062821077070937, @@ -919,8 +919,8 @@ else if(event.getActType().equals("work")){ } counter2++; } else if (event.getTimeBinEndTime() == 11 * 3600. && event.getrReceiverPointId().toString().equals(Id.create("16", ReceiverPoint.class).toString()) && event.getAffectedAgentId().toString().equals((Id.create("person_car_test2", Person.class).toString())) && event.getActType().equals("work")) { - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("wrong cost per car for the given link and time interval", 0.017444990107520864, + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("wrong cost per car for the given link and time interval", 0.017444990107520864, event.getAmount(), MatsimTestUtils.EPSILON); } else { Assert.assertEquals("wrong cost per car for the given link and time interval",0.017327383429596242, @@ -928,71 +928,71 @@ else if(event.getActType().equals("work")){ } counter2++; } else if (event.getTimeBinEndTime() == 11 * 3600. && event.getrReceiverPointId().toString().equals(Id.create("16", ReceiverPoint.class).toString()) && event.getAffectedAgentId().toString().equals((Id.create("person_car_test3", Person.class).toString())) && event.getActType().equals("home")) { - if ( !!runConfig.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { - Assert.assertEquals("wrong cost per car for the given link and time interval", 0.028225601971719153, + if ( !!runConfig.routing().getAccessEgressType().equals(AccessEgressType.none) ) { + Assert.assertEquals("wrong cost per car for the given link and time interval", 0.028225601971719153, event.getAmount(), MatsimTestUtils.EPSILON); } else { - Assert.assertEquals("wrong cost per car for the given link and time interval", 0.028225601971719153, + Assert.assertEquals("wrong cost per car for the given link and time interval", 0.028225601971719153, event.getAmount(), MatsimTestUtils.EPSILON); } counter2++; } else { Assert.assertEquals("There should either be no further events, or the amount should be zero.", 0., event.getAmount(), MatsimTestUtils.EPSILON); } - - } + + } Assert.assertTrue("No event found to be tested.", tested2); Assert.assertEquals("Wrong number of total events.", 3, counter2, MatsimTestUtils.EPSILON); - + } - + // same test as before, but using the marginal cost approach @Test public final void test2b(){ - + String runDirectory = null; int lastIteration = -1; { // start a simple MATSim run with a single iteration String configFile = testUtils.getPackageInputDirectory() + "NoiseTest/config2.xml"; Config runConfig = ConfigUtils.loadConfig( configFile ) ; - runConfig.controler().setOutputDirectory(testUtils.getOutputDirectory()); + runConfig.controller().setOutputDirectory(testUtils.getOutputDirectory()); + + runConfig.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.none); + // I made test2a test both versions, but I don't really want to do that work again myself. kai, feb'16 - runConfig.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.none); - // I made test2a test both versions, but I don't really want to do that work again myself. kai, feb'16 - Controler controler = new Controler(runConfig); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); - controler.run(); - - runDirectory = controler.getConfig().controler().getOutputDirectory() + "/"; - lastIteration = controler.getConfig().controler().getLastIteration(); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + controler.run(); + + runDirectory = controler.getConfig().controller().getOutputDirectory() + "/"; + lastIteration = controler.getConfig().controller().getLastIteration(); } - + // run the noise analysis for the final iteration (offline) - + Config config = ConfigUtils.createConfig(); config.network().setInputFile(runDirectory + "output_network.xml.gz"); config.plans().setInputFile(runDirectory + "output_plans.xml.gz"); - config.controler().setOutputDirectory(runDirectory); - config.controler().setLastIteration(lastIteration); - + config.controller().setOutputDirectory(runDirectory); + config.controller().setLastIteration(lastIteration); + // adjust the default noise parameters NoiseConfigGroup noiseParameters = ConfigUtils.addOrGetModule(config, NoiseConfigGroup.class); - noiseParameters.setReceiverPointGap(250.); - + noiseParameters.setReceiverPointGap(250.); + String[] consideredActivities = {"home", "work"}; noiseParameters.setConsideredActivitiesForDamageCalculationArray(consideredActivities); - + noiseParameters.setScaleFactor(1.); noiseParameters.setNoiseAllocationApproach(NoiseConfigGroup.NoiseAllocationApproach.MarginalCost); noiseParameters.setUseActualSpeedLevel(false); noiseParameters.setAllowForSpeedsOutsideTheValidRange(true); Scenario scenario = ScenarioUtils.loadScenario(config); - + NoiseOfflineCalculation noiseCalculation = new NoiseOfflineCalculation(scenario, runDirectory); - noiseCalculation.run(); - + noiseCalculation.run(); + // ############################################ // test the noise-specific events // ############################################ @@ -1017,10 +1017,10 @@ public final void test2b(){ } else { Assert.assertEquals("There should either be no further events, or the amount should be zero.", 0., event.getAmount(), MatsimTestUtils.EPSILON); } - } + } Assert.assertTrue("No event found to be tested.", tested); Assert.assertEquals("Wrong number of total events.", 4, counter, MatsimTestUtils.EPSILON); - + boolean tested2 = false; int counter2 = 0; for (NoiseEventAffected event : noiseCalculation.getTimeTracker().getDamageCalculation().getNoiseEventsAffected()) { @@ -1038,97 +1038,97 @@ public final void test2b(){ } else { Assert.assertEquals("There should either be no further events, or the amount should be zero.", 0., event.getAmount(), MatsimTestUtils.EPSILON); } - - } + + } Assert.assertTrue("No event found to be tested.", tested2); Assert.assertEquals("Wrong number of total events.", 3, counter2, MatsimTestUtils.EPSILON); - + } - + // same test as 2a, but using the actual speed level @Test public final void test2c(){ - + // start a simple MATSim run with a single iteration String configFile = testUtils.getPackageInputDirectory() + "NoiseTest/config2.xml"; Controler controler = new Controler(configFile); - controler.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory()); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + controler.getConfig().controller().setOutputDirectory(testUtils.getOutputDirectory()); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); controler.run(); - + // run the noise analysis for the final iteration (offline) - - String runDirectory = controler.getConfig().controler().getOutputDirectory() + "/"; + + String runDirectory = controler.getConfig().controller().getOutputDirectory() + "/"; Config config = ConfigUtils.createConfig(new NoiseConfigGroup()); config.network().setInputFile(runDirectory + "output_network.xml.gz"); config.plans().setInputFile(runDirectory + "output_plans.xml.gz"); - config.controler().setOutputDirectory(runDirectory); - config.controler().setLastIteration(controler.getConfig().controler().getLastIteration()); - + config.controller().setOutputDirectory(runDirectory); + config.controller().setLastIteration(controler.getConfig().controller().getLastIteration()); + // adjust the default noise parameters NoiseConfigGroup noiseParameters = (NoiseConfigGroup) config.getModules().get(NoiseConfigGroup.GROUP_NAME); - noiseParameters.setReceiverPointGap(250.); - + noiseParameters.setReceiverPointGap(250.); + String[] consideredActivities = {"home", "work"}; noiseParameters.setConsideredActivitiesForDamageCalculationArray(consideredActivities); - + noiseParameters.setScaleFactor(1.); noiseParameters.setUseActualSpeedLevel(true); noiseParameters.setAllowForSpeedsOutsideTheValidRange(true); Scenario scenario = ScenarioUtils.loadScenario(config); - + NoiseOfflineCalculation noiseCalculation = new NoiseOfflineCalculation(scenario, runDirectory); - noiseCalculation.run(); - + noiseCalculation.run(); + EventsManager events = EventsUtils.createEventsManager(); - + final Map, List> eventsPerPersonId = new HashMap, List>(); - + events.addHandler(new ActivityStartEventHandler() { - + @Override public void reset(int iteration) { - + } - + @Override public void handleEvent(ActivityStartEvent event) { - + if(!eventsPerPersonId.containsKey(event.getPersonId())){ eventsPerPersonId.put(event.getPersonId(), new ArrayList()); } eventsPerPersonId.get(event.getPersonId()).add(event); - + } }); - + events.addHandler(new ActivityEndEventHandler() { - + @Override public void reset(int iteration) { - + } - + @Override public void handleEvent(ActivityEndEvent event) { - + if(!eventsPerPersonId.containsKey(event.getPersonId())){ eventsPerPersonId.put(event.getPersonId(), new ArrayList()); } eventsPerPersonId.get(event.getPersonId()).add(event); - + } }); - + MatsimEventsReader reader = new MatsimEventsReader(events); - reader.readFile(runDirectory + "ITERS/it." + config.controler().getLastIteration() + "/" + config.controler().getLastIteration() + ".events.xml.gz"); - + reader.readFile(runDirectory + "ITERS/it." + config.controller().getLastIteration() + "/" + config.controller().getLastIteration() + ".events.xml.gz"); + double endTime = 39600; - + String separator = ";"; String line = null; - + Map idxFromKey = new ConcurrentHashMap(); BufferedReader br; @@ -1137,82 +1137,82 @@ public void handleEvent(ActivityEndEvent event) { // ################################# line = null; - + String pathToEmissionsFile = runDirectory + "noise-analysis/emissions/emission_" + Double.toString(endTime) + ".csv"; - + Map, Double> emissionsPerLink = new HashMap, Double>(); idxFromKey = new ConcurrentHashMap(); - + br = IOUtils.getBufferedReader(pathToEmissionsFile); - + try { - + line = br.readLine(); String[] keys = line.split(separator); for(int i = 0; i < keys.length; i++){ idxFromKey.put(keys[i], i); } - + int idxLinkId = idxFromKey.get("Link Id"); int idxNoiseEmission = idxFromKey.get("Noise Emission " + Time.writeTime(endTime, Time.TIMEFORMAT_HHMMSS)); - + while((line = br.readLine()) != null){ - + keys = line.split(separator); emissionsPerLink.put(Id.create(keys[idxLinkId], Link.class), Double.parseDouble(keys[idxNoiseEmission])); - + } - + Assert.assertEquals("Wrong amount of emission!", 56.4418948379387, emissionsPerLink.get(Id.create("link2", Link.class)), MatsimTestUtils.EPSILON); Assert.assertEquals("Wrong amount of emission!", 77.3994680630406, emissionsPerLink.get(Id.create("linkA5", Link.class)), MatsimTestUtils.EPSILON); Assert.assertEquals("Wrong amount of emission!", 0., emissionsPerLink.get(Id.create("link4", Link.class)), MatsimTestUtils.EPSILON); - + } catch (IOException e) { e.printStackTrace(); } } - + // tests the static methods within class "noiseEquations" @Test public final void test3(){ - + double p = 0; double pInPercent = 0; double vCar = 100; double vHgv = vCar; - + // test speed correction term double eCar = 27.7 + 10 * Math.log10( 1 + Math.pow((0.02 * vCar), 3) ); double eHgv = 23.1 + 12.5 * Math.log10( vHgv ); - + double expectedEcar = 37.2424250943932; double expectedEhgv = 48.1; - + Assert.assertEquals("Error in deviation term for speed correction (car)", expectedEcar, eCar, MatsimTestUtils.EPSILON); Assert.assertEquals("Error in deviation term for speed correction (car)", expectedEcar, RLS90NoiseEmission.calculateLCar(vCar), MatsimTestUtils.EPSILON); Assert.assertEquals("Error in deviation term for speed correction (hgv)", expectedEhgv, eHgv, MatsimTestUtils.EPSILON); Assert.assertEquals("Error in deviation term for speed correction (hgv)", expectedEhgv, RLS90NoiseEmission.calculateLHdv(vHgv), MatsimTestUtils.EPSILON); - + Assert.assertTrue("Error in deviation term for speed correction (eCar > eHgv)", eCar < eHgv); - + // test mittelungspegel and speed correction - + for(double nHgvs = 0; nHgvs < 3; nHgvs++){ - + for(double nCars = 0; nCars < 3; nCars++){ - + int n = (int) (nCars + nHgvs); - + if(n > 0){ p = nHgvs / n; pInPercent = 100 * p; } - + // test computation of mittelungspegel double mittelungspegel = 37.3 + 10 * Math.log10( n * ( 1 + 0.082 * pInPercent ) ); - + double expectedMittelungspegel = Double.NEGATIVE_INFINITY; - + if(nHgvs == 0){ if(nCars == 1) expectedMittelungspegel = 37.3; else if(nCars == 2) expectedMittelungspegel = 40.3102999566398; @@ -1228,51 +1228,51 @@ else if( nHgvs == 2){ else if( nCars == 2) expectedMittelungspegel = 50.396301674259; } } - + Assert.assertEquals("Error while calculating Mittelungspegel for " + nCars + " car(s) and " + nHgvs + " hgv(s)!", expectedMittelungspegel, mittelungspegel, MatsimTestUtils.EPSILON); Assert.assertEquals("Error while calculating Mittelungspegel for " + nCars + " car(s) and " + nHgvs + " hgv(s)!", expectedMittelungspegel, RLS90NoiseEmission.calculateMittelungspegelLm(n, p), MatsimTestUtils.EPSILON); - + //test speed correction double speedCorrection = expectedEcar - 37.3 + 10 * Math.log10( (100 + ( Math.pow(10, 0.1*(expectedEhgv - expectedEcar)) - 1 ) * pInPercent ) / (100 + 8.23*pInPercent) ); - + double expectedSpeedCorrection = -0.0575749056067494; - + if(p == 1./3.) expectedSpeedCorrection = 0.956336446449128; else if(p == 0.5) expectedSpeedCorrection = 1.04384127904235; else if(p == 2./3.) expectedSpeedCorrection = 1.09354779994927; else if( p == 1) expectedSpeedCorrection = 1.14798298974089; - + Assert.assertEquals("Error while calculating speed correction term for p = " + p + "!", expectedSpeedCorrection, speedCorrection, MatsimTestUtils.EPSILON); Assert.assertEquals("Error while calculating speed correction term for p = " + p + "!", expectedSpeedCorrection, RLS90NoiseEmission.calculateGeschwindigkeitskorrekturDv(vCar, vHgv, p), MatsimTestUtils.EPSILON); } - + } - + // test distance correction term for(double distance = 5.; distance <= 140; distance += 45.){ - + double distanceCorrection = 15.8 - 10 * Math.log10( distance ) - 0.0142 * Math.pow(distance, 0.9); - + double expectedDistanceCorrection = 0.; - + if(distance == 5) expectedDistanceCorrection = 8.74985482214084; else if(distance == 50) expectedDistanceCorrection = -1.66983281320262; else if(distance == 95) expectedDistanceCorrection = -4.8327746143211; else if(distance == 140) expectedDistanceCorrection = -6.87412053759382; - + Assert.assertEquals("Error while calculating distance correction term!", expectedDistanceCorrection, distanceCorrection, MatsimTestUtils.EPSILON); Assert.assertEquals("Error while calculating distance correction term!", expectedDistanceCorrection, RLS90NoiseImmission.calculateDistanceCorrection(distance), MatsimTestUtils.EPSILON); - + } // test angle correction term for(double angle = 45; angle <= 360; angle += 45){ - + double angleCorrection = 10 * Math.log10( angle / 180 ); - + double expectedAngleCorrection = 0.; - + if(angle == 45) expectedAngleCorrection = -6.02059991327962; else if(angle == 90) expectedAngleCorrection = -3.01029995663981; else if(angle == 135) expectedAngleCorrection = -1.249387366083; @@ -1281,12 +1281,12 @@ else if( nHgvs == 2){ else if(angle == 270) expectedAngleCorrection = 1.76091259055681; else if(angle == 315) expectedAngleCorrection = 2.43038048686294; else if(angle == 360) expectedAngleCorrection = 3.01029995663981; - + Assert.assertEquals("Error while calculating angle correction term!", expectedAngleCorrection, angleCorrection, MatsimTestUtils.EPSILON); Assert.assertEquals("Error while calculating angle correction term!", expectedAngleCorrection, RLS90NoiseImmission.calculateAngleCorrection(angle), MatsimTestUtils.EPSILON); - + } - + //test resulting noise immission double distance1 = 120; double angle1 = 120; @@ -1297,34 +1297,34 @@ else if( nHgvs == 2){ double distance3 = 399; double angle3 = 10; double emission3 = 50; - + double distanceCorrection1 = 15.8 - 10 * Math.log10( distance1 ) - 0.0142 * Math.pow(distance1, 0.9); double angleCorrection1 = 10 * Math.log10( angle1 / 180 ); double distanceCorrection2 = 15.8 - 10 * Math.log10( distance2 ) - 0.0142 * Math.pow(distance2, 0.9); double angleCorrection2 = 10 * Math.log10( angle2 / 180 ); double distanceCorrection3 = 15.8 - 10 * Math.log10( distance3 ) - 0.0142 * Math.pow(distance3, 0.9); double angleCorrection3 = 10 * Math.log10( angle3 / 180 ); - + double i1 = emission1 + distanceCorrection1 + angleCorrection1; double i2 = emission2 + distanceCorrection2 + angleCorrection2; double i3 = emission3 + distanceCorrection3 + angleCorrection3; - + double[] immissionsArray = {i1,i2,i3}; - + List immissions = new ArrayList(); immissions.add(i1); immissions.add(i2); immissions.add(i3); - + double tmp = 0.; - + for(double d : immissionsArray){ tmp += Math.pow(10, 0.1*d); } - + double resultingNoiseImmission = 10*Math.log10(tmp); double expectedResultingNoiseImmission = 41.279204220881; - + Assert.assertEquals("Error in noise immission calculation!", expectedResultingNoiseImmission, resultingNoiseImmission, MatsimTestUtils.EPSILON); double resultingNoiseImmission1 = 0.; @@ -1341,124 +1341,124 @@ else if( nHgvs == 2){ } } Assert.assertEquals("Error in noise immission calculation!", expectedResultingNoiseImmission, resultingNoiseImmission1, MatsimTestUtils.EPSILON); - + //test noise damage double annualCostRate = (85.0/(1.95583)) * (Math.pow(1.02, (2014-1995))); - + double thresholdDay = 50; double thresholdEvening = 45; double thresholdNight = 40; - + int nPersons = 4; - + double costsDay = resultingNoiseImmission > thresholdDay ? annualCostRate * 3600/(365*24) * nPersons/3600 * Math.pow(2, 0.1 * (resultingNoiseImmission - thresholdDay)) : 0.; double costsEvening = resultingNoiseImmission > thresholdEvening ? annualCostRate * 3600/(365*24) * nPersons/3600 * Math.pow(2, 0.1 * (resultingNoiseImmission - thresholdEvening)) : 0.; double costsNight = resultingNoiseImmission > thresholdNight ? annualCostRate * 3600/(365*24) * nPersons/3600 * Math.pow(2, 0.1 * (resultingNoiseImmission - thresholdNight)) : 0.; - + double expectedCostsDay = 0.; double expectedCostsEvening = 0.; double expectedCostsNight = 0.031590380365211; - + Assert.assertEquals("Error in damage calculation!", expectedCostsDay, costsDay , MatsimTestUtils.EPSILON); Assert.assertEquals("Error in damage calculation!", expectedCostsDay, NoiseDamageCalculation.calculateDamageCosts(resultingNoiseImmission, nPersons, 7.*3600, annualCostRate, 3600.) , MatsimTestUtils.EPSILON); Assert.assertEquals("Error in damage calculation!", expectedCostsEvening, costsEvening, MatsimTestUtils.EPSILON); Assert.assertEquals("Error in damage calculation!", expectedCostsEvening, NoiseDamageCalculation.calculateDamageCosts(resultingNoiseImmission, nPersons, 19.*3600, annualCostRate, 3600.), MatsimTestUtils.EPSILON); Assert.assertEquals("Error in damage calculation!", expectedCostsNight, costsNight, MatsimTestUtils.EPSILON); Assert.assertEquals("Error in damage calculation!", expectedCostsNight, NoiseDamageCalculation.calculateDamageCosts(resultingNoiseImmission, nPersons, 23.*3600, annualCostRate, 3600.), MatsimTestUtils.EPSILON); - } - + } + // tests the static methods within class "noiseEquations" @Test public final void test4(){ - + double vCar = 0.0496757749985181; double vHGV = 0.0478758773550055; int nCar = 119; int nHGV = 4; - + int n = (nCar + nHGV) * 10; - - double p = ( (double) nHGV / (double) (nCar + nHGV)); - + + double p = ( (double) nHGV / (double) (nCar + nHGV)); + double mittelungspegel = RLS90NoiseEmission.calculateMittelungspegelLm(n, p); Assert.assertEquals("Wrong mittelungspegel for n="+ n + " and p=" + p + "!", 69.22567453336540, mittelungspegel, MatsimTestUtils.EPSILON); - + double lCar = RLS90NoiseEmission.calculateLCar(vCar); Assert.assertEquals("Wrong LCar for vCar="+ vCar + "!", 27.70000000425900, lCar, MatsimTestUtils.EPSILON); - + double lHGV = RLS90NoiseEmission.calculateLHdv(vHGV); Assert.assertEquals("Wrong LHGV for vHGV="+ vHGV + "!", 6.60145932205085, lHGV, MatsimTestUtils.EPSILON); double dV = RLS90NoiseEmission.calculateGeschwindigkeitskorrekturDv(vCar, vHGV, p); Assert.assertEquals("Wrong Dv!", -10.772415234056300, dV, MatsimTestUtils.EPSILON); - + double emission = mittelungspegel + dV; Assert.assertEquals("Wrong emission!", 58.453259299309124, emission, MatsimTestUtils.EPSILON); - + // plus one car - + int nPlusOneCar = (nCar+1 + nHGV) * 10; - double pPlusOneCar = ( (double) nHGV / (double) ((nCar + 1) + nHGV)); + double pPlusOneCar = ( (double) nHGV / (double) ((nCar + 1) + nHGV)); double mittelungspegelPlusOneCar = RLS90NoiseEmission.calculateMittelungspegelLm(nPlusOneCar, pPlusOneCar); double dVPlusOneCar = RLS90NoiseEmission.calculateGeschwindigkeitskorrekturDv(vCar, vHGV, pPlusOneCar); double emissionPlusOneCar = mittelungspegelPlusOneCar + dVPlusOneCar; Assert.assertEquals("Wrong emission!", 58.4896140186478, emissionPlusOneCar, MatsimTestUtils.EPSILON); - + // plus one HGV - + int nPlusOneHGV = (nCar + nHGV + 1) * 10; - double pPlusOneHGV = ( (double) (nHGV + 1) / (double) (nCar + (nHGV + 1))); + double pPlusOneHGV = ( (double) (nHGV + 1) / (double) (nCar + (nHGV + 1))); double mittelungspegelPlusOneHGV = RLS90NoiseEmission.calculateMittelungspegelLm(nPlusOneHGV, pPlusOneHGV); double dVPlusOneHGV = RLS90NoiseEmission.calculateGeschwindigkeitskorrekturDv(vCar, vHGV, pPlusOneHGV); double emissionPlusOneHGV = mittelungspegelPlusOneHGV + dVPlusOneHGV; Assert.assertEquals("Wrong emission!", 58.4529399949061, emissionPlusOneHGV, MatsimTestUtils.EPSILON); } - + // tests the static methods within class "noiseEquations" - other speed levels @Test public final void test5(){ - + double vCar = 30; double vHGV = 30; int nCar = 119; int nHGV = 4; - + int n = (nCar + nHGV) * 10; - - double p = ( (double) nHGV / (double) (nCar + nHGV)); - + + double p = ( (double) nHGV / (double) (nCar + nHGV)); + double mittelungspegel = RLS90NoiseEmission.calculateMittelungspegelLm(n, p); Assert.assertEquals("Wrong mittelungspegel for n="+ n + " and p=" + p + "!", 69.22567453336540, mittelungspegel, MatsimTestUtils.EPSILON); - + double lCar = RLS90NoiseEmission.calculateLCar(vCar); Assert.assertEquals("Wrong LCar for vCar="+ vCar + "!", 28.54933574936720, lCar, MatsimTestUtils.EPSILON); - + double lHGV = RLS90NoiseEmission.calculateLHdv(vHGV); Assert.assertEquals("Wrong LHGV for vHGV="+ vHGV + "!", 41.56401568399580, lHGV, MatsimTestUtils.EPSILON); double dV = RLS90NoiseEmission.calculateGeschwindigkeitskorrekturDv(vCar, vHGV, p); Assert.assertEquals("Wrong Dv!", -7.689390421466860, dV, MatsimTestUtils.EPSILON); - + double emission = mittelungspegel + dV; Assert.assertEquals("Wrong emission!", 61.5362841118986, emission, MatsimTestUtils.EPSILON); - + // plus one car - + int nPlusOneCar = (nCar+1 + nHGV) * 10; - double pPlusOneCar = ( (double) nHGV / (double) ((nCar + 1) + nHGV)); + double pPlusOneCar = ( (double) nHGV / (double) ((nCar + 1) + nHGV)); double mittelungspegelPlusOneCar = RLS90NoiseEmission.calculateMittelungspegelLm(nPlusOneCar, pPlusOneCar); double dVPlusOneCar = RLS90NoiseEmission.calculateGeschwindigkeitskorrekturDv(vCar, vHGV, pPlusOneCar); double emissionPlusOneCar = mittelungspegelPlusOneCar + dVPlusOneCar; Assert.assertEquals("Wrong emission!", 61.5580658162266, emissionPlusOneCar, MatsimTestUtils.EPSILON); - + // plus one HGV - + int nPlusOneHGV = (nCar + nHGV + 1) * 10; - double pPlusOneHGV = ( (double) (nHGV + 1) / (double) (nCar + (nHGV + 1))); + double pPlusOneHGV = ( (double) (nHGV + 1) / (double) (nCar + (nHGV + 1))); double mittelungspegelPlusOneHGV = RLS90NoiseEmission.calculateMittelungspegelLm(nPlusOneHGV, pPlusOneHGV); double dVPlusOneHGV = RLS90NoiseEmission.calculateGeschwindigkeitskorrekturDv(vCar, vHGV, pPlusOneHGV); double emissionPlusOneHGV = mittelungspegelPlusOneHGV + dVPlusOneHGV; - Assert.assertEquals("Wrong emission!", 61.9518310976080, emissionPlusOneHGV, MatsimTestUtils.EPSILON); + Assert.assertEquals("Wrong emission!", 61.9518310976080, emissionPlusOneHGV, MatsimTestUtils.EPSILON); } } diff --git a/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseOnlineExampleIT.java b/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseOnlineExampleIT.java index 71cee7bb30c..c03d5d04e57 100644 --- a/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseOnlineExampleIT.java +++ b/contribs/noise/src/test/java/org/matsim/contrib/noise/NoiseOnlineExampleIT.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.noise; @@ -53,7 +53,7 @@ public class NoiseOnlineExampleIT { private static final Logger log = LogManager.getLogger( NoiseOnlineExampleIT.class ) ; - + @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); @@ -62,8 +62,8 @@ public final void test0(){ String configFile = testUtils.getPackageInputDirectory() + "config.xml"; Config config = ConfigUtils.loadConfig(configFile, new NoiseConfigGroup()); - config.controler().setLastIteration(1); - config.controler().setOutputDirectory( testUtils.getOutputDirectory() ); + config.controller().setLastIteration(1); + config.controller().setOutputDirectory( testUtils.getOutputDirectory() ); NoiseConfigGroup noiseParameters = (NoiseConfigGroup) config.getModule("noise"); noiseParameters.setWriteOutputIteration(1); @@ -73,8 +73,8 @@ public final void test0(){ controler.addOverridingModule(new NoiseModule()); controler.run(); - String workingDirectory = controler.getConfig().controler().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controler().getLastIteration() + "/immissions/"; - String receiverPointsFile = controler.getConfig().controler().getOutputDirectory() + "/receiverPoints/receiverPoints.csv"; + String workingDirectory = controler.getConfig().controller().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controller().getLastIteration() + "/immissions/"; + String receiverPointsFile = controler.getConfig().controller().getOutputDirectory() + "/receiverPoints/receiverPoints.csv"; ProcessNoiseImmissions processNoiseImmissions = new ProcessNoiseImmissions(workingDirectory, receiverPointsFile, noiseParameters.getReceiverPointGap()); processNoiseImmissions.run(); } @@ -83,8 +83,8 @@ public final void test0(){ public final void testOnTheFlyAggregationTerms() { String configFile = testUtils.getPackageInputDirectory() + "config.xml"; Config config = ConfigUtils.loadConfig(configFile, new NoiseConfigGroup()); - config.controler().setLastIteration(1); - config.controler().setOutputDirectory( testUtils.getOutputDirectory() ); + config.controller().setLastIteration(1); + config.controller().setOutputDirectory( testUtils.getOutputDirectory() ); NoiseConfigGroup noiseParameters = (NoiseConfigGroup) config.getModule("noise"); noiseParameters.setWriteOutputIteration(1); @@ -127,12 +127,12 @@ public final void testOnTheFlyAggregationTerms() { controler.run(); //run file based noise processing as reference - String workingDirectory = controler.getConfig().controler().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controler().getLastIteration() + "/immissions/"; - String receiverPointsFile = controler.getConfig().controler().getOutputDirectory() + "/receiverPoints/receiverPoints.csv"; + String workingDirectory = controler.getConfig().controller().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controller().getLastIteration() + "/immissions/"; + String receiverPointsFile = controler.getConfig().controller().getOutputDirectory() + "/receiverPoints/receiverPoints.csv"; ProcessNoiseImmissions processNoiseImmissions = new ProcessNoiseImmissions(workingDirectory, receiverPointsFile, noiseParameters.getReceiverPointGap()); processNoiseImmissions.run(); - String pathToImmissionsFile = controler.getConfig().controler().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controler().getLastIteration() + "/immissions/immission_processed.csv"; + String pathToImmissionsFile = controler.getConfig().controller().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controller().getLastIteration() + "/immissions/immission_processed.csv"; //store file based noise aggregation terms by receiver Map, Double> ldenByRp = new HashMap<>(); @@ -183,8 +183,8 @@ public final void testOnTheFlyAggregationTerms() { public final void testNoiseListener(){ Config config = ConfigUtils.loadConfig( testUtils.getPackageInputDirectory() + "config.xml", new NoiseConfigGroup() ); - config.controler().setLastIteration(1); - config.controler().setOutputDirectory( testUtils.getOutputDirectory() ); + config.controller().setLastIteration(1); + config.controller().setOutputDirectory( testUtils.getOutputDirectory() ); NoiseConfigGroup noiseParameters = (NoiseConfigGroup) config.getModule("noise"); noiseParameters.setWriteOutputIteration(1); @@ -206,8 +206,8 @@ public final void testNoiseListener(){ controler.run(); - String workingDirectory = controler.getConfig().controler().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controler().getLastIteration() + "/immissions/"; - String receiverPointsFile = controler.getConfig().controler().getOutputDirectory() + "/receiverPoints/receiverPoints.csv"; + String workingDirectory = controler.getConfig().controller().getOutputDirectory() + "/ITERS/it." + controler.getConfig().controller().getLastIteration() + "/immissions/"; + String receiverPointsFile = controler.getConfig().controller().getOutputDirectory() + "/receiverPoints/receiverPoints.csv"; ProcessNoiseImmissions processNoiseImmissions = new ProcessNoiseImmissions(workingDirectory, receiverPointsFile, noiseParameters.getReceiverPointGap()); processNoiseImmissions.addListener( new NoiseModule.NoiseListener() { @Override public void newRecord( XYTRecord record ) { log.warn( record ) ; } diff --git a/contribs/otfvis/src/main/java/org/matsim/contrib/otfvis/OTFVisFileWriterModule.java b/contribs/otfvis/src/main/java/org/matsim/contrib/otfvis/OTFVisFileWriterModule.java index 0475b256630..7ea8fb8d7d5 100644 --- a/contribs/otfvis/src/main/java/org/matsim/contrib/otfvis/OTFVisFileWriterModule.java +++ b/contribs/otfvis/src/main/java/org/matsim/contrib/otfvis/OTFVisFileWriterModule.java @@ -23,18 +23,17 @@ package org.matsim.contrib.otfvis; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.vis.otfvis.OTFFileWriterFactory; import org.matsim.vis.otfvis.OTFVisConfigGroup; -import static org.matsim.core.config.groups.ControlerConfigGroup.*; +import static org.matsim.core.config.groups.ControllerConfigGroup.*; public class OTFVisFileWriterModule extends AbstractModule { @Override public void install() { ConfigUtils.addOrGetModule(getConfig(), OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class); - if (getConfig().controler().getSnapshotFormat().contains( SnapshotFormat.otfvis )) { + if (getConfig().controller().getSnapshotFormat().contains( SnapshotFormat.otfvis )) { addSnapshotWriterBinding().toProvider(OTFFileWriterFactory.class); } } diff --git a/contribs/otfvis/src/test/java/org/matsim/contrib/otfvis/OTFVisIT.java b/contribs/otfvis/src/test/java/org/matsim/contrib/otfvis/OTFVisIT.java index e178622e938..d713edcd6ab 100644 --- a/contribs/otfvis/src/test/java/org/matsim/contrib/otfvis/OTFVisIT.java +++ b/contribs/otfvis/src/test/java/org/matsim/contrib/otfvis/OTFVisIT.java @@ -19,7 +19,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.otfvis; @@ -28,7 +28,6 @@ import org.junit.Test; 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.QSimConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup.SnapshotStyle; import org.matsim.core.controler.Controler; @@ -36,17 +35,16 @@ import org.matsim.testcases.MatsimTestUtils; import java.io.File; -import java.util.Arrays; import java.util.Collections; -import static org.matsim.core.config.groups.ControlerConfigGroup.*; +import static org.matsim.core.config.groups.ControllerConfigGroup.*; /** * Simple test case to ensure the converting from eventsfile to .mvi-file * Needs somehow a bunch of memory - please use "-Xmx630m"! - * + * * @author yu - * + * */ public class OTFVisIT { @@ -69,20 +67,20 @@ public void testConvert() { @Test public void testOTFVisSnapshotWriterOnQSim() { final Config config = ConfigUtils.loadConfig("test/scenarios/equil/config_plans1.xml"); - config.controler().setLastIteration(2); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); - config.controler().setMobsim("qsim"); - config.controler().setSnapshotFormat( Collections.singletonList( SnapshotFormat.otfvis ) ); + config.controller().setLastIteration(2); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); + config.controller().setMobsim("qsim"); + config.controller().setSnapshotFormat( Collections.singletonList( SnapshotFormat.otfvis ) ); QSimConfigGroup qSimConfigGroup = config.qsim(); qSimConfigGroup.setSnapshotPeriod(600); qSimConfigGroup.setSnapshotStyle( SnapshotStyle.equiDist ) ;; final Controler controler = new Controler(config); controler.addOverridingModule(new OTFVisFileWriterModule()); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); Assert.assertTrue(new File(controler.getControlerIO().getIterationFilename(0, "otfvis.mvi")).exists()); diff --git a/contribs/otfvis/src/test/java/org/matsim/vis/otfvis/checklists/T2_RunControlerWithMovieOutput.java b/contribs/otfvis/src/test/java/org/matsim/vis/otfvis/checklists/T2_RunControlerWithMovieOutput.java index 2cfc0f5e895..0469294ebc4 100644 --- a/contribs/otfvis/src/test/java/org/matsim/vis/otfvis/checklists/T2_RunControlerWithMovieOutput.java +++ b/contribs/otfvis/src/test/java/org/matsim/vis/otfvis/checklists/T2_RunControlerWithMovieOutput.java @@ -1,6 +1,6 @@ /* *********************************************************************** * * project: org.matsim.* - * + * * * * *********************************************************************** * * * @@ -31,10 +31,10 @@ public class T2_RunControlerWithMovieOutput { public static void main(String[] args) { Controler con = new Controler("test/scenarios/equil/config-qsim.xml"); - con.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + con.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); con.addOverridingModule(new OTFVisFileWriterModule()); con.run(); - System.out.println("\n QSim is done. Output:" + con.getConfig().controler().getOutputDirectory()); + System.out.println("\n QSim is done. Output:" + con.getConfig().controller().getOutputDirectory()); } } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/package-info.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/package-info.java index 8487313fadf..005b83994a3 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/package-info.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/package-info.java @@ -1,17 +1,20 @@ /** - * The parking contrib is split into three substantially different parts
      + * The parking contrib is split into several substantially different parts
        + * *
      • Parking Choice, based on work of Rashid Waraich. Parts of the contrib are used in the carsharing contrib. - *

        Its main goal, as far as we understand it, is the simulation of parking choice (e.g. between garages). There is no modelling of circulating traffic searching for parking or walking of agents to/from parking. Currently (2022) unmaintained. + *

        Its main goal, as far as we understand it, is the simulation of parking choice (e.g. between garages). + * There is no modelling of circulating traffic searching for parking or walking of agents to/from parking. Currently (2022) unmaintained. * *

      • Parking Search, by Joschka Bischoff. This contrib is currently developed at TU Berlin. *

        The main goal is to model parking search, including walk legs of agents and vehicles searching for parking spaces. - *

      * - *
        Parking Proxy by Tobias Kohl (Senozon) - *

        This was designed for large scenarios where it's not feasable to fully simulate parking agents. Rather, the additional time needed for parking is estimated

        - *
      - * *
        Parking Costs, developed by Marcel Rieser and Joschka Bischoff at SBB. + *
      • Parking Proxy by Tobias Kohl (Senozon) + *

        This was designed for large scenarios where it's not feasable to fully simulate parking agents. + * Rather, the additional time needed for parking is estimated

        + * + *
      • Parking Costs, developed by Marcel Rieser and Joschka Bischoff at SBB. *

        This modules allows the integration of parking costs based on link attribute data.

        + * *
      * * @author of this doc: jfbischoff, nagel diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java index a25725940c1..49fd0109768 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java @@ -60,7 +60,7 @@ public double calcWalkScore(Coord destCoord, PC2Parking parking, Id pers double linkLength = link.getLength(); double walkDistance = CoordUtils.calcEuclideanDistance(destCoord, parking.getCoordinate()) - * scenario.getConfig().plansCalcRoute().getBeelineDistanceFactors().get("walk")* beelineDistanceFactor; + * scenario.getConfig().routing().getBeelineDistanceFactors().get("walk")* beelineDistanceFactor; double walkSpeed = linkLength / this.walkTravelTime.getLinkTravelTime(link, 0, person, null); diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/run/RunParkingChoiceExample.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/run/RunParkingChoiceExample.java index 35113f4625a..e53da13e52d 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/run/RunParkingChoiceExample.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/run/RunParkingChoiceExample.java @@ -44,8 +44,8 @@ /** * @author jbischoff * Sample main file for setting up an Matsim run with parking. Check the output events for Parking events and the scores. - * - * + * + * */ public class RunParkingChoiceExample { @@ -58,12 +58,12 @@ public static void run(Config config) { Scenario scenario = ScenarioUtils.loadScenario(config); Controler controler = new Controler(scenario); - controler.getConfig().controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); + controler.getConfig().controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); // --- // we need some settings to walk from parking to destination: - ParkingScore parkingScoreManager = new ParkingScoreManager(new WalkTravelTime(controler.getConfig().plansCalcRoute()), scenario); + ParkingScore parkingScoreManager = new ParkingScoreManager(new WalkTravelTime(controler.getConfig().routing()), scenario); parkingScoreManager.setParkingScoreScalingFactor(1); parkingScoreManager.setParkingBetas(new ParkingBetaExample()); diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingcost/module/ParkingCostModule.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingcost/module/ParkingCostModule.java index a28c002a198..ae27638cb26 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingcost/module/ParkingCostModule.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingcost/module/ParkingCostModule.java @@ -35,7 +35,7 @@ public class ParkingCostModule extends AbstractModule { public void install() { ParkingCostConfigGroup parkingCostConfigGroup = ConfigUtils.addOrGetModule(getConfig(), ParkingCostConfigGroup.class); if (parkingCostConfigGroup.useParkingCost) { - Collection mainModes = switch (getConfig().controler().getMobsim()) { + Collection mainModes = switch (getConfig().controller().getMobsim()) { case "qsim" -> getConfig().qsim().getMainModes(); case "hermes" -> getConfig().hermes().getMainModes(); default -> throw new RuntimeException("ParkingCosts are currently supported for Qsim and Hermes"); diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingproxy/run/RunWithParkingProxy.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingproxy/run/RunWithParkingProxy.java index 0f243e6e035..9603f5a23ce 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingproxy/run/RunWithParkingProxy.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingproxy/run/RunWithParkingProxy.java @@ -22,7 +22,7 @@ import org.matsim.contrib.parking.parkingproxy.ParkingProxyModule; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.scenario.ScenarioUtils; @@ -31,21 +31,21 @@ public class RunWithParkingProxy { public static void main(String[] args) { - + ParkingProxyConfigGroup parkingConfig = new ParkingProxyConfigGroup(); Config config = ConfigUtils.loadConfig(args, parkingConfig); //config.controler().setLastIteration(100); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - config.plansCalcRoute().setAccessEgressType(AccessEgressType.accessEgressModeToLink); - config.planCalcScore().setWriteExperiencedPlans(true); - + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + config.routing().setAccessEgressType(AccessEgressType.accessEgressModeToLink); + config.scoring().setWriteExperiencedPlans(true); + Scenario scen = ScenarioUtils.loadScenario(config); - + Controler controler = new Controler(scen); - + controler.addOverridingModule(new ParkingProxyModule(scen) ); - + controler.run(); } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/RunParkingSearchExample.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/RunParkingSearchExample.java index 0d0554b739f..bf76aceb42b 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/RunParkingSearchExample.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/RunParkingSearchExample.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.parking.parkingsearch; @@ -45,10 +45,10 @@ public class RunParkingSearchExample { public static void main(String[] args) { - + Config config = ConfigUtils.loadConfig("parkingsearch/config.xml", new ParkingSearchConfigGroup()); //all further input files are set in the config. - + //get the parking search config group to set some parameters, like agent's search strategy or average parking slot length ParkingSearchConfigGroup configGroup = (ParkingSearchConfigGroup) config.getModules().get(ParkingSearchConfigGroup.GROUP_NAME); configGroup.setParkingSearchStrategy(ParkingSearchStrategy.Benenson); @@ -56,9 +56,9 @@ public static void main(String[] args) { // set to false, if you don't require visualisation, then the example will run for 10 iterations, with OTFVis, only one iteration is performed. boolean otfvis = false; if (otfvis) { - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); } else { - config.controler().setLastIteration(10); + config.controller().setLastIteration(10); } new RunParkingSearchExample().run(config,otfvis); @@ -75,9 +75,9 @@ public void run(Config config, boolean otfvis) { Controler controler = new Controler(scenario); config.qsim().setSnapshotStyle(SnapshotStyle.withHoles); - + controler.addOverridingModule(new AbstractModule() { - + @Override public void install() { ParkingSlotVisualiser visualiser = new ParkingSlotVisualiser(scenario); diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/evaluation/ZoneParkingOccupationListener.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/evaluation/ZoneParkingOccupationListener.java index 1dbf981bcc1..e8f4e8dfcaa 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/evaluation/ZoneParkingOccupationListener.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/evaluation/ZoneParkingOccupationListener.java @@ -1,5 +1,5 @@ /** - * + * */ package org.matsim.contrib.parking.parkingsearch.evaluation; @@ -29,22 +29,22 @@ * */ public class ZoneParkingOccupationListener implements MobsimBeforeCleanupListener, MobsimAfterSimStepListener{ - + private final ZoneParkingManager zoneManager; private Logger log = LogManager.getLogger(ZoneParkingOccupationListener.class); - private HashMap> zoneOccupationPerTime; + private HashMap> zoneOccupationPerTime; private MatsimServices services; int iteration; - + private TreeSet allMonitoredTimeStamps; - + /** - * + * */ @Inject public ZoneParkingOccupationListener(ParkingSearchManager manager, MatsimServices services, Config config) { this.zoneManager = (ZoneParkingManager) manager; - iteration = config.controler().getFirstIteration(); + iteration = config.controller().getFirstIteration(); this.services = services; this.zoneOccupationPerTime = new HashMap>(); for(String zone : zoneManager.getZones()){ @@ -56,14 +56,14 @@ public ZoneParkingOccupationListener(ParkingSearchManager manager, MatsimService @Override public void notifyMobsimAfterSimStep(MobsimAfterSimStepEvent e) { if( (e.getSimulationTime()%900) == 0 && !(e.getSimulationTime() == 0)){ - + double timeStamp = e.getSimulationTime(); if (!(this.allMonitoredTimeStamps.contains(timeStamp)) ) this.allMonitoredTimeStamps.add(timeStamp); - + for(String zone : this.zoneOccupationPerTime.keySet()){ double occ = this.zoneManager.getOccupancyRatioOfZone(zone); ParkingTuple tuple = new ParkingTuple(timeStamp, occ); - this.zoneOccupationPerTime.get(zone).add(tuple); + this.zoneOccupationPerTime.get(zone).add(tuple); } } } @@ -81,10 +81,10 @@ public void notifyMobsimBeforeCleanup(MobsimBeforeCleanupEvent e) { this.zoneOccupationPerTime.put(zone, tSet); this.allMonitoredTimeStamps.clear(); this.allMonitoredTimeStamps.add(-1.0); - } + } iteration++; } - + private void writeStats(String fileName) { log.error("WRITING OCCUPANCY STATS TO " + fileName); @@ -92,7 +92,7 @@ private void writeStats(String fileName) { for(double d : this.allMonitoredTimeStamps){ head += "" + d +";"; } - + BufferedWriter bw = IOUtils.getBufferedWriter(fileName); try { bw.write(head); @@ -104,10 +104,10 @@ private void writeStats(String fileName) { TreeSet timeSet = new TreeSet(); timeSet.addAll(allMonitoredTimeStamps); double oldOcc = -5.0; - + int zoneSize = currentSet.size(); int timeSize = timeSet.size(); - + for(int i = 0; i < zoneSize; i++){ ParkingTuple ff = currentSet.pollFirst(); for(int zz = 0; zz < timeSize; zz ++ ){ @@ -135,7 +135,7 @@ else if( time == ff.getTime()){ // TODO Auto-generated catch block e.printStackTrace(); } - + log.error("FINISHED WRITING OCCUPANCY STATS"); } @@ -145,34 +145,34 @@ private void writeStatsVertical(String fileName) { String head = ";;"; String capacityLine = "TotalCapacity;;"; String subheader = "SlotNr;SimTime;"; - + ArrayList zoneColumns = new ArrayList(); int numberOfSlots = this.allMonitoredTimeStamps.size(); double[] slotTimes = new double[numberOfSlots]; int[] slotNumbers = new int[numberOfSlots]; TreeSet timeSet = new TreeSet(); timeSet.addAll(allMonitoredTimeStamps); - + for (int timeSlot = 0; timeSlot < numberOfSlots; timeSlot ++ ){ double tt = timeSet.pollFirst(); slotTimes[timeSlot] = tt; - slotNumbers[timeSlot] = (int) (tt/900); + slotNumbers[timeSlot] = (int) (tt/900); } - + for(String zone : this.zoneManager.getZones()){ head += zone +";"; capacityLine += this.zoneManager.getTotalCapacityOfZone(zone) + ";"; subheader += "OccRatio;"; - - + + double[] ratios = new double[numberOfSlots]; - - TreeSet ratioSet = this.zoneOccupationPerTime.get(zone); - + + TreeSet ratioSet = this.zoneOccupationPerTime.get(zone); + double oldRatio = 0.0; for(int i = 0; i < numberOfSlots; i++){ - - ParkingTuple tuple = ratioSet.pollFirst(); + + ParkingTuple tuple = ratioSet.pollFirst(); if(slotTimes[i] == tuple.getTime()){ ratios[i] = tuple.getOccupancy(); oldRatio = tuple.getOccupancy(); @@ -184,10 +184,10 @@ else if(slotTimes[i] < tuple.getTime()){ throw new RuntimeException("timeSlot number is higher than recorded time. timeSlot: " + slotTimes[i] + "\t time: " + tuple.getTime()); } } - - zoneColumns.add(ratios); + + zoneColumns.add(ratios); } - + BufferedWriter bw = IOUtils.getBufferedWriter(fileName); try { bw.write(head); @@ -195,27 +195,27 @@ else if(slotTimes[i] < tuple.getTime()){ bw.write(capacityLine); bw.newLine(); bw.write(subheader); - + DecimalFormat df = new DecimalFormat("##.##"); - + for(int z = 0; z < numberOfSlots; z++){ bw.newLine(); - + String line = "" + slotNumbers[z] + ";" + df.format(slotTimes[z]) + ";"; for(int p = 0; p < this.zoneManager.getZones().size(); p++){ line += "" + df.format(zoneColumns.get(p)[z]) + ";"; } - + bw.write(line); } - + bw.flush(); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - + log.error("FINISHED WRITING OCCUPANCY STATS"); } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/WalkLegFactory.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/WalkLegFactory.java index 0fef2946523..4498dc80fa5 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/WalkLegFactory.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/WalkLegFactory.java @@ -43,8 +43,8 @@ public class WalkLegFactory { @Inject public WalkLegFactory(Network network, Config config) { this.network = network; - this.beelinedistancefactor = config.plansCalcRoute().getBeelineDistanceFactors().get("walk"); - this.walkspeed = config.plansCalcRoute().getTeleportedModeSpeeds().get("walk"); + this.beelinedistancefactor = config.routing().getBeelineDistanceFactors().get("walk"); + this.walkspeed = config.routing().getTeleportedModeSpeeds().get("walk"); } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/vehicleteleportationlogic/VehicleTeleportationToNearbyParking.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/vehicleteleportationlogic/VehicleTeleportationToNearbyParking.java index 7b6eab754c9..c0a22d93ade 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/vehicleteleportationlogic/VehicleTeleportationToNearbyParking.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/vehicleteleportationlogic/VehicleTeleportationToNearbyParking.java @@ -34,23 +34,23 @@ /** * teleports vehicle to a location near the agent, if vehicle is more than a certain threshold in metres away * @author jbischoff - * + * */ public class VehicleTeleportationToNearbyParking implements VehicleTeleportationLogic { - + private double maximumWalkDistance = 2000; //TODO: Make this configurable - + private double beelineDistanceFactor; @Inject ParkingSearchManager manager; - - ParkingSearchLogic parkingLogic; + + ParkingSearchLogic parkingLogic; Network network; - + @Inject public VehicleTeleportationToNearbyParking(Config config, Network network) { - this.beelineDistanceFactor = config.plansCalcRoute().getModeRoutingParams().get(TransportMode.walk).getBeelineDistanceFactor(); + this.beelineDistanceFactor = config.routing().getModeRoutingParams().get(TransportMode.walk).getBeelineDistanceFactor(); this.parkingLogic = new RandomParkingSearchLogic(network); this.network = network; } @@ -60,7 +60,7 @@ public Id getVehicleLocation(Id agentLinkId, Id vehicleId, double walkDistance = CoordUtils.calcEuclideanDistance(network.getLinks().get(vehicleLinkId).getCoord(), network.getLinks().get(agentLinkId).getCoord()) * this.beelineDistanceFactor; if (walkDistance<=this.maximumWalkDistance){ return vehicleLinkId; - } + } Id parkingLinkId = agentLinkId; while (!this.manager.reserveSpaceIfVehicleCanParkHere(vehicleId, parkingLinkId)){ parkingLinkId = parkingLogic.getNextLink(parkingLinkId, vehicleId, mode); @@ -68,5 +68,5 @@ public Id getVehicleLocation(Id agentLinkId, Id vehicleId, manager.parkVehicleHere(vehicleId, parkingLinkId, time); return parkingLinkId; } - + } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/sim/ParkingManagerModule.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/sim/ParkingManagerModule.java index 475d6d85442..dff408ec017 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/sim/ParkingManagerModule.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/sim/ParkingManagerModule.java @@ -27,14 +27,7 @@ import org.matsim.contrib.parking.parkingsearch.manager.ParkingSearchManager; import org.matsim.contrib.parking.parkingsearch.manager.ZoneParkingManager; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup; import org.matsim.core.controler.AbstractModule; -import org.matsim.core.router.AStarLandmarksFactory; -import org.matsim.core.router.DijkstraFactory; -import org.matsim.core.router.FastAStarLandmarksFactory; -import org.matsim.core.router.FastDijkstraFactory; -import org.matsim.core.router.speedy.SpeedyALTFactory; -import org.matsim.core.router.util.LeastCostPathCalculatorFactory; public class ParkingManagerModule extends AbstractModule { diff --git a/contribs/parking/src/test/java/org/matsim/contrib/parking/run/RunParkingChoiceExampleIT.java b/contribs/parking/src/test/java/org/matsim/contrib/parking/run/RunParkingChoiceExampleIT.java index 6ea09f92030..57792fb205d 100644 --- a/contribs/parking/src/test/java/org/matsim/contrib/parking/run/RunParkingChoiceExampleIT.java +++ b/contribs/parking/src/test/java/org/matsim/contrib/parking/run/RunParkingChoiceExampleIT.java @@ -31,17 +31,17 @@ */ public class RunParkingChoiceExampleIT { @Rule public MatsimTestUtils utils = new MatsimTestUtils() ; - + /** * Test method for {@link org.matsim.contrib.parking.parkingchoice.run.RunParkingChoiceExample#run(org.matsim.core.config.Config)}. */ @Test public final void testRun() { Config config = ConfigUtils.loadConfig("./src/main/resources/parkingchoice/config.xml"); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setLastIteration(0); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setLastIteration(0); RunParkingChoiceExample.run(config); - + } } diff --git a/contribs/parking/src/test/java/org/matsim/contrib/parking/run/RunParkingSearchScenarioIT.java b/contribs/parking/src/test/java/org/matsim/contrib/parking/run/RunParkingSearchScenarioIT.java index f4f357e61bc..eef6af3f609 100644 --- a/contribs/parking/src/test/java/org/matsim/contrib/parking/run/RunParkingSearchScenarioIT.java +++ b/contribs/parking/src/test/java/org/matsim/contrib/parking/run/RunParkingSearchScenarioIT.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.parking.run; @@ -42,13 +42,13 @@ public class RunParkingSearchScenarioIT { public void testRunParking() { String configFile = "./src/main/resources/parkingsearch/config.xml"; Config config = ConfigUtils.loadConfig(configFile, new ParkingSearchConfigGroup()); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); ParkingSearchConfigGroup configGroup = (ParkingSearchConfigGroup) config.getModules().get(ParkingSearchConfigGroup.GROUP_NAME); configGroup.setParkingSearchStrategy(ParkingSearchStrategy.Benenson); - + new RunParkingSearchExample().run(config,false); - + } } diff --git a/contribs/pom.xml b/contribs/pom.xml index 987847d56ac..9ffc2dec10e 100644 --- a/contribs/pom.xml +++ b/contribs/pom.xml @@ -74,7 +74,6 @@ dvrp ev emissions - eventsBasedPTRouter freight freightreceiver hybridsim @@ -90,6 +89,7 @@ parking protobuf pseudosimulation + railsim roadpricing sbb-extensions shared_mobility diff --git a/contribs/protobuf/pom.xml b/contribs/protobuf/pom.xml index b75f9d59200..56b7e7b9e14 100644 --- a/contribs/protobuf/pom.xml +++ b/contribs/protobuf/pom.xml @@ -11,7 +11,7 @@ protobuf - 3.24.2 + 3.24.4 @@ -30,16 +30,20 @@ - - - + + kr.motd.maven os-maven-plugin 1.7.1 - - - - + + + initialize + + detect + + + + org.xolstice.maven.plugins protobuf-maven-plugin diff --git a/contribs/pseudosimulation/pom.xml b/contribs/pseudosimulation/pom.xml index 3c8e45cc647..56b3b3b9bfc 100644 --- a/contribs/pseudosimulation/pom.xml +++ b/contribs/pseudosimulation/pom.xml @@ -15,11 +15,6 @@ common 16.0-SNAPSHOT - - org.matsim.contrib - events-based-pt-router - 16.0-SNAPSHOT - commons-cli commons-cli diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/ChoiceGenerationControler.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/ChoiceGenerationControler.java index 00fc950cbcc..022d0cc21e7 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/ChoiceGenerationControler.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/ChoiceGenerationControler.java @@ -6,9 +6,9 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.contrib.eventsBasedPTRouter.TransitRouterEventsWSFactory; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculatorImpl; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeStuckCalculator; +//import org.matsim.contrib.eventsBasedPTRouter.TransitRouterEventsWSFactory; +//import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculatorImpl; +//import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeStuckCalculator; import org.matsim.contrib.pseudosimulation.mobsim.PSimProvider; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; @@ -34,8 +34,8 @@ */ public class ChoiceGenerationControler implements BeforeMobsimListener{ - final WaitTimeStuckCalculator waitTimeCalculator; - final StopStopTimeCalculatorImpl stopStopTimeCalculator; +// final WaitTimeStuckCalculator waitTimeCalculator; +// final StopStopTimeCalculatorImpl stopStopTimeCalculator; final TravelTimeCalculator travelTimeCalculator; private PSimProvider pSimProvider; Config config; @@ -43,29 +43,29 @@ public class ChoiceGenerationControler implements BeforeMobsimListener{ Scenario scenario; public ChoiceGenerationControler(String[] args) { config = ConfigUtils.loadConfig(args[0]); - config.parallelEventHandling().setSynchronizeOnSimSteps(false); - config.parallelEventHandling().setNumberOfThreads(1); - config.planCalcScore().setWriteExperiencedPlans(true); + config.eventsManager().setSynchronizeOnSimSteps(false); + config.eventsManager().setNumberOfThreads(1); + config.scoring().setWriteExperiencedPlans(true); scenario = ScenarioUtils.loadScenario(config); controler = new Controler(scenario); - waitTimeCalculator = new WaitTimeStuckCalculator( - controler.getScenario().getPopulation(), - controler.getScenario().getTransitSchedule(), - controler.getConfig().travelTimeCalculator().getTraveltimeBinSize(), - (int) (controler.getConfig().qsim().getEndTime().seconds() - controler.getConfig().qsim().getStartTime().seconds())); - stopStopTimeCalculator = new StopStopTimeCalculatorImpl( - controler.getScenario().getTransitSchedule(), - controler.getConfig().travelTimeCalculator().getTraveltimeBinSize(), - (int) (controler.getConfig().qsim().getEndTime().seconds() - controler.getConfig().qsim().getStartTime().seconds())); - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - bind(TransitRouter.class).toProvider(new TransitRouterEventsWSFactory(controler.getScenario(), - waitTimeCalculator.get(), - stopStopTimeCalculator.get())); - } - }); +// waitTimeCalculator = new WaitTimeStuckCalculator( +// controler.getScenario().getPopulation(), +// controler.getScenario().getTransitSchedule(), +// controler.getConfig().travelTimeCalculator().getTraveltimeBinSize(), +// (int) (controler.getConfig().qsim().getEndTime().seconds() - controler.getConfig().qsim().getStartTime().seconds())); +// stopStopTimeCalculator = new StopStopTimeCalculatorImpl( +// controler.getScenario().getTransitSchedule(), +// controler.getConfig().travelTimeCalculator().getTraveltimeBinSize(), +// (int) (controler.getConfig().qsim().getEndTime().seconds() - controler.getConfig().qsim().getStartTime().seconds())); +// controler.addOverridingModule(new AbstractModule() { +// @Override +// public void install() { +// bind(TransitRouter.class).toProvider(new TransitRouterEventsWSFactory(controler.getScenario(), +// waitTimeCalculator.get(), +// stopStopTimeCalculator.get())); +// } +// }); // controler.setScoringFunctionFactory( // new CharyparNagelOpenTimesScoringFunctionFactory(controler.getConfig().planCalcScore(), // controler.getScenario())); @@ -73,8 +73,8 @@ public void install() { EventsManagerImpl eventsManager = new EventsManagerImpl(); EventsReaderXMLv1 reader = new EventsReaderXMLv1(eventsManager); - eventsManager.addHandler(waitTimeCalculator); - eventsManager.addHandler(stopStopTimeCalculator); +// eventsManager.addHandler(waitTimeCalculator); +// eventsManager.addHandler(stopStopTimeCalculator); eventsManager.addHandler(travelTimeCalculator); reader.readFile(args[1]); @@ -106,8 +106,8 @@ public void notifyBeforeMobsim(BeforeMobsimEvent event) { for(Person person:controler.getScenario().getPopulation().getPersons().values()){ plans.add(person.getSelectedPlan()); } - pSimProvider.setWaitTime(waitTimeCalculator.get()); +// pSimProvider.setWaitTime(waitTimeCalculator.get()); pSimProvider.setTravelTime(travelTimeCalculator.getLinkTravelTimes()); - pSimProvider.setStopStopTime(stopStopTimeCalculator.get()); +// pSimProvider.setStopStopTime(stopStopTimeCalculator.get()); } } diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/MobSimSwitcher.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/MobSimSwitcher.java index f5a902e178e..71cdaf37a41 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/MobSimSwitcher.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/MobSimSwitcher.java @@ -3,12 +3,10 @@ import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.contrib.pseudosimulation.mobsim.PSimProvider; import org.matsim.contrib.pseudosimulation.replanning.PlanCatcher; import org.matsim.core.controler.events.BeforeMobsimEvent; import org.matsim.core.controler.events.IterationEndsEvent; @@ -70,7 +68,7 @@ public void notifyIterationStarts(IterationStartsEvent event) { private boolean determineIfQSimIter(int iteration) { - if (iteration == scenario.getConfig().controler().getLastIteration() || iteration == scenario.getConfig().controler().getFirstIteration() ) { + if (iteration == scenario.getConfig().controller().getLastIteration() || iteration == scenario.getConfig().controller().getFirstIteration() ) { isQSimIteration = true; return isQSimIteration; } diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/PSimDataProvider.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/PSimDataProvider.java index 7c6368c7528..461999c0120 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/PSimDataProvider.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/PSimDataProvider.java @@ -1,7 +1,7 @@ package org.matsim.contrib.pseudosimulation; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; +//import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; +//import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; import org.matsim.contrib.pseudosimulation.distributed.listeners.events.transit.TransitPerformance; import org.matsim.contrib.pseudosimulation.replanning.PlanCatcher; import org.matsim.core.router.util.TravelTime; @@ -10,8 +10,8 @@ * Created by fouriep on 4/21/15. */ public interface PSimDataProvider { - public StopStopTime getStopStopTime(); - public WaitTime getWaitTime(); +// public StopStopTime getStopStopTime(); +// public WaitTime getWaitTime(); public TransitPerformance getTransitPerformance(); public PlanCatcher getPlanCatcher(); public TravelTime getTravelTime(); diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/RunPSim.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/RunPSim.java index 3df6ab05ecf..d499aee4a6b 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/RunPSim.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/RunPSim.java @@ -23,18 +23,16 @@ import com.google.inject.Singleton; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.eventsBasedPTRouter.TransitRouterEventsWSFactory; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculator; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeCalculator; +//import org.matsim.contrib.eventsBasedPTRouter.TransitRouterEventsWSFactory; +//import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; +//import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculator; +//import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; +//import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeCalculator; //import org.matsim.contrib.pseudosimulation.distributed.listeners.events.transit.TransitPerformanceRecorder; import org.matsim.contrib.pseudosimulation.mobsim.PSimProvider; import org.matsim.contrib.pseudosimulation.mobsim.SwitchingMobsimProvider; import org.matsim.contrib.pseudosimulation.replanning.PlanCatcher; -import org.matsim.contrib.pseudosimulation.trafficinfo.PSimStopStopTimeCalculator; import org.matsim.contrib.pseudosimulation.trafficinfo.PSimTravelTimeCalculator; -import org.matsim.contrib.pseudosimulation.trafficinfo.PSimWaitTimeCalculator; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.AbstractModule; @@ -43,7 +41,6 @@ import org.matsim.core.mobsim.qsim.QSimProvider; import org.matsim.core.router.util.TravelTime; import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.pt.router.TransitRouter; /** * @author pieterfourie @@ -61,8 +58,8 @@ public RunPSim(Config config, PSimConfigGroup pSimConfigGroup) { //The following line will make the controler use the events manager that doesn't check for event order. //This is essential for pseudo-simulation as the PSim module generates events on a person-basis, //not a system basis - config.parallelEventHandling().setSynchronizeOnSimSteps(false); - config.parallelEventHandling().setNumberOfThreads(1); + config.eventsManager().setSynchronizeOnSimSteps(false); + config.eventsManager().setNumberOfThreads(1); this.matsimControler = new Controler(scenario); @@ -74,10 +71,10 @@ public RunPSim(Config config, PSimConfigGroup pSimConfigGroup) { public void install() { bind(MobSimSwitcher.class).toInstance(mobSimSwitcher); bindMobsim().toProvider(SwitchingMobsimProvider.class); - bind(WaitTimeCalculator.class).to(PSimWaitTimeCalculator.class); - bind(WaitTime.class).toProvider(PSimWaitTimeCalculator.class); - bind(StopStopTimeCalculator.class).to(PSimStopStopTimeCalculator.class); - bind(StopStopTime.class).toProvider(PSimStopStopTimeCalculator.class); +// bind(WaitTimeCalculator.class).to(PSimWaitTimeCalculator.class); +// bind(WaitTime.class).toProvider(PSimWaitTimeCalculator.class); +// bind(StopStopTimeCalculator.class).to(PSimStopStopTimeCalculator.class); +// bind(StopStopTime.class).toProvider(PSimStopStopTimeCalculator.class); // bind(TravelTimeCalculator.class).to(PSimTravelTimeCalculator.class); // I made TravelTimeCalculator final, so PSimTravelTimeCalculator can no longer inherit from it. The following statement binds PSimTravelTimeCalculator @@ -85,7 +82,7 @@ public void install() { bind(PSimTravelTimeCalculator.class).in( Singleton.class ) ; bind(TravelTime.class).toProvider(PSimTravelTimeCalculator.class); - bind(TransitRouter.class).toProvider(TransitRouterEventsWSFactory.class); +// bind(TransitRouter.class).toProvider(TransitRouterEventsWSFactory.class); bind(PlanCatcher.class).toInstance(new PlanCatcher()); bind(PSimProvider.class).toInstance(new PSimProvider(scenario,matsimControler.getEvents())); bind(QSimProvider.class); @@ -104,7 +101,7 @@ public void install() { public static void main(String args[]) { Config config = ConfigUtils.loadConfig(args[0]); - config.controler().setCreateGraphs(false); + config.controller().setCreateGraphs(false); PSimConfigGroup pSimConfigGroup = new PSimConfigGroup(); config.addModule(pSimConfigGroup); diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/MasterControler.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/MasterControler.java index 9e1e85a8450..183e98bc63b 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/MasterControler.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/MasterControler.java @@ -23,8 +23,6 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculatorSerializable; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeCalculatorSerializable; import org.matsim.contrib.pseudosimulation.distributed.instrumentation.scorestats.SlaveScoreStats; import org.matsim.contrib.pseudosimulation.distributed.listeners.controler.GenomeAnalysis; import org.matsim.contrib.pseudosimulation.distributed.listeners.controler.SlaveScoreWriter; @@ -33,7 +31,7 @@ import org.matsim.contrib.pseudosimulation.util.CollectionUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -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.MatsimServices; @@ -73,8 +71,8 @@ public class MasterControler implements AfterMobsimListener, ShutdownListener, S private Config config; private Controler matsimControler; private TreeMap slaveHandlerTreeMap; - private WaitTimeCalculatorSerializable waitTimeCalculator; - private StopStopTimeCalculatorSerializable stopStopTimeCalculator; +// private WaitTimeCalculatorSerializable waitTimeCalculator; +// private StopStopTimeCalculatorSerializable stopStopTimeCalculator; private TransitPerformanceRecorder transitPerformanceRecorder; private SerializableLinkTravelTimes linkTravelTimes; private AtomicInteger numThreads = new AtomicInteger(0); @@ -180,13 +178,13 @@ public MasterControler(String configFile) throws NumberFormatException, IOExcept if (this.config.transit().isUseTransit()) { - waitTimeCalculator = new WaitTimeCalculatorSerializable(matsimControler.getScenario().getTransitSchedule(), this.config.travelTimeCalculator().getTraveltimeBinSize(), - (int) (this.config.qsim().getEndTime().seconds() - this.config.qsim().getStartTime().seconds())); - matsimControler.getEvents().addHandler(waitTimeCalculator); - stopStopTimeCalculator = new StopStopTimeCalculatorSerializable(matsimControler.getScenario().getTransitSchedule(), - this.config.travelTimeCalculator().getTraveltimeBinSize(), (int) (this.config.qsim() - .getEndTime().seconds() - this.config.qsim().getStartTime().seconds())); - matsimControler.getEvents().addHandler(stopStopTimeCalculator); +// waitTimeCalculator = new WaitTimeCalculatorSerializable(matsimControler.getScenario().getTransitSchedule(), this.config.travelTimeCalculator().getTraveltimeBinSize(), +// (int) (this.config.qsim().getEndTime().seconds() - this.config.qsim().getStartTime().seconds())); +// matsimControler.getEvents().addHandler(waitTimeCalculator); +// stopStopTimeCalculator = new StopStopTimeCalculatorSerializable(matsimControler.getScenario().getTransitSchedule(), +// this.config.travelTimeCalculator().getTraveltimeBinSize(), (int) (this.config.qsim() +// .getEndTime().seconds() - this.config.qsim().getStartTime().seconds())); +// matsimControler.getEvents().addHandler(stopStopTimeCalculator); //tell PlanSerializable to record transit routes PlanSerializable.isUseTransit = true; if (fullTransitPerformanceTransmission) { @@ -204,7 +202,7 @@ public void install() { - matsimControler.getConfig().controler().setOverwriteFileSetting( + matsimControler.getConfig().controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); // true ? // OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles : @@ -223,18 +221,18 @@ public void install() { * @param borrowingRate */ private void setReplanningWeights(Config config, double masterMutationRate, double borrowingRate) { - int disableAfterIteration = config.controler().getLastIteration(); + int disableAfterIteration = config.controller().getLastIteration(); int maximumIterationForMutationDisabling = -1; if (borrowingRate + masterMutationRate >= 1) { borrowingRate = 0.9999 * borrowingRate / (masterMutationRate + borrowingRate); masterMutationRate = 0.9999 * masterMutationRate / (masterMutationRate + borrowingRate); } - List strategySettings = new ArrayList<>(); - strategySettings.addAll(config.strategy().getStrategySettings()); + List strategySettings = new ArrayList<>(); + strategySettings.addAll(config.replanning().getStrategySettings()); Map selectors = new HashMap<>(); Map mutators = new HashMap<>(); for (int i = 0; i < strategySettings.size(); i++) { - StrategyConfigGroup.StrategySettings setting = strategySettings.get(i); + ReplanningConfigGroup.StrategySettings setting = strategySettings.get(i); if (DistributedPlanStrategyTranslationAndRegistration.SupportedSelectors.keySet().contains(setting.getStrategyName())) selectors.put(i, setting.getWeight()); else { @@ -253,16 +251,16 @@ private void setReplanningWeights(Config config, double masterMutationRate, doub strategySettings.get(entry.getKey()).setWeight(masterMutationRate * entry.getValue() / mutatorSum); } //put it back in the config - config.strategy().clearStrategySettings(); - for (StrategyConfigGroup.StrategySettings strategySetting : strategySettings) { - config.strategy().addStrategySettings(strategySetting); + config.replanning().clearStrategySettings(); + for (ReplanningConfigGroup.StrategySettings strategySetting : strategySettings) { + config.replanning().addStrategySettings(strategySetting); } // add the borrowing rate entry - StrategyConfigGroup.StrategySettings borrowingSetting = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings borrowingSetting = new ReplanningConfigGroup.StrategySettings(); borrowingSetting.setWeight(borrowingRate); borrowingSetting.setStrategyName("ReplacePlanFromSlave"); borrowingSetting.setDisableAfter(maximumIterationForMutationDisabling > 0 ? maximumIterationForMutationDisabling : disableAfterIteration); - config.strategy().addStrategySettings(borrowingSetting); + config.replanning().addStrategySettings(borrowingSetting); this.innovationEndsAtIter = maximumIterationForMutationDisabling > 0 ? maximumIterationForMutationDisabling : disableAfterIteration; } @@ -394,7 +392,7 @@ public void notifyAfterMobsim(AfterMobsimEvent event) { startSlaveHandlersInMode(CommunicationsMode.TRANSMIT_SCORES); waitForSlaveThreads(); } - boolean isLoadBalanceIteration = event.getIteration() > config.controler().getFirstIteration() && + boolean isLoadBalanceIteration = event.getIteration() > config.controller().getFirstIteration() && (event.getIteration() % loadBalanceInterval == 0 || slavesHaveRequestedShutdown() || hydra.hydraSlaves.size() > 0); @@ -778,8 +776,8 @@ public void transmitTravelTimes() throws IOException { writer.writeInt(currentIteration); writer.writeObject(linkTravelTimes); if (config.transit().isUseTransit()) { - writer.writeObject(stopStopTimeCalculator.getStopStopTimes()); - writer.writeObject(waitTimeCalculator.getWaitTimes()); +// writer.writeObject(stopStopTimeCalculator.getStopStopTimes()); +// writer.writeObject(waitTimeCalculator.getWaitTimes()); if (fullTransitPerformanceTransmission) writer.writeObject(transitPerformanceRecorder.getTransitPerformance()); } @@ -969,7 +967,7 @@ private void initializeSlave(SlaveHandler slaveHandler, int i, boolean initialRo slaveHandler.sendNumber(slaveIterationsPerMasterIteration); slaveHandler.sendNumber(slaveNumberOfPlans); slaveHandler.sendDouble(slaveMutationRate); - slaveHandler.sendNumber(config.controler().getLastIteration() * slaveIterationsPerMasterIteration); + slaveHandler.sendNumber(config.controller().getLastIteration() * slaveIterationsPerMasterIteration); slaveHandler.sendBoolean(initialRoutingOnSlaves); slaveHandler.sendBoolean(QuickReplanning); slaveHandler.sendBoolean(fullTransitPerformanceTransmission); diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/SlaveControler.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/SlaveControler.java index a45f80ba4d6..3d3508640a0 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/SlaveControler.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/SlaveControler.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.UncheckedIOException; import java.net.ConnectException; import java.net.Socket; import java.util.ArrayList; @@ -28,11 +29,6 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.contrib.common.diversitygeneration.planselectors.DiversityGeneratingPlansRemover; -import org.matsim.contrib.eventsBasedPTRouter.TransitRouterEventsWSFactory; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculatorSerializable; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeCalculatorSerializable; import org.matsim.contrib.pseudosimulation.distributed.instrumentation.scorestats.SlaveScoreStatsCalculator; import org.matsim.contrib.pseudosimulation.distributed.listeners.events.transit.TransitPerformance; import org.matsim.contrib.pseudosimulation.mobsim.PSimProvider; @@ -41,7 +37,7 @@ import org.matsim.contrib.pseudosimulation.util.CollectionUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -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; @@ -59,8 +55,6 @@ import org.matsim.core.router.util.TravelTime; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; -import org.matsim.core.utils.io.UncheckedIOException; -import org.matsim.pt.router.TransitRouter; import com.google.inject.Inject; @@ -86,8 +80,6 @@ public class SlaveControler implements IterationStartsListener, StartupListener, private double totalIterationTime; private Controler matsimControler; private TravelTime linkTravelTimes; - private WaitTime waitTimes; - private StopStopTime stopStopTimes; private ObjectInputStream reader; private ObjectOutputStream writer; private PSimProvider pSimProvider; @@ -97,7 +89,6 @@ public class SlaveControler implements IterationStartsListener, StartupListener, private boolean isOkForNextIter = true; private Map, Double> selectedPlanScoreMemory; private TransitPerformance transitPerformance; - private TransitRouterEventsWSFactory transitRouterEventsWSFactory; private void printHelp(Options options) { String header = "The MasterControler takes the following options:\n\n"; @@ -151,7 +142,7 @@ public SlaveControler(String[] args) throws IOException, ClassNotFoundException, final DistributedSimConfigGroup distributedSimConfigGroup = ConfigUtils.addOrGetModule(this.config,DistributedSimConfigGroup.GROUP_NAME,DistributedSimConfigGroup.class); //The following line will make the controler use the events manager that doesn't check for event order - config.parallelEventHandling().setSynchronizeOnSimSteps(false); + config.eventsManager().setSynchronizeOnSimSteps(false); //if you don't set the number of threads, org.matsim.core.events.EventsUtils will just use the simstepmanager int numThreads = config.global().getNumberOfThreads(); if (commandLine.hasOption("t")) @@ -166,7 +157,7 @@ public SlaveControler(String[] args) throws IOException, ClassNotFoundException, System.err.println("Will use the number of threads in config for simulation."); } config.global().setNumberOfThreads(numThreads); - config.parallelEventHandling().setNumberOfThreads(1); + config.eventsManager().setNumberOfThreads(1); String hostname = "localhost"; if (commandLine.hasOption("h")) { @@ -208,7 +199,7 @@ public SlaveControler(String[] args) throws IOException, ClassNotFoundException, numberOfPlansOnSlave = reader.readInt(); slaveMutationRate = reader.readDouble(); slaveLogger.warn("Running " + numberOfPSimIterationsPerCycle + " PSim iterations for every QSim iter"); - config.controler().setLastIteration(reader.readInt()); + config.controller().setLastIteration(reader.readInt()); initialRouting = reader.readBoolean(); boolean quickReplannning = reader.readBoolean(); fullTransitPerformanceTransmission = reader.readBoolean(); @@ -224,18 +215,18 @@ public SlaveControler(String[] args) throws IOException, ClassNotFoundException, writer.flush(); - config.controler().setOutputDirectory(config.controler().getOutputDirectory() + "_" + myNumber); + config.controller().setOutputDirectory(config.controller().getOutputDirectory() + "_" + myNumber); //limit IO config.linkStats().setWriteLinkStatsInterval(0); - config.controler().setCreateGraphs(false); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); - config.controler().setWriteSnapshotsInterval(0); + config.controller().setCreateGraphs(false); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); + config.controller().setWriteSnapshotsInterval(0); // don't load plans; receive them from master config.plans().setInputFile(null); // Important, otherwise Psim breaks - config.parallelEventHandling().setSynchronizeOnSimSteps(false); - config.parallelEventHandling().setNumberOfThreads(1); + config.eventsManager().setSynchronizeOnSimSteps(false); + config.eventsManager().setNumberOfThreads(1); if (slaveMutationRate > 0) setReplanningWeights(config, slaveMutationRate); @@ -249,7 +240,7 @@ public SlaveControler(String[] args) throws IOException, ClassNotFoundException, DistributedPlanStrategyTranslationAndRegistration.substituteStrategies(config, quickReplannning, numberOfPSimIterationsPerCycle); matsimControler = new Controler(scenario); DistributedPlanStrategyTranslationAndRegistration.registerStrategiesWithControler(this.matsimControler, plancatcher, quickReplannning, numberOfPSimIterationsPerCycle); - matsimControler.getConfig().controler().setOverwriteFileSetting( + matsimControler.getConfig().controller().setOverwriteFileSetting( true ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists); @@ -268,15 +259,6 @@ public void install() { }); if (config.transit().isUseTransit()) { - - stopStopTimes = new StopStopTimeCalculatorSerializable(scenario.getTransitSchedule(), - config.travelTimeCalculator().getTraveltimeBinSize(), (int) (config - .qsim().getEndTime().seconds() - config.qsim().getStartTime().seconds())).getStopStopTimes(); - - waitTimes = new WaitTimeCalculatorSerializable(scenario.getTransitSchedule(), - config.travelTimeCalculator().getTraveltimeBinSize(), (int) (config - .qsim().getEndTime().seconds() - config.qsim().getStartTime().seconds())).getWaitTimes(); - // tell PlanSerializable to record transit routes PlanSerializable.isUseTransit = true; @@ -285,11 +267,11 @@ public void install() { matsimControler.addOverridingModule(new AbstractModule() { @Override public void install() { - System.out.println("init routers"); +// System.out.println("init routers"); // transitRouterEventsWSFactory = new TransitRouterEventsWSFactory(scenario, // waitTimes, // stopStopTimes); - bind(TransitRouter.class).toProvider(transitRouterEventsWSFactory); +// bind(TransitRouter.class).toProvider(transitRouterEventsWSFactory); } }); @@ -308,7 +290,7 @@ public void install() { @Override public void install() { bind(TravelTime.class).toInstance(travelTime); - if (scenario.getConfig().strategy().getPlanSelectorForRemoval().equals("DiversityGeneratingPlansRemover")) { + if (scenario.getConfig().replanning().getPlanSelectorForRemoval().equals("DiversityGeneratingPlansRemover")) { bindPlanSelectorForRemoval().toProvider(DiversityGeneratingPlansRemover.Builder.class); } } @@ -319,11 +301,11 @@ public void install() { } if (diversityGeneratingPlanSelection) - matsimControler.getConfig().strategy().setPlanSelectorForRemoval("DiversityGeneratingPlansRemover"); + matsimControler.getConfig().replanning().setPlanSelectorForRemoval("DiversityGeneratingPlansRemover"); //no use for this, if you don't exactly know the communicationsMode of population when something goes wrong. // better to have plans written out every n successful iterations, specified in the config - matsimControler.getConfig().controler().setDumpDataAtEnd(false); - matsimControler.getConfig().strategy().setMaxAgentPlanMemorySize(numberOfPlansOnSlave); + matsimControler.getConfig().controller().setDumpDataAtEnd(false); + matsimControler.getConfig().replanning().setMaxAgentPlanMemorySize(numberOfPlansOnSlave); } public static void main(String[] args) throws IOException, ClassNotFoundException, ParseException, InterruptedException { @@ -387,13 +369,13 @@ public void notifyIterationStarts(IterationStartsEvent event) { travelTime.setTravelTime(linkTravelTimes); pSimProvider.setTravelTime(linkTravelTimes); if (config.transit().isUseTransit()) { - pSimProvider.setStopStopTime(stopStopTimes); - pSimProvider.setWaitTime(waitTimes); - pSimProvider.setTransitPerformance(transitPerformance); - if (transitRouterEventsWSFactory != null) { +// pSimProvider.setStopStopTime(stopStopTimes); +// pSimProvider.setWaitTime(waitTimes); +// pSimProvider.setTransitPerformance(transitPerformance); +// if (transitRouterEventsWSFactory != null) { // transitRouterEventsWSFactory.setStopStopTimeCalculator(stopStopTimes); // transitRouterEventsWSFactory.setWaitTimeCalculator(waitTimes); - } +// } } plancatcher.init(); numberOfIterations++; @@ -449,8 +431,8 @@ public void transmitTravelTimes() throws IOException, ClassNotFoundException { masterCurrentIteration = reader.readInt(); linkTravelTimes = (SerializableLinkTravelTimes) reader.readObject(); if (config.transit().isUseTransit()) { - stopStopTimes = (StopStopTime) reader.readObject(); - waitTimes = (WaitTime) reader.readObject(); +// stopStopTimes = (StopStopTime) reader.readObject(); +// waitTimes = (WaitTime) reader.readObject(); if (fullTransitPerformanceTransmission) { Object o = reader.readObject(); transitPerformance = (TransitPerformance) o; @@ -619,8 +601,8 @@ public void notifyBeforeMobsim(BeforeMobsimEvent event) { @Override public void notifyIterationEnds(IterationEndsEvent event) { Iterator, Double>> iterator = selectedPlanScoreMemory.entrySet().iterator(); - StopStopTimeCalculatorSerializable.printCallStatisticsAndReset(); - WaitTimeCalculatorSerializable.printCallStatisticsAndReset(); +// StopStopTimeCalculatorSerializable.printCallStatisticsAndReset(); +// WaitTimeCalculatorSerializable.printCallStatisticsAndReset(); while (iterator.hasNext()) { Map.Entry, Double> entry = iterator.next(); scenario.getPopulation().getPersons().get(entry.getKey()).getSelectedPlan().setScore(entry.getValue()); @@ -630,12 +612,12 @@ public void notifyIterationEnds(IterationEndsEvent event) { private void setReplanningWeights(Config config, double mutationRate) { if (mutationRate > 1) mutationRate = 0.9999; - List strategySettings = new ArrayList<>(); - strategySettings.addAll(config.strategy().getStrategySettings()); + List strategySettings = new ArrayList<>(); + strategySettings.addAll(config.replanning().getStrategySettings()); Map selectors = new HashMap<>(); Map mutators = new HashMap<>(); for (int i = 0; i < strategySettings.size(); i++) { - StrategyConfigGroup.StrategySettings setting = strategySettings.get(i); + ReplanningConfigGroup.StrategySettings setting = strategySettings.get(i); if (DistributedPlanStrategyTranslationAndRegistration.SupportedSelectors.keySet().contains(setting.getStrategyName())) selectors.put(i, setting.getWeight()); else { @@ -653,9 +635,9 @@ private void setReplanningWeights(Config config, double mutationRate) { strategySettings.get(entry.getKey()).setWeight(mutationRate * entry.getValue() / mutatorSum); } //put it back in the config - config.strategy().clearStrategySettings(); - for (StrategyConfigGroup.StrategySettings strategySetting : strategySettings) { - config.strategy().addStrategySettings(strategySetting); + config.replanning().clearStrategySettings(); + for (ReplanningConfigGroup.StrategySettings strategySetting : strategySettings) { + config.replanning().addStrategySettings(strategySetting); } } diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/instrumentation/scorestats/SlaveScoreStats.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/instrumentation/scorestats/SlaveScoreStats.java index 06e0283c0c1..bfdcb73bf86 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/instrumentation/scorestats/SlaveScoreStats.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/instrumentation/scorestats/SlaveScoreStats.java @@ -19,8 +19,8 @@ public class SlaveScoreStats implements ScoreStats { int firstIter; public SlaveScoreStats(Config config) { - firstIter = config.controler().getFirstIteration(); - int size = config.controler().getLastIteration() - firstIter+1; + firstIter = config.controller().getFirstIteration(); + int size = config.controller().getLastIteration() - firstIter+1; this.history = new double[4][size]; } @@ -41,6 +41,6 @@ public double[][] getScoreHistoryAsArray() { public Map> getScoreHistory() { throw new RuntimeException("not implemented") ; } - - + + } diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/listeners/controler/GenomeAnalysis.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/listeners/controler/GenomeAnalysis.java index 901600f9c03..dfa93a6a0c4 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/listeners/controler/GenomeAnalysis.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/listeners/controler/GenomeAnalysis.java @@ -37,7 +37,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { Map fullGeneScore = new HashMap<>(); Map fullGeneAltScore = new HashMap<>(); Map, ? extends Person> persons = event.getServices().getScenario().getPopulation().getPersons(); - boolean append = event.getIteration() != event.getServices().getConfig().controler().getFirstIteration(); + boolean append = event.getIteration() != event.getServices().getConfig().controller().getFirstIteration(); try { PrintWriter writer = null; PrintWriter scoreComponentWriter = null; @@ -234,4 +234,4 @@ public SimpleLink(String genome, int count, double score, double altscore) { this.score = score; this.altscore = altscore; } -} \ No newline at end of file +} diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/listeners/controler/SlaveScoreWriter.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/listeners/controler/SlaveScoreWriter.java index 22bac23252a..2d0576c8a85 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/listeners/controler/SlaveScoreWriter.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/listeners/controler/SlaveScoreWriter.java @@ -9,10 +9,10 @@ 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.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; public class SlaveScoreWriter implements IterationEndsListener, ShutdownListener, StartupListener { @@ -32,7 +32,7 @@ public SlaveScoreWriter(MasterControler controler) { @Override public void notifyIterationEnds(IterationEndsEvent event) { double[][] history = controler.getSlaveScoreHistory(); - int idx = event.getIteration() - controler.getConfig().controler().getFirstIteration(); + int idx = event.getIteration() - controler.getConfig().controller().getFirstIteration(); try { out.write(event.getIteration() + "\t" + history[INDEX_EXECUTED][idx] + "\t" @@ -52,7 +52,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { "iteration", "score"); double[] iterations = new double[idx]; for (int i = 0; i < idx; i++) { - iterations[i] = i + controler.getConfig().controler().getFirstIteration()+1; + iterations[i] = i + controler.getConfig().controller().getFirstIteration()+1; } double[] values = new double[idx]; double[] fullhist = new double[idx]; diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/plans/PlanGenome.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/plans/PlanGenome.java index 12cd0a7023f..33ee42fbc42 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/plans/PlanGenome.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/distributed/plans/PlanGenome.java @@ -219,6 +219,24 @@ public String getType() { public void setType(final String type) { this.type = type; } + + @Override + public Id getId() { return null; } + + @Override + public void setPlanId(Id planId) { /* nothing to do here */ } + + @Override + public int getIterationCreated() { return -1; } + + @Override + public void setIterationCreated(int iteration) { /* nothing to do here */ } + + @Override + public String getPlanMutator() { return null; } + + @Override + public void setPlanMutator(String planMutator) { /* nothing to do here */ } @Override public final List getPlanElements() { diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/PSimProvider.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/PSimProvider.java index 2759e9c38be..baa9619edc4 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/PSimProvider.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/PSimProvider.java @@ -4,8 +4,6 @@ package org.matsim.contrib.pseudosimulation.mobsim; import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; import org.matsim.contrib.pseudosimulation.distributed.listeners.events.transit.TransitPerformance; import org.matsim.contrib.pseudosimulation.mobsim.transitperformance.TransitEmulator; import org.matsim.contrib.pseudosimulation.replanning.PlanCatcher; @@ -42,25 +40,25 @@ public void setTravelTime(TravelTime travelTime) { this.travelTime = travelTime; } - @Deprecated - public void setWaitTime(WaitTime waitTime) { - throw new RuntimeException("Use an instance of " + TransitEmulator.class.getSimpleName() + " instead."); - } +// @Deprecated +// public void setWaitTime(WaitTime waitTime) { +// throw new RuntimeException("Use an instance of " + TransitEmulator.class.getSimpleName() + " instead."); +// } - @Deprecated - public void setStopStopTime(StopStopTime stopStopTime) { - throw new RuntimeException("Use an instance of " + TransitEmulator.class.getSimpleName() + " instead."); - } +// @Deprecated +// public void setStopStopTime(StopStopTime stopStopTime) { +// throw new RuntimeException("Use an instance of " + TransitEmulator.class.getSimpleName() + " instead."); +// } @Deprecated public void setTransitPerformance(TransitPerformance transitPerformance) { throw new RuntimeException("Use an instance of " + TransitEmulator.class.getSimpleName() + " instead."); } - @Deprecated - public void setTimes(TravelTime travelTime, WaitTime waitTime, StopStopTime stopStopTime) { - throw new RuntimeException("Use an instance of " + TransitEmulator.class.getSimpleName() + " instead."); - } +// @Deprecated +// public void setTimes(TravelTime travelTime, WaitTime waitTime, StopStopTime stopStopTime) { +// throw new RuntimeException("Use an instance of " + TransitEmulator.class.getSimpleName() + " instead."); +// } @Deprecated //will replace where necessary diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/SwitchingMobsimProvider.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/SwitchingMobsimProvider.java index ef6d34a7f32..61de8d12aae 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/SwitchingMobsimProvider.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/SwitchingMobsimProvider.java @@ -30,8 +30,6 @@ import org.matsim.core.mobsim.framework.Mobsim; import org.matsim.core.mobsim.jdeqsim.JDEQSimConfigGroup; import org.matsim.core.mobsim.jdeqsim.JDEQSimulation; -import org.matsim.core.mobsim.qsim.QSim; -import org.matsim.core.mobsim.qsim.QSimBuilder; import org.matsim.core.mobsim.qsim.QSimProvider; import org.matsim.core.utils.timing.TimeInterpretation; @@ -52,7 +50,7 @@ public class SwitchingMobsimProvider implements Provider { @Override public Mobsim get() { - String mobsim = config.controler().getMobsim(); + String mobsim = config.controller().getMobsim(); if (mobSimSwitcher.isQSimIteration()) { if (mobsim.equals("jdeqsim")) { return new JDEQSimulation(ConfigUtils.addOrGetModule(scenario.getConfig(), JDEQSimConfigGroup.NAME, JDEQSimConfigGroup.class), scenario, eventsManager, timeInterpretation); diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/transitperformance/TransitPerformanceFromEventBasedRouterInterfaces.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/transitperformance/TransitPerformanceFromEventBasedRouterInterfaces.java index 13f2536ddf9..e767a863b02 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/transitperformance/TransitPerformanceFromEventBasedRouterInterfaces.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/mobsim/transitperformance/TransitPerformanceFromEventBasedRouterInterfaces.java @@ -1,6 +1,6 @@ /* * Copyright 2018 Gunnar Flötteröd - * + * * 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 3 of the License, or @@ -23,8 +23,8 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Leg; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; +//import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; +//import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; import org.matsim.pt.routes.TransitPassengerRoute; import org.matsim.pt.transitSchedule.TransitRouteImpl; import org.matsim.pt.transitSchedule.api.TransitLine; @@ -44,16 +44,16 @@ */ public class TransitPerformanceFromEventBasedRouterInterfaces implements TransitEmulator { - private WaitTime waitTimes; - private StopStopTime stopStopTimes; +// private WaitTime waitTimes; +// private StopStopTime stopStopTimes; private Map, TransitLine> transitLines; private Map, TransitStopFacility> stopFacilities; @Inject - public TransitPerformanceFromEventBasedRouterInterfaces(WaitTime waitTimes, StopStopTime stopStopTimes, + public TransitPerformanceFromEventBasedRouterInterfaces(/*WaitTime waitTimes, StopStopTime stopStopTimes,*/ TransitSchedule transitSchedule) { - this.waitTimes = waitTimes; - this.stopStopTimes = stopStopTimes; +// this.waitTimes = waitTimes; +// this.stopStopTimes = stopStopTimes; this.transitLines = transitSchedule.getTransitLines(); this.stopFacilities = transitSchedule.getFacilities(); } @@ -65,8 +65,8 @@ public Trip findTrip(Leg prevLeg, double earliestDepartureTime_s) { TransitLine line = this.transitLines.get(route.getLineId()); TransitRoute transitRoute = line.getRoutes().get(route.getRouteId()); - final double accessTime_s = earliestDepartureTime_s + this.waitTimes.getRouteStopWaitTime(route.getLineId(), - transitRoute.getId(), route.getAccessStopId(), earliestDepartureTime_s); + final double accessTime_s = earliestDepartureTime_s /*+ this.waitTimes.getRouteStopWaitTime(route.getLineId(), + transitRoute.getId(), route.getAccessStopId(), earliestDepartureTime_s)*/; final double egressTime_s = accessTime_s + this.findTransitTravelTime(route, accessTime_s); return new Trip(null, accessTime_s, egressTime_s); } @@ -99,7 +99,7 @@ private double findTransitTravelTime(TransitPassengerRoute route, double prevEnd Id fromId = transitRoute.getStops().get(i).getStopFacility().getId(); TransitRouteStop toStop = transitRoute.getStops().get(i + 1); Id toId = toStop.getStopFacility().getId(); - travelTime += stopStopTimes.getStopStopTime(fromId, toId, prevStopTime); +// travelTime += stopStopTimes.getStopStopTime(fromId, toId, prevStopTime); prevStopTime += travelTime; if (toStop.getStopFacility().getId().equals(dest)) { destinationFound = true; diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/replanning/DistributedPlanStrategyTranslationAndRegistration.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/replanning/DistributedPlanStrategyTranslationAndRegistration.java index 148ead7b851..1baf66c5b01 100644 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/replanning/DistributedPlanStrategyTranslationAndRegistration.java +++ b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/replanning/DistributedPlanStrategyTranslationAndRegistration.java @@ -4,7 +4,7 @@ import org.matsim.contrib.pseudosimulation.replanning.factories.DistributedPlanMutatorStrategyFactory; import org.matsim.contrib.pseudosimulation.replanning.factories.DistributedPlanSelectorStrategyFactory; import org.matsim.core.config.Config; -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.replanning.PlanStrategy; @@ -115,7 +115,7 @@ public static boolean isStrategySupported(String name) { } public static void substituteStrategies(Config config, boolean quickReplanning, int selectionInflationFactor) { - for (StrategyConfigGroup.StrategySettings settings : config.strategy().getStrategySettings()) { + for (ReplanningConfigGroup.StrategySettings settings : config.replanning().getStrategySettings()) { String classname = settings.getStrategyName(); diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/PSimStopStopTimeCalculator.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/PSimStopStopTimeCalculator.java deleted file mode 100644 index 4b1a0e49a21..00000000000 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/PSimStopStopTimeCalculator.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.matsim.contrib.pseudosimulation.trafficinfo; - -import com.google.inject.Singleton; -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.events.PersonLeavesVehicleEvent; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculatorSerializable; -import org.matsim.contrib.pseudosimulation.MobSimSwitcher; -import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; -import org.matsim.core.config.Config; -import org.matsim.pt.transitSchedule.api.TransitSchedule; - -import jakarta.inject.Inject; - -@Singleton -public class PSimStopStopTimeCalculator extends StopStopTimeCalculatorSerializable { - private final MobSimSwitcher switcher; - - @Inject - PSimStopStopTimeCalculator(Scenario scenario, MobSimSwitcher switcher, EventsManager eventsManager) { - super(scenario.getTransitSchedule(),scenario.getConfig() ); - this.switcher = switcher; - eventsManager.addHandler(this); - } - - @Override - public void reset(int iteration) { - if (switcher.isQSimIteration()) { - LogManager.getLogger(this.getClass()).error( - "Calling reset on traveltimecalc"); - super.reset(iteration); - } - } - - @Override - public void handleEvent(VehicleArrivesAtFacilityEvent event) { - if (switcher.isQSimIteration()) - super.handleEvent(event); - } - - @Override - public void handleEvent(PersonLeavesVehicleEvent event) { - if (switcher.isQSimIteration()) - super.handleEvent(event); - } - -} diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/PSimWaitTimeCalculator.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/PSimWaitTimeCalculator.java deleted file mode 100644 index f618a5c8a45..00000000000 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/PSimWaitTimeCalculator.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.matsim.contrib.pseudosimulation.trafficinfo; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -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.events.PersonDepartureEvent; -import org.matsim.api.core.v01.events.PersonEntersVehicleEvent; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeCalculatorSerializable; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeStuckCalculator; -import org.matsim.contrib.pseudosimulation.MobSimSwitcher; -import org.matsim.core.api.experimental.events.EventsManager; - - -/** - * @author fouriep - *

      - * Extends Ordonez's {@link WaitTimeStuckCalculator} to only handle - * events during QSim iterations. - */ -@Singleton -public class PSimWaitTimeCalculator extends WaitTimeCalculatorSerializable { - private final MobSimSwitcher switcher; - - @Inject - public PSimWaitTimeCalculator(Scenario scenario, - MobSimSwitcher switcher, EventsManager eventsManager) { - super(scenario.getTransitSchedule(),scenario.getConfig()); - this.switcher = switcher; - eventsManager.addHandler(this); - } - - @Override - public void reset(int iteration) { - if (switcher.isQSimIteration()) { - LogManager.getLogger(this.getClass()).error( - "Calling reset on traveltimecalc"); - super.reset(iteration); - } - } - - @Override - public void handleEvent(PersonDepartureEvent event) { - if (switcher.isQSimIteration()) - super.handleEvent(event); - } - - @Override - public void handleEvent(PersonEntersVehicleEvent event) { - if (switcher.isQSimIteration()) - super.handleEvent(event); - } - - - -} diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/deterministic/DeterministicStopStopTimeCalculator.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/deterministic/DeterministicStopStopTimeCalculator.java deleted file mode 100644 index 567187f053d..00000000000 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/deterministic/DeterministicStopStopTimeCalculator.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.matsim.contrib.pseudosimulation.trafficinfo.deterministic; - -import java.util.List; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTime; -import org.matsim.contrib.eventsBasedPTRouter.stopStopTimes.StopStopTimeCalculator; -import org.matsim.core.router.DefaultRoutingRequest; -import org.matsim.pt.router.TransitRouter; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.utils.objectattributes.attributable.Attributes; - -import com.google.inject.Inject; -import com.google.inject.Singleton; - -@Singleton -public class DeterministicStopStopTimeCalculator implements StopStopTimeCalculator { - private final TransitRouter transitRouter; - private final TransitSchedule schedule; - - @Inject - public DeterministicStopStopTimeCalculator(TransitRouter transitRouter, TransitSchedule schedule) { - this.transitRouter = transitRouter; - this.schedule = schedule; - } - - @Override - public double getStopStopTime(Id stopOId, Id stopDId, double time) { - // ATTENTION! This could be optimized. Basically, we probably don't need to - // route here. However, finding the travel time even on one route is not a - // computationally efficient task, because the same transit stop id may occur - // multiple times on the same route. - - TransitStopFacility originFacility = schedule.getFacilities().get(stopOId); - TransitStopFacility destinationFacility = schedule.getFacilities().get(stopDId); - - List legs = transitRouter.calcRoute(DefaultRoutingRequest.withoutAttributes(originFacility, destinationFacility, time, null)); - return legs.stream().mapToDouble(l -> ((Leg)l).getTravelTime().seconds()).sum(); - } - - @Override - public double getStopStopTimeVariance(Id stopOId, Id stopDId, - double time) { - return 0.0; - } - - @Override - public StopStopTime get() { - return new StopStopTime() { - @Override - public double getStopStopTimeVariance(Id stopOId, Id stopDId, - double time) { - return 0.0; - } - - @Override - public double getStopStopTime(Id stopOId, Id stopDId, - double time) { - return DeterministicStopStopTimeCalculator.this.getStopStopTime(stopOId, stopDId, time); - } - }; - } -} diff --git a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/deterministic/DeterministicWaitTimeCalculator.java b/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/deterministic/DeterministicWaitTimeCalculator.java deleted file mode 100644 index d1aa43ce61b..00000000000 --- a/contribs/pseudosimulation/src/main/java/org/matsim/contrib/pseudosimulation/trafficinfo/deterministic/DeterministicWaitTimeCalculator.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.matsim.contrib.pseudosimulation.trafficinfo.deterministic; - -import java.util.LinkedList; -import java.util.List; - -import org.matsim.api.core.v01.Id; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTime; -import org.matsim.contrib.eventsBasedPTRouter.waitTimes.WaitTimeCalculator; -import org.matsim.pt.transitSchedule.api.Departure; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitRouteStop; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -import com.google.inject.Inject; -import com.google.inject.Singleton; - -@Singleton -public class DeterministicWaitTimeCalculator implements WaitTimeCalculator { - private final TransitSchedule schedule; - - @Inject - public DeterministicWaitTimeCalculator(TransitSchedule schedule) { - this.schedule = schedule; - } - - @Override - public double getRouteStopWaitTime(Id lineId, Id routeId, Id stopId, - double time) { - TransitRoute route = schedule.getTransitLines().get(lineId).getRoutes().get(routeId); - - // First collect all the offsets on the route for a specific transit stop id. - // Note that a single transit facility may be contained multiple times on a - // route! - List facilityOffsets = new LinkedList<>(); - - for (TransitRouteStop stop : route.getStops()) { - if (stop.getStopFacility().getId().equals(stopId)) { - facilityOffsets.add(stop.getDepartureOffset().seconds()); - } - } - - if (facilityOffsets.size() == 0) { - // The facility is not contained on this route - throw new IllegalStateException(); - } - - // Now loop through all the departures and routes and find the actual stop - // departure that is right after the given time. - - double minimumWaitTime = Double.POSITIVE_INFINITY; - - for (double offset : facilityOffsets) { - for (Departure departure : route.getDepartures().values()) { - double stopDepartureTime = departure.getDepartureTime() + offset; - - while (stopDepartureTime < time) { - // Consistent with TransitRouterNetworkTravelTimeAndDisutility.MIDNIGHT - stopDepartureTime += 24.0 * 3600; - } - - double waitTime = time - stopDepartureTime; - - if (waitTime < minimumWaitTime) { - minimumWaitTime = waitTime; - } - } - } - - return minimumWaitTime; - } - - @Override - public WaitTime get() { - return new WaitTime() { - @Override - public double getRouteStopWaitTime(Id lineId, Id routeId, - Id stopId, double time) { - return DeterministicWaitTimeCalculator.this.getRouteStopWaitTime(lineId, routeId, stopId, time); - } - }; - } -} diff --git a/contribs/pseudosimulation/src/test/java/org/matsim/contrib/pseudosimulation/RunPSimTest.java b/contribs/pseudosimulation/src/test/java/org/matsim/contrib/pseudosimulation/RunPSimTest.java index 02d4125191c..2a82fc13096 100644 --- a/contribs/pseudosimulation/src/test/java/org/matsim/contrib/pseudosimulation/RunPSimTest.java +++ b/contribs/pseudosimulation/src/test/java/org/matsim/contrib/pseudosimulation/RunPSimTest.java @@ -1,10 +1,6 @@ package org.matsim.contrib.pseudosimulation; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Assert; @@ -18,8 +14,7 @@ import org.matsim.contrib.pseudosimulation.mobsim.transitperformance.TransitEmulator; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.StrategyConfigGroup; -import org.matsim.core.config.groups.PlansConfigGroup.HandlingOfPlansWithoutRoutingMode; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.MatsimServices; @@ -30,15 +25,18 @@ import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; -import org.matsim.pt.config.TransitConfigGroup.TransitRoutingAlgorithmType; import org.matsim.testcases.MatsimTestUtils; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RunPSimTest { @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - private Logger logger = LogManager.getLogger(RunPSimTest.class ); + private final Logger logger = LogManager.getLogger(RunPSimTest.class ); private final Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("pt-tutorial" ),"0.config.xml" ) ); @@ -47,22 +45,18 @@ public class RunPSimTest { */ @Test public void testA() { - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); - config.controler().setCreateGraphs(false); + config.controller().setCreateGraphs(false); PSimConfigGroup pSimConfigGroup = new PSimConfigGroup(); config.addModule(pSimConfigGroup); pSimConfigGroup.setIterationsPerCycle(20); - - config.plansCalcRoute().setRoutingRandomness(0.); + + config.routing().setRoutingRandomness(0.); //identify selector strategies Field[] selectors = DefaultPlanStrategiesModule.DefaultSelector.class.getDeclaredFields(); List selectorNames = new ArrayList<>(); -// for (Field selector : selectors) { -// selectorNames.add(selector.toString()); -// logger.warn( selector.toString() ); -// } + // yyyyyy does not work as designed selectorNames.add( DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta ); selectorNames.add( DefaultPlanStrategiesModule.DefaultSelector.BestScore ); @@ -72,7 +66,7 @@ public void testA() { selectorNames.add( DefaultPlanStrategiesModule.DefaultSelector.SelectExpBeta ); //lower the weight of non-selector strategies, as we will run many iters - for( StrategyConfigGroup.StrategySettings settings : config.strategy().getStrategySettings() ){ + for( ReplanningConfigGroup.StrategySettings settings : config.replanning().getStrategySettings() ){ if( !selectorNames.contains( settings.getStrategyName() ) ){ logger.warn( settings.getStrategyName() ); settings.setWeight( settings.getWeight() * 20 ); @@ -83,8 +77,8 @@ public void testA() { // System.exit( -1); final String outDir = utils.getOutputDirectory(); - config.controler().setOutputDirectory( outDir ); - config.controler().setLastIteration(20); + config.controller().setOutputDirectory( outDir ); + config.controller().setLastIteration(20); // config.controler().setDumpDataAtEnd(false); // config.strategy().setFractionOfIterationsToDisableInnovation( 0.8 ); // crashes @@ -95,12 +89,12 @@ public void testA() { ((Controler) runPSim.getMatsimControler()).addOverridingModule(new AbstractModule() { @Override - public void install() { + public void install() { this.bind(TransitEmulator.class).to(NoTransitEmulator.class); } }); - - + + runPSim.run(); double psimScore = execScoreTracker.executedScore; logger.info("RunPSim score was " + psimScore); @@ -109,36 +103,33 @@ public void install() { Population popActual = PopulationUtils.createPopulation( config ); PopulationUtils.readPopulation( popActual, outDir + "/output_plans.xml.gz" ); new PopulationComparison().compare( popExpected, popActual ) ; - Assert.assertEquals("RunPsim score changed.", 138.90472630897597d, psimScore, MatsimTestUtils.EPSILON); -// Assert.assertEquals("RunPsim score changed.", 134.54001491094124d, psimScore, MatsimTestUtils.EPSILON); -// Assert.assertEquals("RunPsim score changed.", 134.52369453719413d, psimScore, MatsimTestUtils.EPSILON); -// Assert.assertEquals("RunPsim score changed.", 132.73129073101293d, psimScore, MatsimTestUtils.EPSILON); + Assert.assertEquals("RunPsim score changed.", 138.86084460860525, psimScore, MatsimTestUtils.EPSILON); + } /** * For comparison run 2 normal qsim iterations. Psim score should be slightly higher than default Controler score. - * + * * Prior to implementing routing mode RunPSimTest tested only that psimScore outperformed default Controler on this * test for executed score by a margin > 1%. In the last commit in matsim master where the test ran, the psim score * in testA() was 134.52369453719413 and qsim score in testB was 131.84309487251033). */ @Test public void testB() { - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(2); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); - config.plansCalcRoute().setRoutingRandomness(0.); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(2); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); + config.routing().setRoutingRandomness(0.); Controler controler = new Controler(config); ExecScoreTracker execScoreTracker = new ExecScoreTracker(controler); controler.addControlerListener(execScoreTracker); controler.run(); - + double qsimScore = execScoreTracker.executedScore; logger.info("Default controler score was " + qsimScore ); // Assert.assertEquals("Default controler score changed.", 131.84309487251033d, qsimScore, MatsimTestUtils.EPSILON); - Assert.assertEquals("Default controler score changed.", 131.84350487113088d, qsimScore, MatsimTestUtils.EPSILON); + Assert.assertEquals("Default controler score changed.", 131.8303325803256, qsimScore, MatsimTestUtils.EPSILON); } class ExecScoreTracker implements ShutdownListener { @@ -151,7 +142,7 @@ class ExecScoreTracker implements ShutdownListener { @Override public void notifyShutdown(ShutdownEvent event) { - executedScore = controler.getScoreStats().getScoreHistory().get(ScoreStatsControlerListener.ScoreItem.executed).get(controler.getConfig().controler().getLastIteration()); + executedScore = controler.getScoreStats().getScoreHistory().get(ScoreStatsControlerListener.ScoreItem.executed).get(controler.getConfig().controller().getLastIteration()); } diff --git a/contribs/railsim/README.md b/contribs/railsim/README.md new file mode 100644 index 00000000000..3efbc30fedc --- /dev/null +++ b/contribs/railsim/README.md @@ -0,0 +1,35 @@ +# railsim + +A large-scale hybrid micro- and mesoscopic simulation approach for railway operation. + +Trains behave and interact with links differently than cars: While usually multiple cars can be on one link, +for safety reasons there should be only one train on a track (segment or block) per time. +And while a car is typically located on one link only, a long train may occupy space on multiple links. +To capture these differences and offer a realistic simulation of train traffic within MATSim, +the *railsim* contrib provides a custom QSim-Engine to simulate trains: + +- Trains are spatially expanded along several links. Additional events indicate when the end of the train leaves a link. +- Trains accelerate and decelerate based on predefined vehicle attributes (along a single link or along several links). +- The infrastructure ahead of each train is blocked (reserved train path) depending on the braking distance which is + computed based on the vehicle-specific deceleration and the current speed. +- Capacity effects are modeled at the level of resources. A resource consists of one link or several links. +- Trains may deviate from the network route given in the schedule, e.g. to avoid a blocked track (dispatching, + disposition). + +## Configuration + +See `config.RailsimConfigGroup.java` + +## Enabling railsim in MATSim + +See `RunRailsimExample.java` + +## Specifications + +- [network-specification](docs/network-specification.md) +- [train-specification](docs/train-specification.md) +- [events-specification](docs/events-specification.md) + +## Acknowledgments + +This contrib was initiated and initially funded by the [Swiss Federal Railways](https://www.sbb.ch) (SBB). diff --git a/contribs/railsim/docs/deadlock-avoidance.md b/contribs/railsim/docs/deadlock-avoidance.md new file mode 100644 index 00000000000..5b8a2229823 --- /dev/null +++ b/contribs/railsim/docs/deadlock-avoidance.md @@ -0,0 +1,145 @@ +# Deadlock-Avoidance + +Deadlocks can occur on two scales in the mesoscopic approach of railsim: + +- Locally within a route section with constant capacity: *Deadlock in a route section with bidirectionally shared + constant capacity.* +- Globally due to conflicting route selections in the network: *Deadlock due to sequence of multiple route sections with + different bidirectionally shared capacities (bottleneck).* + +## Local case + +The local case seems easier to solve. A possible approach is described below: + +Before a train travels on a section with constant capacity (successive links with constant capacity, where the speed +limit may vary, hereafter called segment), it must check that not all tracks are already occupied from the opposite +direction. If this is the case, the train must wait in front of the segment before entering. If at least one track from +the opposite direction is free, then the train must check whether tracks in its direction are already in use. If this is +the case, it will be checked that the incoming train is not slowed down by the preceding train if there is sufficient +capacity, so that the faster train can overtake the slower train. If the incoming train is slower than the previous +train anyway, it should enter the same track to keep as much capacity as possible free for the opposite direction. + +The tracks of a segment could be represented as an array of free-again times (maximum of the exit times of the trains on +a track) or zero if the track is free. When a train enters a track it overwrites the free-again time, if its exit time +is after the exit time of the preceding train. + +## Global case + +The global case is more complex to solve, and the problem is described below. The description is based on the segments +defined in the local case, even though they could possibly be omitted for this case, depending on the chosen solution +approach. + +A train on its route reserves segments ahead as far as possible (see *full path reservation*) or alternatively until the +next station with the assumption that there are enough tracks available in the station to pass each other (see *station +to station path reservation*). +If two reserved paths running in opposite directions meet in a segment and the maximum capacity in the segment is used, +then both trains should travel as far as it is still possible to pass each other. So they have to stop before the +bottleneck, where the capacity still allows for a crossing. The train that arrives first at the bottleneck continues its +path, while the other train remains stationary until it no longer sees the opposite train in its reserved path. Then +the waiting train continues its path into the bottleneck. + +This raises a few questions: + +- What happens when several (not just two) reserved paths overlap? No matter how many trains are oncoming, the segment + must allow **one** free track in the opposite direction. +- In situations with multiple overlaps, how do we find the positions where the trains should wait? Last places on the + path where the equivalent capacity is at least 1? +- How do we solve the problem computationally efficiently? + +### Full path reservation + +In case of reservation of the entire route of a train line, i.e. from the origin station to the destination station of +the route, deadlocks are no longer possible on the route. If we have vehicle circuits where a train is waiting at the +destination station for the next departure (and thus blocks a track), again a deadlock would be possible when another +train tries to enter the destination station and no track is available. + +==To Discuss:== this case is probably rather rare and negligible for the time being? If we model the stations as +segments too, then this case should be automatically solved? + +**Key idea** + +We have agents who want to navigate through resources. In the context of railsim, agents are individual vehicles, +resources are `RailLink`s (?), and the full path of an agent is the transit route it takes from the origin to the +destination station. A vehicle can have several transit routes on a simulation day. +Assuming that the current simulation is in a deadlock-free state, the goal is to ensure that the simulation will also be +deadlock-free after a next simulation step. This requires a deadlock avoidance algorithm. The algorithm shall prevent +deadlock state from occurring. + +**Algorithm** + +1. Setup: + - Create a constant 1D-array with total train capacity per resource **CAP** (dim: 1 x n_resources) + - Create a binary matrix for global positions **POS** (dim: n_agents x n_resources) and initialize it with zero. + - Create a binary matrix for all path masks **PATH** (dim: n_agents x n_resources) and calculate for each + agent **a_i** the binary mask for the full path with resources needed to reach the destination. Write mask into + the paths mask matrix **PATH[a_i, ]**. + - Create a set with moving agents **MOV** and a set with agents on a decision point resource **DEC**. Add all agents + to both sets. +2. Start railsim simulation, in each iteration: + 1. Handle moving set agents: + - For each agent in the moving set **MOV** enter the currently occupied resource into the global position + mask **POS[a_i, ]**. + 2. Handle decision set agents: + - Mask the path of each agent in the decision set **DEC** with the global position mask and identify all + potentially conflicting agents. + - Create a new 1D-array (dim: 1 x n_resources) with the sum of paths of all conflicting agents per agent (zero + out non-conflicting agents in **PATH** and sum the columns). + - Subtract the summed path array from the constant available capacity layer **CAP** for each agent. + - If the next resource an agent wants to allocate has at least one free capacity, the agent is added to the + moving set **MOV**, otherwise the agent is removed from the moving set and has to wait on the current resource + for this iteration. + 3. The steps 1 and 2 are repeated for **the situation where the next step is already moved virtually** of all agents + in the moving agent set. If there is a conflict, randomly chose one agent of the conflicting pair and remove it + from the moving set (has to wait in this interation). Do not save the actual movement from this step! + 4. For all agents in the moving set **MOV**, set the current resource in the path matrix to zero + **PATH[a_i, r_c]=0**. and check if the next resource they occupy is a decision point. If it is a decision point, + add the agent to the decision set *DEC*. + 5. Continue railsim iteration (here the actual movement of the agent happens) and repeat. + +**Key benefits** + +The algorithm described above can be fully parallelized. The computation time depends only on the number of agents (n) +and number of resources (m). The computation complexity is O(n2 * m) in the worst case. + +**References** + +This algorithm was designed and implemented by Adrian Egli (SBB) as part of the Flatland project. + +**Railsim context** + +- Resources have to be smaller entities (e.g. `RailLink`) than segments, since otherwise two agents are not allowed to + travel in the same direction. +- Not all resources should trigger the deadlock avoidance algorithm for the agent. For better performance, only when an + agent is on a decision point (decision set of agents), the algorithm is triggered (e.g. first / entering `RailLink` of + a segment with constant capacity). +- The former two points could be combined: + - Each segment consists of the following **directed** `RailLink`s for both directions (2x): An *entering* `RailLink` + , *intermediate* `RailLink`s for each change in VMax (with same capacity), a *leaving* `RailLink`. + - Every `RailLink` has an opposite direction `RailLink`, where the entering link is the leaving link and vice versa. + - The algorithm is only triggered on the **leaving** `RailLink`s. + - Stations could also be modelled as segments (entering, intermediate, leaving links). +- I (mu) am not sure if we still need the combination with the local deadlock case, but I suspect that this is necessary + if the capacity of a segment is greater than 1. We then have to determine which train is on which track to see if the + train can overtake or has to brake. + +### Station to station path reservation + +In the case where the trains only reserve the path to the next station, a deadlock is again possible when entering the +station. It is not guaranteed that the train can enter the station, and a train in the station (travelling in the +opposite direction), could be waiting for the incoming train to free its track. + +==To Discuss:== do we want to see this deadlock or should the simulation should never block in general? + +If the simulation never blocks, a lack of capacity in a station should be visible in the delays of the trains. It is +probably not easy to find the initial cause of the delay, as a delay potentially propagates and affects other trains. +Additional events may be needed to signal and document a train's decision to wait at a particular point and thus deviate +from the timetable. This allows to detect the origins and the course of the delays in an event analysis after the +simulation. + +## References + +The deadlock problem has already been solved in the Flatland project and could be used as a starting point or serve as +inspiration: + +- [flatland_solver_policy/policy/heuristic_policy/shortest_path_deadlock_avoidance_policy/deadlock_avoidance_policy.py](https://github.com/aiAdrian/flatland_solver_policy/blob/main/policy/heuristic_policy/shortest_path_deadlock_avoidance_policy/deadlock_avoidance_policy.py) +- [flatland/flatland/contrib/utils/deadlock_checker.py](https://gitlab.aicrowd.com/flatland/flatland/-/blob/master/flatland/contrib/utils/deadlock_checker.py) diff --git a/contribs/railsim/docs/events-specification.md b/contribs/railsim/docs/events-specification.md new file mode 100644 index 00000000000..e960461b9fe --- /dev/null +++ b/contribs/railsim/docs/events-specification.md @@ -0,0 +1,36 @@ +# Events-Specification + +railsim introduces additional, custom events. This document describes these event types. + +All the additional events use the prefix `railsim`. + +## Event Types + +### RailsimLinkStateChangeEvent + +The generic `RailsimLinkStateChangeEvent` includes information about the new state of a link (or even the track of a +multi-track link). + +Attributes: + +- `state`: `free` or `blocked` +- `vehicleId`: if `state=reserved|blocked`, the id of the vehicle blocking or reserving this link +- `track`: a number (0-based or 1-based?) if the link has multiple tracks + +### RailsimTrainLeavesLinkEvent + +One could argue that setting the link state to `free` would imply the same. I (mr) would still +say it makes sense to have it separate, because depending on the implementation, a link could +remain blocked for a longer time even if the train has already passed (e.g. minimum headway time). + +There is **no** `RailsimTrainEntersLinkEvent`. The regular `LinkEnterEvent` is used to provide the highest +compatibility with existing analysis and visualization tools. + +### RailsimTrainStateEvent + +This event is emitted every time there is a position update for a train and contains detailed information about the +trains position on a single link. + +### RailsimDetourEvent + +This event is emitted when a train is re-routed and contains parts of the routes that have changed. diff --git a/contribs/railsim/docs/network-specification.md b/contribs/railsim/docs/network-specification.md new file mode 100644 index 00000000000..956de2e3da3 --- /dev/null +++ b/contribs/railsim/docs/network-specification.md @@ -0,0 +1,226 @@ +# Network-Specification + +## Introduction + +As trains interact differently with links than regular cars, the typical attributes like `capacity` and `lanes` are not +suitable for describing rail infrastructure. + +railsim uses custom link attributes to describe the essential parts of the rail infrastructure. +This document specifies these custom attributes. + +For the maximum allowed speed on a link, the normal `freespeed` attribute is used. + +## Specification + +We use the prefix `railsim` where it is appropriate. + +### Link Attributes + +#### railsimTrainCapacity + +The number of trains that can be on this link at the same time. If the attribute is not provided, a default of 1 is +used. +railsim supports the microscopic modelling of tracks, where each link represents a single track (`railsimCapacity` = 1 +or default), and a mesoscopic level of modelling, where a link may represent multiple tracks (`railsimCapacity` > 1). + +Example: + +```xml + + + + 3 + + + +``` + +#### railsimResourceId + +The id of a resource, i.e. a segment of links that share a constant capacity. + +This can be used to denote certain blocks of links that can only be reserved as a whole. +One use-case is the modelling of bidirectional links, where one train blocks both directions. +MATSim uses uni-directional links. While on a road, cars might usually be able to pass each other +even on small roads by going very slow and near the edge, but trains cannot. + +This can also be used to model intersections as one resource, which will restrict crossing trains. + +The train capacity will be derived as the minimum of all included links of this resource. +Links that have no resource id will be handled as individual resource. + +#### railsimMinimumTime + +The minimum time ("minimum train headway time") for the switch at the end of the link (toNode). +If no link attribute is provided, a default of 0 is used. + +#### railsimEntry + +Entry link of a station, triggers re-routing and serves as origin. + +#### railsimExit + +Exit link of a station, denotes a destination in re-routing. + +Example: + +```xml + + + + true + + + +``` + +#### railsimSpeed_ + vehicle type + +TODO + +The vehicle-specific freespeed on this link. +Please note that the actual vehicle-type must be used as part of the attribute name, see example. + +Example: + +```xml + + + + 44.444 + 50.0 + + + +``` + +### Node Attributes + +Currently none. + +## Microscopic + +### Moving Block + +Model tracks consisting of short links. Each link, except for the opposite link, has a unique resource ID and a capacity +of 1. + +### Fixed block + +Model blocks of links with a capacity of 1 each and identical resource IDs. + +### Station + +Each platform link has a distinct resource ID, except for the opposite link, and a capacity of 1. Each platform link has +a transit stop facility, which belongs to the same stop area id. Ingoing and outgoing links of the station have entry +and exit attributes. + +### Examples + +#### Single track with contraflow + +Default value of `railsimCapacity` sets an own railsimResourceId for each track. + +```xml + + + + + AB + + + + + AB + + + +``` + +#### Two tracks, each with a single direction + +Default value of `railsimResourceId` sets an own railsimResourceId for each track. + +```xml + + + + + + + +``` + +#### Three tracks, with contraflow in the middle track + +```xml + + + + + + + AB + + + + + AB + + + + + +``` + +#### Two tracks that intersect each other + +If two tracks cross each other, e.g. like in the form of the letter `X` or a plus `+`, a train driving in one direction +effectively also blocks the intersecting tracks, even if they only share a common node, but not a common link. + +There should be no additional link- or node-attributes necessary. The simulation should block the node in the case of +`railsimCapacity = 1`, but not if the capacity is larger than 1. If the node is blocked, no other trains must be able +to cross this node/intersection. + +## Mesoscopic + +### Route + +Model tracks consisting of links with capacities exceeding 1. Opposite links share the same resource ID. There is no +differentiation between moving block and fixed block. A mesoscopic link can only initiate or terminate at points where a +physical track change is feasible. + +### Station + +The station consists of one or several links, including the opposite links, with the same resource ID. The capacity is +larger than 1 and corresponds to the number of tracks. + +### Examples + +#### Section with a capacity of 2 + +```xml + + + + + 2 + + + + + 2 + + + +``` diff --git a/contribs/railsim/docs/train-specification.md b/contribs/railsim/docs/train-specification.md new file mode 100644 index 00000000000..41fcec36403 --- /dev/null +++ b/contribs/railsim/docs/train-specification.md @@ -0,0 +1,41 @@ +# Train-Specification + +## Introduction + +railsim supports the simulation of specific, train-related behavior, e.g. acceleration based on the total weight of a +train. In order to simulate this detailed behavior, additional attributes must be specified per train, i.e. per vehicle +type in MATSim. + +This document specifies these custom attributes. + +## Specification + +### TransitVehicle Attributes + +Default vehicle type attributes for length, maximum velocity and capacity. +Set network mode to rail. + +#### railsimAcceleration + +The vehicle-specific acceleration. Unit: meters per square-seconds \[m/s²] + +#### railsimDeceleration + +The vehicle-specific deceleration. Unit: meters per square-seconds \[m/s²] + +## Examples + +```xml + + + + 0.4 + 0.5 + + + + + + + +``` diff --git a/contribs/railsim/pom.xml b/contribs/railsim/pom.xml new file mode 100644 index 00000000000..345b4fd0cea --- /dev/null +++ b/contribs/railsim/pom.xml @@ -0,0 +1,28 @@ + + + + contrib + org.matsim + 16.0-SNAPSHOT + + 4.0.0 + ch.sbb.matsim.contrib + railsim + + + + org.assertj + assertj-core + test + + + + org.mockito + mockito-core + test + + + + diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/MapBasedDataContainerProvider.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/RailsimModule.java similarity index 55% rename from matsim/src/main/java/org/matsim/core/trafficmonitoring/MapBasedDataContainerProvider.java rename to contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/RailsimModule.java index 391c7cd60c4..9d25bc4a9a9 100644 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/MapBasedDataContainerProvider.java +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/RailsimModule.java @@ -1,10 +1,9 @@ /* *********************************************************************** * * project: org.matsim.* - * MapBasedDataContainerProvider.java * * * *********************************************************************** * * * - * copyright : (C) 2013 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -18,36 +17,30 @@ * * * *********************************************************************** */ -package org.matsim.core.trafficmonitoring; +package ch.sbb.matsim.contrib.railsim; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; +import ch.sbb.matsim.contrib.railsim.analysis.linkstates.RailsimLinkStateControlerListener; +import ch.sbb.matsim.contrib.railsim.analysis.trainstates.RailsimTrainStateControlerListener; +import ch.sbb.matsim.contrib.railsim.config.RailsimConfigGroup; +import ch.sbb.matsim.contrib.railsim.qsimengine.RailsimQSimModule; +import com.google.inject.Singleton; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.controler.AbstractModule; -import java.util.Map; +/** + * Railsim module installing all needed component. + */ +public class RailsimModule extends AbstractModule { -class MapBasedDataContainerProvider implements DataContainerProvider { - - private final Map, TravelTimeData> linkData; - private final TravelTimeDataFactory ttDataFactory; - - public MapBasedDataContainerProvider(Map, TravelTimeData> linkData, TravelTimeDataFactory ttDataFactory) { - this.linkData = linkData; - this.ttDataFactory = ttDataFactory; - } - - @Override - public TravelTimeData getTravelTimeData(final Id linkId, final boolean createIfMissing) { - TravelTimeData data = this.linkData.get(linkId); - if ((null == data) && createIfMissing) { - data = this.ttDataFactory.createTravelTimeData(linkId) ; - this.linkData.put(linkId, data); - } - return data; - } - @Override - public TravelTimeData getTravelTimeData(Link link, boolean createIfMissing) { - return this.getTravelTimeData(link.getId(), createIfMissing); + public void install() { + installQSimModule(new RailsimQSimModule()); + ConfigUtils.addOrGetModule(getConfig(), RailsimConfigGroup.class); + + bind(RailsimLinkStateControlerListener.class).in(Singleton.class); + addControlerListenerBinding().to(RailsimLinkStateControlerListener.class); + + bind(RailsimTrainStateControlerListener.class).in(Singleton.class); + addControlerListenerBinding().to(RailsimTrainStateControlerListener.class); } - } diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/RailsimUtils.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/RailsimUtils.java new file mode 100644 index 00000000000..6eff2e945f2 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/RailsimUtils.java @@ -0,0 +1,158 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim; + +import ch.sbb.matsim.contrib.railsim.config.RailsimConfigGroup; +import org.matsim.api.core.v01.network.Link; +import org.matsim.vehicles.VehicleType; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +/** + * Utility class for working with Railsim and its specific attributes. + * + * @author ikaddoura + * @author rakow + * @author munterfi + */ +public final class RailsimUtils { + + public static final String LINK_ATTRIBUTE_RESOURCE_ID = "railsimResourceId"; + public static final String LINK_ATTRIBUTE_CAPACITY = "railsimTrainCapacity"; + public static final String LINK_ATTRIBUTE_MINIMUM_TIME = "railsimMinimumTime"; + public static final String VEHICLE_ATTRIBUTE_ACCELERATION = "railsimAcceleration"; + public static final String VEHICLE_ATTRIBUTE_DECELERATION = "railsimDeceleration"; + + private RailsimUtils() { + } + + /** + * Round number to precision commonly used in Railsim. + */ + public static double round(double d) { + return BigDecimal.valueOf(d).setScale(3, RoundingMode.HALF_EVEN).doubleValue(); + } + + /** + * Return the train capacity for this link, if no link attribute is provided the default is 1. + */ + public static int getTrainCapacity(Link link) { + Object attr = link.getAttributes().getAttribute(LINK_ATTRIBUTE_CAPACITY); + return attr != null ? (int) attr : 1; + } + + /** + * Sets the train capacity for the link. + */ + public static void setTrainCapacity(Link link, int capacity) { + link.getAttributes().putAttribute(LINK_ATTRIBUTE_CAPACITY, capacity); + } + + /** + * Return the minimum time for the switch at the end of the link (toNode); if no link attribute is provided the default is 0. + */ + public static double getMinimumHeadwayTime(Link link) { + Object attr = link.getAttributes().getAttribute(LINK_ATTRIBUTE_MINIMUM_TIME); + return attr != null ? (double) attr : 0; + } + + /** + * Sets the minimum headway time after a link can be released. + */ + public static void setMinimumHeadwayTime(Link link, double time) { + link.getAttributes().putAttribute(LINK_ATTRIBUTE_MINIMUM_TIME, time); + } + + /** + * Resource id or null if there is none. + */ + public static String getResourceId(Link link) { + return (String) link.getAttributes().getAttribute(LINK_ATTRIBUTE_RESOURCE_ID); + } + + /** + * Sets the resource id for the link. + */ + public static void setResourceId(Link link, String resourceId) { + link.getAttributes().putAttribute(LINK_ATTRIBUTE_RESOURCE_ID, resourceId); + } + + /** + * Whether this link is an entry link applicable for re routing. + */ + public static boolean isEntryLink(Link link) { + return Boolean.TRUE.equals(link.getAttributes().getAttribute("railsimEntry")); + } + + /** + * Sets whether this link is an entry link applicable for re-routing. + */ + public static void setEntryLink(Link link, boolean isEntry) { + link.getAttributes().putAttribute("railsimEntry", isEntry); + } + + /** + * Exit link used for re routing. + */ + public static boolean isExitLink(Link link) { + return Boolean.TRUE.equals(link.getAttributes().getAttribute("railsimExit")); + } + + /** + * Sets whether this link is an exit link used for re-routing. + */ + public static void setExitLink(Link link, boolean isExit) { + link.getAttributes().putAttribute("railsimExit", isExit); + } + + /** + * Return the default deceleration time or the vehicle-specific value. + */ + public static double getTrainDeceleration(VehicleType vehicle, RailsimConfigGroup railsimConfigGroup) { + double deceleration = railsimConfigGroup.decelerationDefault; + Object attr = vehicle.getAttributes().getAttribute(VEHICLE_ATTRIBUTE_DECELERATION); + return attr != null ? (double) attr : deceleration; + } + + /** + * Sets the deceleration time for the vehicle type. + */ + public static void setTrainDeceleration(VehicleType vehicle, double deceleration) { + vehicle.getAttributes().putAttribute(VEHICLE_ATTRIBUTE_DECELERATION, deceleration); + } + + /** + * Return the default acceleration time or the vehicle-specific value. + */ + public static double getTrainAcceleration(VehicleType vehicle, RailsimConfigGroup railsimConfigGroup) { + double acceleration = railsimConfigGroup.accelerationDefault; + Object attr = vehicle.getAttributes().getAttribute(VEHICLE_ATTRIBUTE_ACCELERATION); + return attr != null ? (double) attr : acceleration; + } + + /** + * Sets the acceleration time for the vehicle type. + */ + public static void setTrainAcceleration(VehicleType vehicle, double acceleration) { + vehicle.getAttributes().putAttribute(VEHICLE_ATTRIBUTE_ACCELERATION, acceleration); + } + +} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/controler/RunControlerWW.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/RunRailsimExample.java similarity index 55% rename from contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/controler/RunControlerWW.java rename to contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/RunRailsimExample.java index 27c713ed684..e4f69dbb5b7 100644 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/controler/RunControlerWW.java +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/RunRailsimExample.java @@ -1,10 +1,9 @@ /* *********************************************************************** * * project: org.matsim.* - * ControlerWW.java * * * *********************************************************************** * * * - * copyright : (C) 2012 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -18,39 +17,44 @@ * * * *********************************************************************** */ -package org.matsim.contrib.eventsBasedPTRouter.controler; +package ch.sbb.matsim.contrib.railsim; -import org.matsim.contrib.eventsBasedPTRouter.TransitRouterEventsWLFactory; +import ch.sbb.matsim.contrib.railsim.qsimengine.RailsimQSimModule; +import org.matsim.api.core.v01.Scenario; 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.contrib.eventsBasedPTRouter.waitTimes.WaitTimeStuckCalculator; -import org.matsim.pt.router.TransitRouter; - /** - * A run Controler for a transit router that depends on the travel times and wait times - * - * @author sergioo + * Example script that shows how to use railsim included in this contrib. */ +public final class RunRailsimExample { -public class RunControlerWW { + private RunRailsimExample() { + } public static void main(String[] args) { - Config config = ConfigUtils.createConfig(); - ConfigUtils.loadConfig(config, args[0]); - final Controler controler = new Controler(ScenarioUtils.loadScenario(config)); - final WaitTimeStuckCalculator waitTimeCalculator = new WaitTimeStuckCalculator(controler.getScenario().getPopulation(), controler.getScenario().getTransitSchedule(), controler.getConfig(), controler.getEvents()); - controler.getEvents().addHandler(waitTimeCalculator); - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - bind(TransitRouter.class).toProvider(new TransitRouterEventsWLFactory(controler, waitTimeCalculator.get())); - } - }); + + if (args.length == 0) { + System.err.println("Path to config is required as first argument."); + System.exit(2); + } + + String configFilename = args[0]; + Config config = ConfigUtils.loadConfig(configFilename); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + + Scenario scenario = ScenarioUtils.loadScenario(config); + Controler controler = new Controler(scenario); + + controler.addOverridingModule(new RailsimModule()); + + // if you have other extensions that provide QSim components, call their configure-method here + controler.configureQSimComponents(components -> new RailsimQSimModule().configure(components)); + controler.run(); } - + } diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/PostProcessAnalysis.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/PostProcessAnalysis.java new file mode 100644 index 00000000000..aed580e018f --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/PostProcessAnalysis.java @@ -0,0 +1,81 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.analysis; + +import ch.sbb.matsim.contrib.railsim.analysis.linkstates.RailLinkStateAnalysis; +import ch.sbb.matsim.contrib.railsim.analysis.trainstates.TrainStateAnalysis; +import ch.sbb.matsim.contrib.railsim.eventmappers.RailsimLinkStateChangeEventMapper; +import ch.sbb.matsim.contrib.railsim.eventmappers.RailsimTrainStateEventMapper; +import ch.sbb.matsim.contrib.railsim.events.RailsimLinkStateChangeEvent; +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent; +import org.matsim.api.core.v01.Scenario; +import org.matsim.core.api.experimental.events.EventsManager; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.events.EventsUtils; +import org.matsim.core.events.MatsimEventsReader; +import org.matsim.core.network.io.MatsimNetworkReader; +import org.matsim.core.scenario.ScenarioUtils; + +/** + * Class to generate rail sim csv files from event file. + */ +public final class PostProcessAnalysis { + + private PostProcessAnalysis() { + } + + public static void main(String[] args) { + String eventsFilename; + String networkFilename = null; + if (args.length > 0) { + eventsFilename = args[0]; + } else { + System.err.println("Please provide events filename."); + System.exit(2); + return; + } + if (args.length > 1) { + networkFilename = args[1]; + } + + Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); + if (networkFilename != null) { + new MatsimNetworkReader(scenario.getNetwork()).readFile(networkFilename); + } + + RailLinkStateAnalysis linkStateAnalysis = new RailLinkStateAnalysis(); + TrainStateAnalysis trainStateAnalysis = new TrainStateAnalysis(); + + EventsManager events = EventsUtils.createEventsManager(); + events.addHandler(linkStateAnalysis); + events.addHandler(trainStateAnalysis); + events.initProcessing(); + + MatsimEventsReader reader = new MatsimEventsReader(events); + reader.addCustomEventMapper(RailsimLinkStateChangeEvent.EVENT_TYPE, new RailsimLinkStateChangeEventMapper()); + reader.addCustomEventMapper(RailsimTrainStateEvent.EVENT_TYPE, new RailsimTrainStateEventMapper()); + reader.readFile(eventsFilename); + + events.finishProcessing(); + + RailsimCsvWriter.writeLinkStatesCsv(linkStateAnalysis.getEvents(), "railsimLinkStates.csv"); + RailsimCsvWriter.writeTrainStatesCsv(trainStateAnalysis.getEvents(), scenario.getNetwork(), "railsimTrainStates.csv"); + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/RailsimCsvWriter.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/RailsimCsvWriter.java new file mode 100644 index 00000000000..61462ddebbd --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/RailsimCsvWriter.java @@ -0,0 +1,119 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.analysis; + +import ch.sbb.matsim.contrib.railsim.RailsimUtils; +import ch.sbb.matsim.contrib.railsim.events.RailsimLinkStateChangeEvent; +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.matsim.api.core.v01.Coord; +import org.matsim.api.core.v01.network.Link; +import org.matsim.api.core.v01.network.Network; +import org.matsim.core.utils.io.IOUtils; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.List; + +/** + * Helper class to write railsim related csv files. + */ +public final class RailsimCsvWriter { + + private RailsimCsvWriter() { + } + + /** + * Write {@link RailsimLinkStateChangeEvent} to a csv file. + */ + public static void writeLinkStatesCsv(List events, String filename) throws UncheckedIOException { + String[] header = {"link", "time", "state", "vehicle", "track"}; + + try (CSVPrinter csv = new CSVPrinter(IOUtils.getBufferedWriter(filename), CSVFormat.DEFAULT.builder().setHeader(header).build())) { + for (RailsimLinkStateChangeEvent event : events) { + csv.print(event.getLinkId().toString()); + csv.print(event.getTime()); + csv.print(event.getState().toString()); + csv.print(event.getVehicleId() != null ? event.getVehicleId().toString() : ""); + csv.print(event.getTrack()); + csv.println(); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + } + + /** + * Write {@link RailsimTrainStateEvent} to a csv file. + */ + public static void writeTrainStatesCsv(List events, Network network, String filename) throws UncheckedIOException { + String[] header = {"vehicle", "time", "acceleration", "speed", "targetSpeed", "headLink", "headPosition", "headX", "headY", "tailLink", "tailPosition", "tailX", "tailY"}; + + try (CSVPrinter csv = new CSVPrinter(IOUtils.getBufferedWriter(filename), CSVFormat.DEFAULT.builder().setHeader(header).build())) { + for (RailsimTrainStateEvent event : events) { + csv.print(event.getVehicleId().toString()); + csv.print(event.getExactTime()); + csv.print(event.getAcceleration()); + csv.print(RailsimUtils.round(event.getSpeed())); + csv.print(RailsimUtils.round(event.getTargetSpeed())); + + csv.print(event.getHeadLink().toString()); + csv.print(RailsimUtils.round(event.getHeadPosition())); + if (network != null) { + Link link = network.getLinks().get(event.getHeadLink()); + if (link != null) { + double fraction = event.getHeadPosition() / link.getLength(); + Coord from = link.getFromNode().getCoord(); + Coord to = link.getToNode().getCoord(); + csv.print(from.getX() + (to.getX() - from.getX()) * fraction); + csv.print(from.getY() + (to.getY() - from.getY()) * fraction); + } + } else { + csv.print(""); + csv.print(""); + } + + csv.print(event.getTailLink().toString()); + csv.print(RailsimUtils.round(event.getTailPosition())); + if (network != null) { + Link link = network.getLinks().get(event.getTailLink()); + if (link != null) { + double fraction = event.getTailPosition() / link.getLength(); + Coord from = link.getFromNode().getCoord(); + Coord to = link.getToNode().getCoord(); + csv.print(from.getX() + (to.getX() - from.getX()) * fraction); + csv.print(from.getY() + (to.getY() - from.getY()) * fraction); + } + } else { + csv.print(""); + csv.print(""); + } + + csv.println(); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + } + +} diff --git a/matsim/src/main/java/org/matsim/pt/router/FakeFacility.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/linkstates/RailLinkStateAnalysis.java similarity index 64% rename from matsim/src/main/java/org/matsim/pt/router/FakeFacility.java rename to contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/linkstates/RailLinkStateAnalysis.java index 00c2edade64..5f204dc9387 100644 --- a/matsim/src/main/java/org/matsim/pt/router/FakeFacility.java +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/linkstates/RailLinkStateAnalysis.java @@ -1,11 +1,9 @@ - /* *********************************************************************** * * project: org.matsim.* - * FakeFacility.java * * * *********************************************************************** * * * - * copyright : (C) 2019 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,29 +17,27 @@ * * * *********************************************************************** */ - package org.matsim.pt.router; +package ch.sbb.matsim.contrib.railsim.analysis.linkstates; -import java.util.Map; +import ch.sbb.matsim.contrib.railsim.eventhandlers.RailsimLinkStateChangeEventHandler; +import ch.sbb.matsim.contrib.railsim.events.RailsimLinkStateChangeEvent; -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.Id; -import org.matsim.facilities.Facility; +import java.util.ArrayList; +import java.util.List; -public final class FakeFacility implements Facility { - private Coord coord; - public FakeFacility( Coord coord ) { this.coord = coord ; } - @Override public Coord getCoord() { - return this.coord ; - } +/** + * Handler for {@link RailsimLinkStateChangeEvent}. + */ +public final class RailLinkStateAnalysis implements RailsimLinkStateChangeEventHandler { + + final List events = new ArrayList<>(1000); @Override - public Map getCustomAttributes() { - throw new RuntimeException("not implemented") ; + public void handleEvent(RailsimLinkStateChangeEvent event) { + this.events.add(event); } - @Override - public Id getLinkId() { - throw new RuntimeException("not implemented") ; + public List getEvents() { + return events; } - } diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/linkstates/RailsimLinkStateControlerListener.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/linkstates/RailsimLinkStateControlerListener.java new file mode 100644 index 00000000000..3c5d71264c3 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/linkstates/RailsimLinkStateControlerListener.java @@ -0,0 +1,61 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.analysis.linkstates; + +import ch.sbb.matsim.contrib.railsim.analysis.RailsimCsvWriter; +import com.google.inject.Inject; +import org.matsim.api.core.v01.Scenario; +import org.matsim.core.api.experimental.events.EventsManager; +import org.matsim.core.controler.OutputDirectoryHierarchy; +import org.matsim.core.controler.events.IterationEndsEvent; +import org.matsim.core.controler.events.IterationStartsEvent; +import org.matsim.core.controler.listener.IterationEndsListener; +import org.matsim.core.controler.listener.IterationStartsListener; + +/** + * Controler to automatically write rail sim analysis files. + */ +public final class RailsimLinkStateControlerListener implements IterationEndsListener, IterationStartsListener { + + private RailLinkStateAnalysis analysis; + private OutputDirectoryHierarchy controlerIO; + private final EventsManager eventsManager; + private final Scenario scenario; + + @Inject + RailsimLinkStateControlerListener(Scenario scenario, EventsManager eventsManager, OutputDirectoryHierarchy controlerIO) { + this.eventsManager = eventsManager; + this.controlerIO = controlerIO; + this.scenario = scenario; + this.analysis = new RailLinkStateAnalysis(); + } + + @Override + public void notifyIterationStarts(IterationStartsEvent event) { + this.eventsManager.addHandler(this.analysis); + } + + @Override + public void notifyIterationEnds(IterationEndsEvent event) { + String railLinkStatesCsvFilename = this.controlerIO.getIterationFilename(event.getIteration(), "railsimLinkStates.csv", this.scenario.getConfig().controller().getCompressionType()); + RailsimCsvWriter.writeLinkStatesCsv(this.analysis.events, railLinkStatesCsvFilename); + } + +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/trainstates/RailsimTrainStateControlerListener.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/trainstates/RailsimTrainStateControlerListener.java new file mode 100644 index 00000000000..60c39494e28 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/trainstates/RailsimTrainStateControlerListener.java @@ -0,0 +1,62 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.analysis.trainstates; + +import ch.sbb.matsim.contrib.railsim.analysis.RailsimCsvWriter; +import com.google.inject.Inject; +import org.matsim.api.core.v01.Scenario; +import org.matsim.core.api.experimental.events.EventsManager; +import org.matsim.core.controler.OutputDirectoryHierarchy; +import org.matsim.core.controler.events.IterationEndsEvent; +import org.matsim.core.controler.events.IterationStartsEvent; +import org.matsim.core.controler.listener.IterationEndsListener; +import org.matsim.core.controler.listener.IterationStartsListener; + + +/** + * Controler to write {@link ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent} csv files. + */ +public final class RailsimTrainStateControlerListener implements IterationEndsListener, IterationStartsListener { + + private TrainStateAnalysis analysis; + private OutputDirectoryHierarchy controlerIO; + private final EventsManager eventsManager; + private final Scenario scenario; + + @Inject + RailsimTrainStateControlerListener(Scenario scenario, EventsManager eventsManager, OutputDirectoryHierarchy controlerIO) { + this.eventsManager = eventsManager; + this.controlerIO = controlerIO; + this.scenario = scenario; + this.analysis = new TrainStateAnalysis(); + } + + @Override + public void notifyIterationStarts(IterationStartsEvent event) { + this.eventsManager.addHandler(this.analysis); + } + + @Override + public void notifyIterationEnds(IterationEndsEvent event) { + String railLinkStatesCsvFilename = this.controlerIO.getIterationFilename(event.getIteration(), "railsimTrainStates.csv", this.scenario.getConfig().controller().getCompressionType()); + RailsimCsvWriter.writeTrainStatesCsv(this.analysis.events, this.scenario.getNetwork(), railLinkStatesCsvFilename); + } + +} diff --git a/matsim/src/main/java/org/matsim/pt/router/InternalTransitPassengerRoute.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/trainstates/TrainStateAnalysis.java similarity index 66% rename from matsim/src/main/java/org/matsim/pt/router/InternalTransitPassengerRoute.java rename to contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/trainstates/TrainStateAnalysis.java index 61f04a3f20a..fcc7531ce43 100644 --- a/matsim/src/main/java/org/matsim/pt/router/InternalTransitPassengerRoute.java +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/analysis/trainstates/TrainStateAnalysis.java @@ -3,7 +3,7 @@ * * * *********************************************************************** * * * - * copyright : (C) 2015 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -17,36 +17,27 @@ * * * *********************************************************************** */ -package org.matsim.pt.router; +package ch.sbb.matsim.contrib.railsim.analysis.trainstates; +import ch.sbb.matsim.contrib.railsim.eventhandlers.RailsimTrainStateEventHandler; +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent; + +import java.util.ArrayList; import java.util.List; /** - * - * @author aneumann - * + * Handler collecting all {@link RailsimTrainStateEvent}s. */ -public class InternalTransitPassengerRoute { - - private final double cost; - private final List route; +public final class TrainStateAnalysis implements RailsimTrainStateEventHandler { - public InternalTransitPassengerRoute(double cost, List leastCostRoute) { - this.cost = cost; - this.route = leastCostRoute; - - } + final List events = new ArrayList<>(1000); - public double getTravelCost() { - return this.cost; - } - - public List getRoute() { - return this.route; + @Override + public void handleEvent(RailsimTrainStateEvent event) { + this.events.add(event); } - @Override - public String toString() { - return "Cost: " + this.cost + " via " + this.route; + public List getEvents() { + return events; } } diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/config/RailsimConfigGroup.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/config/RailsimConfigGroup.java new file mode 100644 index 00000000000..9599b04c915 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/config/RailsimConfigGroup.java @@ -0,0 +1,73 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.config; + +import ch.sbb.matsim.contrib.railsim.RailsimUtils; +import org.matsim.core.config.Config; +import org.matsim.core.config.ReflectiveConfigGroup; + +import java.util.Set; + +/** + * Config of the Railsim contrib. + */ +public final class RailsimConfigGroup extends ReflectiveConfigGroup { + + public static final String GROUP_NAME = "railsim"; + + @Parameter + @Comment("Comma separated set of modes that are handled by the railsim qsim engine in the simulation. Defaults to 'rail'.") + public String networkModes = "rail"; + + @Parameter + @Comment("Global acceleration in meters per second^2 which is used if there is no value provided in the vehicle attributes (" + RailsimUtils.VEHICLE_ATTRIBUTE_ACCELERATION + ");" + " used to compute the train velocity per link.") + public double accelerationDefault = 0.5; + + @Parameter + @Comment("Global deceleration in meters per second^2 which is used if there is no value provided in the vehicle attributes (" + RailsimUtils.VEHICLE_ATTRIBUTE_DECELERATION + ");" + " used to compute the reserved train path and the train velocity per link.") + public double decelerationDefault = 0.5; + + @Parameter + @Comment("Time interval in seconds a train has to wait until trying again to request a track reservation if the track was blocked by another train.") + public double pollInterval = 10; + + @Parameter + @Comment("Maximum time interval in seconds which is used to update the train position update events.") + public double updateInterval = 10.; + + public RailsimConfigGroup() { + super(GROUP_NAME); + } + + public Set getNetworkModes() { + return Set.of(networkModes.split(",")); + } + + @Override + protected void checkConsistency(Config config) { + super.checkConsistency(config); + for (String mode : getNetworkModes()) { + if (config.qsim().getMainModes().contains(mode)) { + throw new IllegalArgumentException(String.format("Railsim mode '%s' must not be a network mode in qsim.", mode)); + } + } + } + +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventhandlers/RailsimLinkStateChangeEventHandler.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventhandlers/RailsimLinkStateChangeEventHandler.java new file mode 100644 index 00000000000..7fd4ef9cfa4 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventhandlers/RailsimLinkStateChangeEventHandler.java @@ -0,0 +1,34 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.eventhandlers; + +import ch.sbb.matsim.contrib.railsim.events.RailsimLinkStateChangeEvent; +import org.matsim.core.events.handler.EventHandler; + +/** + * Handler for {@link RailsimLinkStateChangeEvent}. + */ +public interface RailsimLinkStateChangeEventHandler extends EventHandler { + + /** + * Process given event. + */ + void handleEvent(RailsimLinkStateChangeEvent event); +} diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataFactory.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventhandlers/RailsimTrainStateEventHandler.java similarity index 73% rename from matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataFactory.java rename to contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventhandlers/RailsimTrainStateEventHandler.java index fbe4aa0d726..5f4ae3179e6 100644 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataFactory.java +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventhandlers/RailsimTrainStateEventHandler.java @@ -1,10 +1,9 @@ /* *********************************************************************** * * project: org.matsim.* - * TravelTimeDataFactory.java * * * *********************************************************************** * * * - * copyright : (C) 2009 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -18,14 +17,18 @@ * * * *********************************************************************** */ -package org.matsim.core.trafficmonitoring; +package ch.sbb.matsim.contrib.railsim.eventhandlers; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; -import org.matsim.core.api.internal.MatsimFactory; +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent; +import org.matsim.core.events.handler.EventHandler; -interface TravelTimeDataFactory extends MatsimFactory { - - public TravelTimeData createTravelTimeData(final Id linkId); +/** + * Event handler for {@link RailsimTrainStateEvent}. + */ +public interface RailsimTrainStateEventHandler extends EventHandler { + /** + * Handle given event. + */ + void handleEvent(RailsimTrainStateEvent event); } diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataHashMapFactory.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventmappers/RailsimLinkStateChangeEventMapper.java similarity index 53% rename from matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataHashMapFactory.java rename to contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventmappers/RailsimLinkStateChangeEventMapper.java index a8689615970..97488e97e1d 100644 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataHashMapFactory.java +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventmappers/RailsimLinkStateChangeEventMapper.java @@ -1,10 +1,9 @@ /* *********************************************************************** * * project: org.matsim.* - * TravelTimeDataHashMapFactory.java * * * *********************************************************************** * * * - * copyright : (C) 2009 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -18,23 +17,36 @@ * * * *********************************************************************** */ -package org.matsim.core.trafficmonitoring; +package ch.sbb.matsim.contrib.railsim.eventmappers; +import ch.sbb.matsim.contrib.railsim.events.RailsimLinkStateChangeEvent; +import ch.sbb.matsim.contrib.railsim.qsimengine.TrackState; import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.GenericEvent; import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; +import org.matsim.core.events.MatsimEventsReader; +import org.matsim.vehicles.Vehicle; -class TravelTimeDataHashMapFactory implements TravelTimeDataFactory { - - private final Network network; - - public TravelTimeDataHashMapFactory(final Network network) { - this.network = network; - } - +/** + * Converter for railsim events. + */ +public class RailsimLinkStateChangeEventMapper implements MatsimEventsReader.CustomEventMapper { @Override - public TravelTimeData createTravelTimeData(Id linkId) { - return new TravelTimeDataHashMap(this.network.getLinks().get(linkId)); + public RailsimLinkStateChangeEvent apply(GenericEvent event) { + var attributes = event.getAttributes(); + return new RailsimLinkStateChangeEvent( + event.getTime(), + asId(attributes.get(RailsimLinkStateChangeEvent.ATTRIBUTE_LINK), Link.class), + asId(attributes.get(RailsimLinkStateChangeEvent.ATTRIBUTE_VEHICLE), Vehicle.class), + TrackState.valueOf(attributes.get(RailsimLinkStateChangeEvent.ATTRIBUTE_STATE)), + Integer.parseInt(attributes.get(RailsimLinkStateChangeEvent.ATTRIBUTE_TRACK)) + ); } + private static Id asId(String value, Class idClass) { + if (value == null) { + return null; + } + return Id.create(value, idClass); + } } diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventmappers/RailsimTrainStateEventMapper.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventmappers/RailsimTrainStateEventMapper.java new file mode 100644 index 00000000000..1c118f15856 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/eventmappers/RailsimTrainStateEventMapper.java @@ -0,0 +1,56 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.eventmappers; + +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.GenericEvent; +import org.matsim.api.core.v01.network.Link; +import org.matsim.core.events.MatsimEventsReader; +import org.matsim.vehicles.Vehicle; + +/** + * Convert for {@link RailsimTrainStateEvent}. + */ +public class RailsimTrainStateEventMapper implements MatsimEventsReader.CustomEventMapper { + @Override + public RailsimTrainStateEvent apply(GenericEvent event) { + var attributes = event.getAttributes(); + return new RailsimTrainStateEvent( + event.getTime(), + Double.parseDouble(attributes.get(RailsimTrainStateEvent.ATTRIBUTE_EXACT_TIME)), + asId(attributes.get(RailsimTrainStateEvent.ATTRIBUTE_VEHICLE), Vehicle.class), + asId(attributes.get(RailsimTrainStateEvent.ATTRIBUTE_HEAD_LINK), Link.class), + Double.parseDouble(attributes.get(RailsimTrainStateEvent.ATTRIBUTE_HEAD_POSITION)), + asId(attributes.get(RailsimTrainStateEvent.ATTRIBUTE_TAIL_LINK), Link.class), + Double.parseDouble(attributes.get(RailsimTrainStateEvent.ATTRIBUTE_TAIL_POSITION)), + Double.parseDouble(attributes.get(RailsimTrainStateEvent.ATTRIBUTE_SPEED)), + Double.parseDouble(attributes.get(RailsimTrainStateEvent.ATTRIBUTE_ACCELERATION)), + Double.parseDouble(attributes.get(RailsimTrainStateEvent.ATTRIBUTE_TARGET_SPEED)) + ); + } + + private static Id asId(String value, Class idClass) { + if (value == null) { + return null; + } + return Id.create(value, idClass); + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimDetourEvent.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimDetourEvent.java new file mode 100644 index 00000000000..f5a84b0e8ff --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimDetourEvent.java @@ -0,0 +1,80 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.events; + +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.Event; +import org.matsim.api.core.v01.events.HasVehicleId; +import org.matsim.api.core.v01.network.Link; +import org.matsim.pt.transitSchedule.api.TransitStopFacility; +import org.matsim.vehicles.Vehicle; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Event that occurs when a train was re-routed. + */ +public class RailsimDetourEvent extends Event implements HasVehicleId { + + public static final String EVENT_TYPE = "railsimDetourEvent"; + + private final Id vehicleId; + private final Id entry; + private final Id exit; + private final List> detour; + private final Id newStop; + + public RailsimDetourEvent(double time, Id vehicleId, Id entry, Id exit, List> detour, + Id newStop) { + super(time); + this.vehicleId = vehicleId; + this.entry = entry; + this.exit = exit; + this.detour = detour; + this.newStop = newStop; + } + + @Override + public String getEventType() { + return EVENT_TYPE; + } + + @Override + public Id getVehicleId() { + return vehicleId; + } + + + @Override + public Map getAttributes() { + Map attributes = super.getAttributes(); + + attributes.put(HasVehicleId.ATTRIBUTE_VEHICLE, vehicleId.toString()); + attributes.put("entry", entry.toString()); + attributes.put("exit", exit.toString()); + attributes.put("detour", detour.stream().map(Object::toString).collect(Collectors.joining(","))); + attributes.put("newStop", Objects.toString(newStop)); + + return attributes; + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimLinkStateChangeEvent.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimLinkStateChangeEvent.java new file mode 100644 index 00000000000..55a73fdf6d7 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimLinkStateChangeEvent.java @@ -0,0 +1,87 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.events; + +import ch.sbb.matsim.contrib.railsim.qsimengine.TrackState; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.Event; +import org.matsim.api.core.v01.events.HasLinkId; +import org.matsim.api.core.v01.events.HasVehicleId; +import org.matsim.api.core.v01.network.Link; +import org.matsim.vehicles.Vehicle; + +import java.util.Map; + +/** + * Event thrown when the {@link ch.sbb.matsim.contrib.railsim.qsimengine.TrackState} of a {@link Link} changes. + */ +public final class RailsimLinkStateChangeEvent extends Event implements HasLinkId, HasVehicleId { + + public static final String EVENT_TYPE = "railsimLinkStateChangeEvent"; + + public static final String ATTRIBUTE_STATE = "state"; + public static final String ATTRIBUTE_TRACK = "track"; + + private final Id linkId; + private final Id vehicleId; + private final TrackState state; + private final int track; + + public RailsimLinkStateChangeEvent(double time, Id linkId, Id vehicleId, TrackState state, int track) { + super(time); + this.linkId = linkId; + this.vehicleId = vehicleId; + this.state = state; + this.track = track; + } + + @Override + public String getEventType() { + return EVENT_TYPE; + } + + @Override + public Id getLinkId() { + return linkId; + } + + @Override + public Id getVehicleId() { + return this.vehicleId; + } + + public TrackState getState() { + return state; + } + + public int getTrack() { + return track; + } + + @Override + public Map getAttributes() { + Map attr = super.getAttributes(); + attr.put(ATTRIBUTE_LINK, this.linkId.toString()); + attr.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); + attr.put(ATTRIBUTE_STATE, this.state.toString()); + attr.put(ATTRIBUTE_TRACK, String.valueOf(track)); + return attr; + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimTrainLeavesLinkEvent.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimTrainLeavesLinkEvent.java new file mode 100644 index 00000000000..eb2d4038f81 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimTrainLeavesLinkEvent.java @@ -0,0 +1,69 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.events; + +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.Event; +import org.matsim.api.core.v01.events.HasLinkId; +import org.matsim.api.core.v01.events.HasVehicleId; +import org.matsim.api.core.v01.network.Link; +import org.matsim.vehicles.Vehicle; + +import java.util.Map; + +/** + * Event thrown when the very end of a train left a link. + */ +public class RailsimTrainLeavesLinkEvent extends Event implements HasLinkId, HasVehicleId { + + public static final String EVENT_TYPE = "railsimTrainLeavesLinkEvent"; + + private final Id linkId; + private final Id vehicleId; + + public RailsimTrainLeavesLinkEvent(double time, Id vehicleId, Id linkId) { + super(time); + this.vehicleId = vehicleId; + this.linkId = linkId; + } + + @Override + public String getEventType() { + return EVENT_TYPE; + } + + @Override + public Id getLinkId() { + return linkId; + } + + @Override + public Id getVehicleId() { + return vehicleId; + } + + @Override + public Map getAttributes() { + Map attr = super.getAttributes(); + attr.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); + attr.put(ATTRIBUTE_LINK, this.linkId.toString()); + return attr; + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimTrainStateEvent.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimTrainStateEvent.java new file mode 100644 index 00000000000..7fa89816c1b --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/events/RailsimTrainStateEvent.java @@ -0,0 +1,132 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.events; + +import ch.sbb.matsim.contrib.railsim.RailsimUtils; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.Event; +import org.matsim.api.core.v01.events.HasVehicleId; +import org.matsim.api.core.v01.network.Link; +import org.matsim.vehicles.Vehicle; + +import java.util.Map; + +/** + * Event for currents train position. + */ +public final class RailsimTrainStateEvent extends Event implements HasVehicleId { + + public static final String EVENT_TYPE = "railsimTrainStateEvent"; + + public static final String ATTRIBUTE_EXACT_TIME = "exactTime"; + public static final String ATTRIBUTE_HEAD_LINK = "headLink"; + public static final String ATTRIBUTE_HEAD_POSITION = "headPosition"; + public static final String ATTRIBUTE_TAIL_LINK = "tailLink"; + public static final String ATTRIBUTE_TAIL_POSITION = "tailPosition"; + public static final String ATTRIBUTE_SPEED = "speed"; + public static final String ATTRIBUTE_ACCELERATION = "acceleration"; + public static final String ATTRIBUTE_TARGET_SPEED = "targetSpeed"; + + /** + * Exact time with resolution of 0.001s. + */ + private final double exactTime; + private final Id vehicleId; + private final Id headLink; + private final double headPosition; + private final Id tailLink; + private final double tailPosition; + private final double speed; + private final double acceleration; + private final double targetSpeed; + + public RailsimTrainStateEvent(double time, double exactTime, Id vehicleId, + Id headLink, double headPosition, + Id tailLink, double tailPosition, + double speed, double acceleration, double targetSpeed) { + super(time); + this.exactTime = RailsimUtils.round(exactTime); + this.vehicleId = vehicleId; + this.headLink = headLink; + this.headPosition = headPosition; + this.tailLink = tailLink; + this.tailPosition = tailPosition; + this.speed = speed; + this.acceleration = acceleration; + this.targetSpeed = targetSpeed; + } + + @Override + public String getEventType() { + return EVENT_TYPE; + } + + @Override + public Id getVehicleId() { + return vehicleId; + } + + public double getExactTime() { + return exactTime; + } + + public double getHeadPosition() { + return headPosition; + } + + public double getTailPosition() { + return tailPosition; + } + + public double getSpeed() { + return speed; + } + + public double getTargetSpeed() { + return this.targetSpeed; + } + + public double getAcceleration() { + return this.acceleration; + } + + public Id getHeadLink() { + return this.headLink; + } + + public Id getTailLink() { + return this.tailLink; + } + + @Override + public Map getAttributes() { + Map attr = super.getAttributes(); + attr.put(ATTRIBUTE_EXACT_TIME, String.valueOf(exactTime)); + attr.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); + attr.put(ATTRIBUTE_HEAD_LINK, String.valueOf(headLink)); + attr.put(ATTRIBUTE_HEAD_POSITION, Double.toString(headPosition)); + attr.put(ATTRIBUTE_TAIL_LINK, String.valueOf(tailLink)); + attr.put(ATTRIBUTE_TAIL_POSITION, Double.toString(tailPosition)); + attr.put(ATTRIBUTE_SPEED, Double.toString(speed)); + attr.put(ATTRIBUTE_ACCELERATION, Double.toString(acceleration)); + attr.put(ATTRIBUTE_TARGET_SPEED, Double.toString(targetSpeed)); + return attr; + } +} diff --git a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeData.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/FuzzyUtils.java similarity index 52% rename from contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeData.java rename to contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/FuzzyUtils.java index 645a1a39efd..3e27651c038 100644 --- a/contribs/eventsBasedPTRouter/src/main/java/org/matsim/contrib/eventsBasedPTRouter/waitTimes/WaitTimeData.java +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/FuzzyUtils.java @@ -1,39 +1,67 @@ -/* *********************************************************************** * - * project: org.matsim.* - * WaitTimeCalculator.java - * * - * *********************************************************************** * - * * - * 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.eventsBasedPTRouter.waitTimes; - -import java.io.Serializable; - -/** - * Structure for saving waiting times - * - * @author sergioo - */ - -public interface WaitTimeData extends Serializable { - - //Methods - void resetWaitTimes(); - void addWaitTime(final int timeSlot, final double waitTime); - double getWaitTime(final int timeSlot); - int getNumData(final int timeSlot); - -} +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +/** + * Util class for fuzzy comparisons. + */ +final class FuzzyUtils { + + private static final double EPSILON = 1E-5; + + private FuzzyUtils() { + } + + /** + * Returns true if two doubles are approximately equal. + */ + public static boolean equals(double a, double b) { + return a == b || Math.abs(a - b) < EPSILON; + } + + /** + * Returns true if the first double is approximately greater than the second. + */ + public static boolean greaterEqualThan(double a, double b) { + return equals(a, b) || a - b > EPSILON; + } + + /** + * Returns true if the first double is certainly greater than the second. + */ + public static boolean greaterThan(double a, double b) { + return a - b > EPSILON; + } + + /** + * Returns true if the first double is approximately less than the second. + */ + public static boolean lessEqualThan(double a, double b) { + return equals(a, b) || b - a > EPSILON; + } + + /** + * Returns true if the first double is approximately less than the second. + */ + public static boolean lessThan(double a, double b) { + return b - a > EPSILON; + } + +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailLink.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailLink.java new file mode 100644 index 00000000000..d59ae3801a2 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailLink.java @@ -0,0 +1,185 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.RailsimUtils; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.HasLinkId; +import org.matsim.api.core.v01.network.Link; +import org.matsim.core.mobsim.framework.MobsimDriverAgent; + +import javax.annotation.Nullable; +import java.util.Arrays; +import java.util.Objects; + +/** + * Rail links which can has multiple tracks and corresponds to exactly one link. + */ +public final class RailLink implements HasLinkId { + + private final Id id; + + /** + * States per track. + */ + private final TrackState[] state; + + private final boolean isEntryLink; + private final boolean isExitLink; + + /** + * Drivers of each blocked track. + */ + private final MobsimDriverAgent[] blocked; + + final double length; + final double freeSpeed; + final double minimumHeadwayTime; + + /** + * ID of the resource this link belongs to. + */ + @Nullable + final Id resource; + + public RailLink(Link link) { + id = link.getId(); + state = new TrackState[RailsimUtils.getTrainCapacity(link)]; + Arrays.fill(state, TrackState.FREE); + blocked = new MobsimDriverAgent[state.length]; + length = link.getLength(); + freeSpeed = link.getFreespeed(); + minimumHeadwayTime = RailsimUtils.getMinimumHeadwayTime(link); + String resourceId = RailsimUtils.getResourceId(link); + resource = resourceId != null ? Id.create(resourceId, RailResource.class) : null; + isEntryLink = RailsimUtils.isEntryLink(link); + isExitLink = RailsimUtils.isExitLink(link); + } + + @Override + public Id getLinkId() { + return id; + } + + @Nullable + public Id getResourceId() { + return resource; + } + + /** + * Number of tracks on this link. + */ + public int getNumberOfTracks() { + return state.length; + } + + /** + * Returns the allowed freespeed, depending on the context, which is given via driver. + */ + public double getAllowedFreespeed(MobsimDriverAgent driver) { + return Math.min(freeSpeed, driver.getVehicle().getVehicle().getType().getMaximumVelocity()); + } + + /** + * Check if driver has already reserved this link. + */ + public boolean isBlockedBy(MobsimDriverAgent driver) { + for (MobsimDriverAgent reservation : blocked) { + if (reservation == driver) + return true; + } + return false; + } + + /** + * Whether at least one track is free. + */ + boolean hasFreeTrack() { + for (TrackState trackState : state) { + if (trackState == TrackState.FREE) + return true; + } + return false; + } + + /** + * Block a track that was previously reserved. + */ + int blockTrack(MobsimDriverAgent driver) { + for (int i = 0; i < state.length; i++) { + if (state[i] == TrackState.FREE) { + blocked[i] = driver; + state[i] = TrackState.BLOCKED; + return i; + } + } + throw new IllegalStateException("No track was free."); + } + + /** + * Release a non-free track to be free again. + */ + int releaseTrack(MobsimDriverAgent driver) { + for (int i = 0; i < state.length; i++) { + if (blocked[i] == driver) { + state[i] = TrackState.FREE; + blocked[i] = null; + return i; + } + } + throw new AssertionError("Driver " + driver + " has not reserved the track."); + } + + + /** + * Entry link of a station relevant for re-routing. + */ + public boolean isEntryLink() { + return isEntryLink; + } + + /** + * Exit link of a station for re-routing. + */ + public boolean isExitLink() { + return isExitLink; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + RailLink link = (RailLink) o; + return Objects.equals(id, link.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + @Override + public String toString() { + return "RailLink{" + + "id=" + id + + ", resource=" + resource + + '}'; + } +} diff --git a/matsim/src/main/java/org/matsim/core/utils/io/UncheckedIOException.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailResource.java similarity index 59% rename from matsim/src/main/java/org/matsim/core/utils/io/UncheckedIOException.java rename to contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailResource.java index f3cca1e6e74..ded83867f7d 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/UncheckedIOException.java +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailResource.java @@ -1,11 +1,9 @@ - /* *********************************************************************** * * project: org.matsim.* - * UncheckedIOException.java * * * *********************************************************************** * * * - * copyright : (C) 2019 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,25 +17,46 @@ * * * *********************************************************************** */ - package org.matsim.core.utils.io; +package ch.sbb.matsim.contrib.railsim.qsimengine; + +import org.matsim.core.mobsim.framework.MobsimDriverAgent; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + /** - * A simple (unchecked) exception class to typically wrap IOExceptions. - * - * @author mrieser + * A resource representing multiple {@link RailLink}. */ -public class UncheckedIOException extends RuntimeException { - private static final long serialVersionUID = 6186620063027481864L; +public class RailResource { - public UncheckedIOException(final String message, final Throwable cause) { - super(message, cause); - } + /** + * Links belonging to this resource. + */ + final List links; - public UncheckedIOException(final Throwable cause) { - super(cause); + /** + * Agents holding this resource exclusively. + */ + final Set reservations; + + /** + * Maximum number of reservations. + */ + int capacity; + + public RailResource(List links) { + this.links = links; + this.reservations = new HashSet<>(); + this.capacity = links.stream().mapToInt(RailLink::getNumberOfTracks).min().orElseThrow(); } - - public UncheckedIOException(final String message) { - super(message); + + /** + * Whether an agent is able to block this resource. + */ + boolean hasCapacity() { + return reservations.size() < capacity; } + } diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailResourceManager.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailResourceManager.java new file mode 100644 index 00000000000..6f00f25b9d6 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailResourceManager.java @@ -0,0 +1,200 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.config.RailsimConfigGroup; +import ch.sbb.matsim.contrib.railsim.events.RailsimLinkStateChangeEvent; +import jakarta.inject.Inject; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.IdMap; +import org.matsim.api.core.v01.network.Link; +import org.matsim.api.core.v01.network.Network; +import org.matsim.core.api.experimental.events.EventsManager; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.mobsim.framework.MobsimDriverAgent; +import org.matsim.core.mobsim.qsim.QSim; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Class responsible for managing and blocking resources and segments of links. + */ +public final class RailResourceManager { + + private final EventsManager eventsManager; + + /** + * Rail links. + */ + private final Map, RailLink> links; + + private final Map, RailResource> resources; + + @Inject + public RailResourceManager(QSim qsim) { + this(qsim.getEventsManager(), ConfigUtils.addOrGetModule(qsim.getScenario().getConfig(), RailsimConfigGroup.class), qsim.getScenario().getNetwork()); + } + + /** + * Construct resources from network. + */ + public RailResourceManager(EventsManager eventsManager, RailsimConfigGroup config, Network network) { + this.eventsManager = eventsManager; + this.links = new IdMap<>(Link.class, network.getLinks().size()); + + Set modes = config.getNetworkModes(); + for (Map.Entry, ? extends Link> e : network.getLinks().entrySet()) { + if (e.getValue().getAllowedModes().stream().anyMatch(modes::contains)) + this.links.put(e.getKey(), new RailLink(e.getValue())); + } + + Map, List> collect = links.values().stream() + .filter(l -> l.resource != null) + .collect(Collectors.groupingBy(l -> l.resource, Collectors.toList()) + ); + + resources = new IdMap<>(RailResource.class, collect.size()); + for (Map.Entry, List> e : collect.entrySet()) { + resources.put(e.getKey(), new RailResource(e.getValue())); + } + } + + /** + * Get single link that belongs to an id. + */ + public RailLink getLink(Id id) { + return links.get(id); + } + + /** + * Return the resource for a given id. + */ + public RailResource getResource(Id id) { + if (id == null) return null; + return resources.get(id); + } + + /** + * Try to block a resource for a specific driver. + * + * @return true if the resource is now blocked or was blocked for this driver already. + */ + private boolean tryBlockResource(RailResource resource, MobsimDriverAgent driver) { + + if (resource.reservations.contains(driver)) + return true; + + if (resource.hasCapacity()) { + resource.reservations.add(driver); + return true; + } + + return false; + } + + /** + * Try to release a resource, but only if none of the links are blocked anymore by this driver. + * + * @return whether driver is still blocking this resource. + */ + private boolean tryReleaseResource(RailResource resource, MobsimDriverAgent driver) { + + if (resource.links.stream().noneMatch(l -> l.isBlockedBy(driver))) { + resource.reservations.remove(driver); + return true; + } + + return false; + } + + /** + * Try to block a track and the underlying resource and return whether it was successful. + */ + public boolean tryBlockTrack(double time, MobsimDriverAgent driver, RailLink link) { + + if (link.isBlockedBy(driver)) + return true; + + Id resourceId = link.getResourceId(); + if (resourceId != null) { + + RailResource resource = getResource(resourceId); + + // resource is required + if (!tryBlockResource(resource, driver)) { + return false; + } + } + + if (link.hasFreeTrack()) { + int track = link.blockTrack(driver); + eventsManager.processEvent(new RailsimLinkStateChangeEvent(Math.ceil(time), link.getLinkId(), + driver.getVehicle().getId(), TrackState.BLOCKED, track)); + + return true; + } + + return false; + } + + /** + * Checks whether a link or underlying resource has remaining capacity. + */ + public boolean hasCapacity(Id link) { + + RailLink l = getLink(link); + + if (!l.hasFreeTrack()) + return false; + + RailResource res = getResource(l.getResourceId()); + if (res != null) { + return res.hasCapacity(); + } + + return true; + } + + /** + * Whether a driver already reserved a link or would be able to reserve it. + */ + public boolean isBlockedBy(RailLink link, MobsimDriverAgent driver) { + // If a link is blocked, the resource must be blocked as well + return link.isBlockedBy(driver); + } + + /** + * Release a non-free track to be free again. + */ + public void releaseTrack(double time, MobsimDriverAgent driver, RailLink link) { + int track = link.releaseTrack(driver); + eventsManager.processEvent(new RailsimLinkStateChangeEvent(Math.ceil(time), link.getLinkId(), driver.getVehicle().getId(), + TrackState.FREE, track)); + + // Release held resources + if (link.getResourceId() != null) { + tryReleaseResource(getResource(link.getResourceId()), driver); + } + + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimCalc.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimCalc.java new file mode 100644 index 00000000000..62437d0bfa7 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimCalc.java @@ -0,0 +1,284 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import java.util.ArrayList; +import java.util.List; + +/** + * Utility class holding static calculation methods related to state (updates). + */ +final class RailsimCalc { + + private RailsimCalc() { + } + + /** + * Calculate traveled distance given initial speed and constant acceleration. + */ + static double calcTraveledDist(double speed, double elapsedTime, double acceleration) { + return speed * elapsedTime + (elapsedTime * elapsedTime * acceleration / 2); + } + + /** + * Inverse of {@link #calcTraveledDist(double, double, double)}, solves for distance, returns needed time. + */ + static double solveTraveledDist(double speed, double dist, double acceleration) { + if (acceleration == 0) + return dist / speed; + + return (Math.sqrt(2 * acceleration * dist + speed * speed) - speed) / acceleration; + } + + /** + * Calculate time needed to advance distance {@code dist}. Depending on acceleration and max speed. + */ + static double calcRequiredTime(TrainState state, double dist) { + + if (FuzzyUtils.equals(dist, 0)) + return 0; + + if (state.acceleration == 0) + return state.speed == 0 ? Double.POSITIVE_INFINITY : dist / state.speed; + + if (state.acceleration > 0) { + + double accelTime = (state.targetSpeed - state.speed) / state.acceleration; + + double d = calcTraveledDist(state.speed, accelTime, state.acceleration); + + // The required distance is reached during acceleration + if (d > dist) { + return solveTraveledDist(state.speed, dist, state.acceleration); + + } else + // Time for accel plus remaining dist at max speed + return accelTime + (dist - d) / state.targetSpeed; + + } else { + + double decelTime = -(state.speed - state.targetSpeed) / state.acceleration; + + // max distance that can be reached + double max = calcTraveledDist(state.speed, decelTime, state.acceleration); + + if (FuzzyUtils.equals(dist, max)) { + return decelTime; + } else if (dist <= max) { + return solveTraveledDist(state.speed, dist, state.acceleration); + } else + return Double.POSITIVE_INFINITY; + } + } + + /** + * Calculate the maximum speed that can be reached under the condition that speed must be reduced to {@code allowedSpeed} + * again after traveled {@code dist}. + */ + static SpeedTarget calcTargetSpeed(double dist, double acceleration, double deceleration, + double currentSpeed, double allowedSpeed, double finalSpeed) { + + // Calculation is simplified if target is the same + if (FuzzyUtils.equals(allowedSpeed, finalSpeed)) { + return new SpeedTarget(finalSpeed, Double.POSITIVE_INFINITY); + } + + double timeDecel = (allowedSpeed - finalSpeed) / deceleration; + double distDecel = calcTraveledDist(allowedSpeed, timeDecel, -deceleration); + + // No further acceleration needed + if (FuzzyUtils.equals(currentSpeed, allowedSpeed)) { + double decelDist = dist - distDecel; + + // Start to stop now + if (FuzzyUtils.equals(decelDist, 0)) { + return new SpeedTarget(finalSpeed, 0); + } + + // Decelerate later + return new SpeedTarget(allowedSpeed, decelDist); + } + + + assert FuzzyUtils.greaterEqualThan(allowedSpeed, currentSpeed) : "Current speed must be lower than allowed"; + assert FuzzyUtils.greaterEqualThan(allowedSpeed, finalSpeed) : "Final speed must be smaller than target"; + + double timeAccel = (allowedSpeed - currentSpeed) / acceleration; + double distAccel = calcTraveledDist(currentSpeed, timeAccel, acceleration); + + // there is enough distance to accelerate to the target speed + if (FuzzyUtils.lessThan(distAccel + distDecel, dist)) { + return new SpeedTarget(allowedSpeed, dist - distDecel); + } + + double nom = 2 * acceleration * deceleration * dist + + acceleration * finalSpeed * finalSpeed + + deceleration * currentSpeed * currentSpeed; + + double v = Math.sqrt(nom / (acceleration + deceleration)); + + timeDecel = (v - finalSpeed) / deceleration; + distDecel = calcTraveledDist(v, timeDecel, -deceleration); + + return new SpeedTarget(v, dist - distDecel); + } + + + /** + * Calculate the deceleration needed to arrive at {@code targetSpeed} exactly after {@code dist}. + * + * @return negative acceleration, always a negative number. + */ + static double calcTargetDecel(double dist, double targetSpeed, double currentSpeed) { + return -(currentSpeed * currentSpeed - targetSpeed * targetSpeed) / (2 * dist); + } + + /** + * Calculate the maximum speed that can be achieved if trains want to stop after dist. + */ + static double calcTargetSpeedForStop(double dist, double acceleration, double deceleration, double currentSpeed) { + + double nom = 2 * acceleration * deceleration * dist + + deceleration * currentSpeed * currentSpeed; + + return Math.sqrt(nom / (acceleration + deceleration)); + } + + /** + * Calculate when the reservation function should be triggered. + * Should return {@link Double#POSITIVE_INFINITY} if this distance is far in the future and can be checked at later point. + * + * @param state current train state + * @param currentLink the link where the train head is on + * @return travel distance after which reservations should be updated. + */ + static double nextLinkReservation(TrainState state, RailLink currentLink) { + + // on way to pt stop, no need to reserve anymore + if (state.isStop(currentLink.getLinkId()) && FuzzyUtils.lessThan(state.headPosition, currentLink.length)) + return Double.POSITIVE_INFINITY; + + double assumedSpeed = calcPossibleMaxSpeed(state); + + // time needed for full stop + double stopTime = assumedSpeed / state.train.deceleration(); + + assert stopTime > 0 : "Stop time can not be negative"; + + // safety distance + double safety = RailsimCalc.calcTraveledDist(assumedSpeed, stopTime, -state.train.deceleration()); + + int idx = state.routeIdx; + double dist = currentLink.length - state.headPosition; + + RailLink nextLink = null; + // need to check beyond safety distance + while (FuzzyUtils.lessEqualThan(dist, safety * 2) && idx < state.route.size()) { + nextLink = state.route.get(idx++); + + if (!nextLink.isBlockedBy(state.driver)) + return dist - safety; + + // No reservation beyond pt stop + if (state.isStop(nextLink.getLinkId())) + break; + + dist += nextLink.length; + } + + // No reservation needed after the end + if (idx == state.route.size() || (nextLink != null && state.isStop(nextLink.getLinkId()))) + return Double.POSITIVE_INFINITY; + + return dist - safety; + } + + /** + * Links that need to be blocked or otherwise stop needs to be initiated. + */ + static List calcLinksToBlock(TrainState state, RailLink currentLink) { + + List result = new ArrayList<>(); + + // Currently driving to pt stop + if (state.isStop(currentLink.getLinkId()) && FuzzyUtils.lessThan(state.headPosition, currentLink.length)) + return result; + + double assumedSpeed = calcPossibleMaxSpeed(state); + double stopTime = assumedSpeed / state.train.deceleration(); + + // safety distance + double safety = RailsimCalc.calcTraveledDist(assumedSpeed, stopTime, -state.train.deceleration()); + + int idx = state.routeIdx; + + // dist to next + double dist = currentLink.length - state.headPosition; + + while (FuzzyUtils.lessEqualThan(dist, safety) && idx < state.route.size()) { + RailLink nextLink = state.route.get(idx++); + result.add(nextLink); + dist += nextLink.length; + + // Beyond pt stop links don't need to be reserved + if (state.isStop(nextLink.getLinkId())) + break; + } + + return result; + } + + /** + * Whether re-routing should be tried. + * + * @param upcoming the upcoming links the train tried to block. + */ + static boolean considerReRouting(List upcoming, RailLink currentLink) { + return currentLink.isEntryLink() || upcoming.stream().anyMatch(RailLink::isEntryLink); + } + + /** + * Maximum speed of the next upcoming links. + */ + private static double calcPossibleMaxSpeed(TrainState state) { + + double safety = RailsimCalc.calcTraveledDist(state.train.maxVelocity(), state.train.maxVelocity() / state.train.deceleration(), -state.train.deceleration()); + double maxSpeed = state.allowedMaxSpeed; + + double dist = 0; + for (int i = 0; i < state.route.size() && dist < safety; i++) { + RailLink link = state.route.get(i); + maxSpeed = Math.max(maxSpeed, link.getAllowedFreespeed(state.driver)); + + dist += link.length; + } + + return maxSpeed; + } + + record SpeedTarget(double targetSpeed, double decelDist) implements Comparable { + + @Override + public int compareTo(SpeedTarget o) { + return Double.compare(decelDist, o.decelDist); + } + } + +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimDriverAgentFactory.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimDriverAgentFactory.java new file mode 100644 index 00000000000..6a68c0ffd59 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimDriverAgentFactory.java @@ -0,0 +1,71 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.config.RailsimConfigGroup; +import com.google.inject.Inject; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.Scenario; +import org.matsim.api.core.v01.TransportMode; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.mobsim.qsim.InternalInterface; +import org.matsim.core.mobsim.qsim.pt.AbstractTransitDriverAgent; +import org.matsim.core.mobsim.qsim.pt.TransitDriverAgentFactory; +import org.matsim.core.mobsim.qsim.pt.TransitDriverAgentImpl; +import org.matsim.core.mobsim.qsim.pt.TransitStopAgentTracker; +import org.matsim.pt.Umlauf; +import org.matsim.pt.transitSchedule.api.TransitStopArea; +import org.matsim.pt.transitSchedule.api.TransitStopFacility; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Factory to create specific drivers for the rail engine. + */ +public class RailsimDriverAgentFactory implements TransitDriverAgentFactory { + + private final Set modes; + private final Map, List> stopAreas; + + @Inject + public RailsimDriverAgentFactory(Config config, Scenario scenario) { + this.modes = ConfigUtils.addOrGetModule(config, RailsimConfigGroup.class).getNetworkModes(); + + this.stopAreas = scenario.getTransitSchedule().getFacilities().values().stream() + .filter(t -> t.getStopAreaId() != null) + .collect(Collectors.groupingBy(TransitStopFacility::getStopAreaId, Collectors.toList())); + } + + @Override + public AbstractTransitDriverAgent createTransitDriver(Umlauf umlauf, InternalInterface internalInterface, TransitStopAgentTracker transitStopAgentTracker) { + + String mode = umlauf.getUmlaufStuecke().get(0).getRoute().getTransportMode(); + + if (this.modes.contains(mode)) { + return new RailsimTransitDriverAgent(stopAreas, umlauf, mode, transitStopAgentTracker, internalInterface); + } + + return new TransitDriverAgentImpl(umlauf, TransportMode.car, transitStopAgentTracker, internalInterface); + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimEngine.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimEngine.java new file mode 100644 index 00000000000..6573ed1b47e --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimEngine.java @@ -0,0 +1,764 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.stream.Collectors; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.Event; +import org.matsim.api.core.v01.events.LinkEnterEvent; +import org.matsim.api.core.v01.events.LinkLeaveEvent; +import org.matsim.api.core.v01.events.PersonEntersVehicleEvent; +import org.matsim.api.core.v01.events.VehicleEntersTrafficEvent; +import org.matsim.api.core.v01.network.Link; +import org.matsim.core.api.experimental.events.EventsManager; +import org.matsim.core.mobsim.framework.MobsimDriverAgent; +import org.matsim.core.mobsim.framework.Steppable; +import org.matsim.core.population.routes.NetworkRoute; +import org.matsim.pt.transitSchedule.api.TransitStopFacility; +import org.matsim.vehicles.VehicleType; + +import ch.sbb.matsim.contrib.railsim.config.RailsimConfigGroup; +import ch.sbb.matsim.contrib.railsim.events.RailsimDetourEvent; +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainLeavesLinkEvent; +import ch.sbb.matsim.contrib.railsim.qsimengine.disposition.TrainDisposition; + +/** + * Engine to simulate train movement. + */ +final class RailsimEngine implements Steppable { + + private static final Logger log = LogManager.getLogger(RailsimEngine.class); + private final EventsManager eventsManager; + private final RailsimConfigGroup config; + private final List activeTrains = new ArrayList<>(); + private final Queue updateQueue = new PriorityQueue<>(); + private final RailResourceManager resources; + private final TrainDisposition disposition; + + RailsimEngine(EventsManager eventsManager, RailsimConfigGroup config, RailResourceManager resources, TrainDisposition disposition) { + this.eventsManager = eventsManager; + this.config = config; + this.resources = resources; + this.disposition = disposition; + } + + @Override + public void doSimStep(double time) { + + UpdateEvent update = updateQueue.peek(); + + // Update loop over all required state updates + while (update != null && update.plannedTime <= time) { + updateQueue.poll(); + + // Use planned time here, otherwise there will be inaccuracies + updateState(update.plannedTime, update); + + // Add the update event again + if (update.type != UpdateEvent.Type.IDLE) { + updateQueue.add(update); + } + + update = updateQueue.peek(); + } + + if (time % config.updateInterval == 0.) { + updateAllPositions(time); + } + } + + /** + * Update the current state of all trains, even if no update would be needed. + */ + public void updateAllStates(double time) { + + // Process all waiting events first + doSimStep(time); + + // Potential duplication of position update events here, if time matches updateInterval + updateAllPositions(time); + } + + /** + * Handle the departure of a train. + */ + public boolean handleDeparture(double now, MobsimDriverAgent agent, Id linkId, NetworkRoute route) { + + log.debug("Train {} is departing at {}", agent.getVehicle(), now); + + // Queue the update event + // NO events can be generated here, or temporal ordering is not guaranteed + // (departures are handled before event queue is processed) + + List list = route.getLinkIds().stream().map(resources::getLink).collect(Collectors.toList()); + list.add(0, resources.getLink(linkId)); + list.add(resources.getLink(route.getEndLinkId())); + + VehicleType type = agent.getVehicle().getVehicle().getType(); + TrainState state = new TrainState(agent, new TrainInfo(type, config), now, linkId, list); + + state.train.checkConsistency(); + + activeTrains.add(state); + + disposition.onDeparture(now, state.driver, state.route); + + updateQueue.add(new UpdateEvent(state, UpdateEvent.Type.DEPARTURE)); + + return true; + } + + private void updateAllPositions(double time) { + for (TrainState train : activeTrains) { + if (train.timestamp < time) + updateState(time, new UpdateEvent(train, UpdateEvent.Type.POSITION)); + } + } + + private void createEvent(Event event) { + // Because of the 1s update interval, events need to be rounded to the current simulation step + event.setTime(Math.ceil(event.getTime())); + this.eventsManager.processEvent(event); + } + + private void updateState(double time, UpdateEvent event) { + + // Do different updates depending on the type + switch (event.type) { + case DEPARTURE -> updateDeparture(time, event); + case POSITION -> { + updatePosition(time, event); + decideNextUpdate(event); + } + case SPEED_CHANGE -> updateSpeed(time, event); + case ENTER_LINK -> enterLink(time, event); + case LEAVE_LINK -> leaveLink(time, event); + case BLOCK_TRACK -> blockTrack(time, event); + case WAIT_FOR_RESERVATION -> checkTrackReservation(time, event); + case UNBLOCK_LINK -> { + unblockTrack(time, event.state, event.unblockLink); + // event will be removed + event.type = UpdateEvent.Type.IDLE; + } + default -> throw new IllegalStateException("Unhandled update type " + event.type); + } + } + + private void updateSpeed(double time, UpdateEvent event) { + + TrainState state = event.state; + + updatePosition(time, event); + + decideTargetSpeed(event, state); + + createEvent(state.asEvent(time)); + + decideNextUpdate(event); + } + + private void blockTrack(double time, UpdateEvent event) { + + TrainState state = event.state; + + updatePosition(time, event); + + if (!blockLinkTracks(time, state)) { + + decideTargetSpeed(event, state); + + event.checkReservation = time + config.pollInterval; + decideNextUpdate(event); + + } else { + event.checkReservation = -1; + decideNextUpdate(event); + } + } + + private void checkTrackReservation(double time, UpdateEvent event) { + + TrainState state = event.state; + + // train might be at the end of route already + RailLink nextLink = state.isRouteAtEnd() ? null : state.route.get(state.routeIdx); + + boolean allBlocked = blockLinkTracks(time, state); + + // Driver can advance if the next link is already free + if (allBlocked || (nextLink != null && nextLink.isBlockedBy(state.driver))) { + + if (allBlocked) + event.checkReservation = -1; + else { + event.checkReservation = time + config.pollInterval; + } + + // Train already waits at the end of previous link + if (event.waitingForLink) { + + enterLink(time, event); + event.waitingForLink = false; + + } else { + + updatePosition(time, event); + decideTargetSpeed(event, state); + decideNextUpdate(event); + + } + + } else { + + event.checkReservation = time + config.pollInterval; + + // If train is already standing still and waiting, there is no update needed. + if (event.waitingForLink) { + event.plannedTime = time + config.pollInterval; + } else { + decideNextUpdate(event); + } + } + } + + private void updateDeparture(double time, UpdateEvent event) { + + TrainState state = event.state; + state.timestamp = time; + + state.allowedMaxSpeed = retrieveAllowedMaxSpeed(state); + + RailLink firstLink = resources.getLink(state.headLink); + + state.headPosition = firstLink.length; + state.tailPosition = firstLink.length - state.train.length(); + + // reserve links and start if first one is free + if (blockLinkTracks(time, state) || resources.isBlockedBy(firstLink, state.driver)) { + + createEvent(new PersonEntersVehicleEvent(time, state.driver.getId(), state.driver.getVehicle().getId())); + createEvent(new VehicleEntersTrafficEvent(time, state.driver.getId(), + state.headLink, state.driver.getVehicle().getId(), state.driver.getMode(), 1.0)); + + state.timestamp = time; + + double stopTime = 0; + if (state.isStop(state.headLink)) { + stopTime = handleTransitStop(time, state); + } + + // Train departs at the very end of the first link + state.routeIdx = 1; + + createEvent(state.asEvent(time)); + + if (stopTime <= 0) { + // Call enter link logic immediately + enterLink(time, event); + } else { + event.plannedTime = time + stopTime; + event.type = UpdateEvent.Type.ENTER_LINK; + } + + } else { + // vehicle will wait and call departure again + event.plannedTime += config.pollInterval; + } + } + + /** + * Reserve links in advance as necessary. + */ + private boolean blockLinkTracks(double time, TrainState state) { + + List links = RailsimCalc.calcLinksToBlock(state, resources.getLink(state.headLink)); + + if (links.isEmpty()) + return true; + + if (state.pt != null && RailsimCalc.considerReRouting(links, resources.getLink(state.headLink))) { + + int start = -1; + int end = -1; + RailLink entry = null; + RailLink exit = null; + + for (int i = Math.max(0, state.routeIdx - 1); i < state.route.size(); i++) { + RailLink l = state.route.get(i); + + if (l.isEntryLink()) { + entry = l; + start = i; + } else if (start > -1 && l.isBlockedBy(state.driver)) { + // check if any link beyond entry is already blocked + // if that is the case re-route is not possible anymore + break; + } else if (start > -1 && l.isExitLink()) { + exit = l; + end = i; + break; + } + } + + // there might be no exit link if this is the end of the route + // exit will be set to null if re-route is too late + // network could be wrong as well, but hard to verify + if (exit != null) { + + // check if this route is different + List subRoute = state.route.subList(start + 1, end); + + List detour = disposition.requestRoute(time, state.pt, subRoute, entry, exit); + + if (detour != null && !subRoute.equals(detour)) { + + TransitStopFacility newStop = state.pt.addDetour(subRoute, detour); + + subRoute.clear(); + subRoute.addAll(detour); + + if (newStop != null) { + state.nextStop = newStop; + } + + createEvent(new RailsimDetourEvent( + time, state.driver.getVehicle().getId(), + entry.getLinkId(), exit.getLinkId(), + detour.stream().map(RailLink::getLinkId).toList(), + newStop != null ? newStop.getId() : null + )); + + // Block links again using the updated route + links = RailsimCalc.calcLinksToBlock(state, resources.getLink(state.headLink)); + + } + } + } + + List blocked = disposition.blockRailSegment(time, state.driver, links); + + // Only continue successfully if all requested link have been blocked + return links.size() == blocked.size(); + } + + private void enterLink(double time, UpdateEvent event) { + + TrainState state = event.state; + + updatePosition(time, event); + + // current head link is the pt stop, which means the train is at the end of the link when this is called + if (!event.waitingForLink && state.isStop(state.headLink)) { + + double stopTime = handleTransitStop(time, state); + + assert stopTime >= 0 : "Stop time must be positive"; + assert FuzzyUtils.equals(state.speed, 0) : "Speed must be 0 at pt stop, but was " + state.speed; + + // Same event is re-scheduled after stopping, + event.plannedTime = time + stopTime; + + return; + } + + // Arrival at destination + if (!event.waitingForLink && state.isRouteAtEnd()) { + + assert FuzzyUtils.equals(state.speed, 0) : "Speed must be 0 at end, but was " + state.speed; + + // Free all reservations + for (RailLink link : state.route) { + if (link.isBlockedBy(state.driver)) { + disposition.unblockRailLink(time, state.driver, link); + } + } + + state.driver.notifyArrivalOnLinkByNonNetworkMode(state.headLink); + state.driver.endLegAndComputeNextState(Math.ceil(time)); + + activeTrains.remove(state); + + event.type = UpdateEvent.Type.IDLE; + return; + } + + // Train stopped and reserves next links + if (FuzzyUtils.equals(state.speed, 0) && !blockLinkTracks(time, state)) { + + RailLink currentLink = state.route.get(state.routeIdx); + // If this linked is blocked the driver can continue + if (!currentLink.isBlockedBy(state.driver)) { + event.waitingForLink = true; + event.type = UpdateEvent.Type.WAIT_FOR_RESERVATION; + event.plannedTime = time + config.pollInterval; + return; + } + } + + // On route departure the head link is null + createEvent(new LinkLeaveEvent(time, state.driver.getVehicle().getId(), state.headLink)); + + // Get link and increment + state.headPosition = 0; + state.headLink = state.route.get(state.routeIdx++).getLinkId(); + + state.driver.notifyMoveOverNode(state.headLink); + createEvent(new LinkEnterEvent(time, state.driver.getVehicle().getId(), state.headLink)); + + RailLink link = resources.getLink(state.headLink); + + assert link.isBlockedBy(state.driver) : "Link has to be blocked by driver when entered"; + + decideTargetSpeed(event, state); + + createEvent(state.asEvent(time)); + + decideNextUpdate(event); + } + + private void leaveLink(double time, UpdateEvent event) { + + TrainState state = event.state; + + RailLink nextTailLink = null; + // Find the next link in the route + for (int i = state.routeIdx; i >= 1; i--) { + if (state.route.get(i - 1).getLinkId().equals(state.tailLink)) { + nextTailLink = state.route.get(i); + } + } + + Objects.requireNonNull(nextTailLink, "Could not find next link in route"); + + updatePosition(time, event); + + createEvent(new RailsimTrainLeavesLinkEvent(time, state.driver.getVehicle().getId(), state.tailLink)); + + RailLink tailLink = resources.getLink(state.tailLink); + + state.tailLink = nextTailLink.getLinkId(); + state.tailPosition = 0; + + decideTargetSpeed(event, state); + + decideNextUpdate(event); + + if (tailLink.minimumHeadwayTime == 0) + unblockTrack(time, state, tailLink); + else + updateQueue.add(new UpdateEvent(state, tailLink, time)); + } + + /** + * Unblocks a link. + */ + private void unblockTrack(double time, TrainState state, RailLink unblockLink) { + disposition.unblockRailLink(time, state.driver, unblockLink); + } + + /** + * Update position within a link and decides on next update. + */ + private void updatePosition(double time, UpdateEvent event) { + + TrainState state = event.state; + + double elapsed = time - state.timestamp; + + if (elapsed == 0) + return; + + double accelTime = (state.targetSpeed - state.speed) / state.acceleration; + + double dist; + if (state.acceleration == 0) { + dist = state.speed * elapsed; + + } else if (accelTime < elapsed) { + + // Travelled distance under constant acceleration + dist = RailsimCalc.calcTraveledDist(state.speed, accelTime, state.acceleration); + + // Remaining time at constant speed + if (state.acceleration > 0) + dist += RailsimCalc.calcTraveledDist(state.targetSpeed, elapsed - accelTime, 0); + + // Target speed was reached + state.speed = state.targetSpeed; + state.acceleration = 0; + + } else { + + // Acceleration was constant the whole time + dist = RailsimCalc.calcTraveledDist(state.speed, elapsed, state.acceleration); + state.speed = state.speed + elapsed * state.acceleration; + + if (FuzzyUtils.equals(state.speed, state.targetSpeed)) { + state.speed = state.targetSpeed; + state.acceleration = 0; + } + + } + + assert FuzzyUtils.greaterEqualThan(dist, 0) : "Travel distance must be positive, but was" + dist; + + state.headPosition += dist; + state.tailPosition += dist; + + if (Double.isFinite(state.targetDecelDist)) { + state.targetDecelDist -= dist; + } + + // When trains are put into the network their tail may be longer than the current link + // this assertion may not hold depending on the network, should possibly be removed + assert state.routeIdx <= 2 || FuzzyUtils.greaterEqualThan(state.tailPosition, 0) : "Illegal state update. Tail position should not be negative"; + + assert FuzzyUtils.lessEqualThan(state.headPosition, resources.getLink(state.headLink).length) : "Illegal state update. Head position must be smaller than link length"; + assert FuzzyUtils.greaterEqualThan(state.headPosition, 0) : "Head position must be positive"; + assert FuzzyUtils.lessEqualThan(state.speed, state.allowedMaxSpeed) : "Speed must be less equal than the allowed speed"; + + state.timestamp = time; + + // Only emit events on certain occasions + if (event.type == UpdateEvent.Type.ENTER_LINK || event.type == UpdateEvent.Type.LEAVE_LINK || event.type == UpdateEvent.Type.POSITION || event.type == UpdateEvent.Type.SPEED_CHANGE) + createEvent(state.asEvent(time)); + } + + /** + * Handle transit stop and update the state. + * + * @return stop time + */ + private double handleTransitStop(double time, TrainState state) { + + assert state.pt != null : "Pt driver must be present"; + + // Time needs to be rounded to current sim step + double stopTime = state.pt.handleTransitStop(state.nextStop, Math.ceil(time)); + state.nextStop = state.pt.getNextTransitStop(); + + return stopTime; + } + + /** + * Decide which update is the earliest and needs to be the next. + */ + private void decideNextUpdate(UpdateEvent event) { + + TrainState state = event.state; + RailLink currentLink = resources.getLink(state.headLink); + + // (1) max speed reached + double accelDist = Double.POSITIVE_INFINITY; + if (state.acceleration > 0 && FuzzyUtils.greaterThan(state.targetSpeed, state.speed)) { + accelDist = RailsimCalc.calcTraveledDist(state.speed, (state.targetSpeed - state.speed) / state.acceleration, state.acceleration); + } + + // (2) start deceleration + double decelDist = state.targetDecelDist; + + assert FuzzyUtils.greaterEqualThan(decelDist, 0) : "Deceleration distance must be larger than 0, but was " + decelDist; + + // (3) next link needs reservation + double reserveDist = Double.POSITIVE_INFINITY; + if (!state.isRouteAtEnd() && !event.isAwaitingReservation()) { + reserveDist = RailsimCalc.nextLinkReservation(state, currentLink); + + if (reserveDist < 0) + reserveDist = 0; + + // Outside of block track the reserve distance is always greater 0 + // infinite loops would occur otherwise + if (!(event.type != UpdateEvent.Type.BLOCK_TRACK || FuzzyUtils.greaterThan(reserveDist, 0))) { + // There are here for debugging + List tmp = RailsimCalc.calcLinksToBlock(state, currentLink); + double r = RailsimCalc.nextLinkReservation(state, currentLink); + + throw new AssertionError("Reserve distance must be positive, but was " + r); + } + } + + // (4) tail link changes + double tailDist = resources.getLink(state.tailLink).length - state.tailPosition; + + // (5) head link changes + double headDist = currentLink.length - state.headPosition; + + assert FuzzyUtils.greaterEqualThan(tailDist, 0) : "Tail distance must be positive"; + assert FuzzyUtils.greaterEqualThan(headDist, 0) : "Head distance must be positive"; + + // Find the earliest required update + + double dist; + if (reserveDist <= accelDist && reserveDist <= decelDist && reserveDist <= tailDist && reserveDist <= headDist) { + dist = reserveDist; + event.type = UpdateEvent.Type.BLOCK_TRACK; + } else if (accelDist <= decelDist && accelDist <= reserveDist && accelDist <= tailDist && accelDist <= headDist) { + dist = accelDist; + event.type = UpdateEvent.Type.SPEED_CHANGE; + } else if (decelDist <= accelDist && decelDist <= reserveDist && decelDist <= tailDist && decelDist <= headDist) { + dist = decelDist; + event.type = UpdateEvent.Type.SPEED_CHANGE; + } else if (tailDist <= decelDist && tailDist <= reserveDist && tailDist <= headDist) { + dist = tailDist; + event.type = UpdateEvent.Type.LEAVE_LINK; + } else { + dist = headDist; + event.type = UpdateEvent.Type.ENTER_LINK; + } + + assert FuzzyUtils.greaterEqualThan(dist, 0) : "Distance for next update must be positive"; + + // dist is the minimum of all supplied distances + event.plannedTime = state.timestamp + RailsimCalc.calcRequiredTime(state, dist); + + // There could be old reservations events that need to be checked first + if (event.isAwaitingReservation() && event.checkReservation < state.timestamp) { + event.checkReservation = state.timestamp; + } + + // insert reservation event if necessary + if (event.isAwaitingReservation() && event.plannedTime > event.checkReservation) { + + event.type = UpdateEvent.Type.WAIT_FOR_RESERVATION; + event.plannedTime = event.checkReservation; + } + + assert Double.isFinite(event.plannedTime) : "Planned update time must be finite, but was " + event.plannedTime; + assert event.plannedTime >= state.timestamp : "Planned time must be after current time"; + + } + + /** + * Calculates possible target speed, consequential acceleration depending on current state. + */ + private void decideTargetSpeed(UpdateEvent event, TrainState state) { + + // Distance to next link + RailLink currentLink = resources.getLink(state.headLink); + + double dist = currentLink.length - state.headPosition; + state.allowedMaxSpeed = retrieveAllowedMaxSpeed(state); + + // Lookahead window + double window = RailsimCalc.calcTraveledDist(state.allowedMaxSpeed, state.allowedMaxSpeed / state.train.deceleration(), + -state.train.deceleration()) + currentLink.length; + + double minAllowed = state.allowedMaxSpeed; + + state.targetSpeed = state.allowedMaxSpeed; + state.targetDecelDist = Double.POSITIVE_INFINITY; + + for (int i = state.routeIdx; i <= state.route.size(); i++) { + + RailLink link; + double allowed; + if (i == state.route.size()) { + link = null; + allowed = 0; + } else { + link = state.route.get(i); + + // If the previous link is a transit stop the speed needs to be 0 at the next link + // train stops at the very end of a link + if (i > 0 && state.isStop(state.route.get(i - 1).getLinkId())) + allowed = 0; + else if (!resources.isBlockedBy(link, state.driver)) + allowed = 0; + else + allowed = link.getAllowedFreespeed(state.driver); + } + + // Only need to consider if speed is lower than the allowed speed + if (!FuzzyUtils.equals(dist, 0) && allowed <= minAllowed) { + RailsimCalc.SpeedTarget target = RailsimCalc.calcTargetSpeed(dist, state.train.acceleration(), state.train.deceleration(), + state.speed, state.allowedMaxSpeed, Math.min(state.allowedMaxSpeed, allowed)); + + assert FuzzyUtils.greaterEqualThan(target.decelDist(), 0) : "Decel dist must be greater than 0, or stopping is not possible"; + + if (FuzzyUtils.equals(target.decelDist(), 0)) { + + // Need to decelerate now + state.targetSpeed = allowed; + state.targetDecelDist = Double.POSITIVE_INFINITY; + break; + } else if (target.decelDist() < state.targetDecelDist && target.targetSpeed() <= state.targetSpeed) { + + // Decelerate later + state.targetSpeed = target.targetSpeed(); + state.targetDecelDist = target.decelDist(); + + } else if (target.targetSpeed() > state.targetSpeed && !Double.isFinite(state.targetDecelDist)) { + // Acceleration is required + state.targetSpeed = target.targetSpeed(); + state.targetDecelDist = target.decelDist(); + } + } + + if (link != null) + dist += link.length; + + if (dist >= window) + break; + + minAllowed = allowed; + } + + // Calc accel depending on target + if (FuzzyUtils.equals(state.speed, state.targetSpeed)) { + state.acceleration = 0; + } else if (FuzzyUtils.lessThan(state.speed, state.targetSpeed)) { + state.acceleration = state.train.acceleration(); + } else { + state.acceleration = -state.train.deceleration(); + } + + assert FuzzyUtils.equals(state.targetSpeed, state.speed) || state.acceleration != 0 : "Acceleration must be set if target speed is different than current"; + assert FuzzyUtils.greaterThan(state.targetDecelDist, 0) : "Target decel must be greater than 0 after updating"; + + } + + /** + * Allowed speed for the train. + */ + private double retrieveAllowedMaxSpeed(TrainState state) { + + double maxSpeed = resources.getLink(state.headLink).getAllowedFreespeed(state.driver); + + for (int i = state.routeIdx - 1; i >= 0; i--) { + RailLink link = state.route.get(i); + maxSpeed = Math.min(maxSpeed, link.getAllowedFreespeed(state.driver)); + if (link.getLinkId().equals(state.tailLink)) { + break; + } + } + + return maxSpeed; + } + +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimQSimEngine.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimQSimEngine.java new file mode 100644 index 00000000000..88ee0b22cbc --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimQSimEngine.java @@ -0,0 +1,123 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.config.RailsimConfigGroup; +import ch.sbb.matsim.contrib.railsim.qsimengine.disposition.TrainDisposition; +import com.google.inject.Inject; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.network.Link; +import org.matsim.api.core.v01.population.Leg; +import org.matsim.api.core.v01.population.PlanElement; +import org.matsim.api.core.v01.population.Route; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.mobsim.framework.MobsimAgent; +import org.matsim.core.mobsim.framework.MobsimDriverAgent; +import org.matsim.core.mobsim.framework.PlanAgent; +import org.matsim.core.mobsim.qsim.InternalInterface; +import org.matsim.core.mobsim.qsim.QSim; +import org.matsim.core.mobsim.qsim.interfaces.DepartureHandler; +import org.matsim.core.mobsim.qsim.interfaces.MobsimEngine; +import org.matsim.core.mobsim.qsim.interfaces.NetsimLink; +import org.matsim.core.mobsim.qsim.pt.TransitStopAgentTracker; +import org.matsim.core.mobsim.qsim.qnetsimengine.QLinkI; +import org.matsim.core.population.routes.NetworkRoute; + +import java.util.Set; + +/** + * QSim Engine to integrate microscopically simulated train movement. + */ +public class RailsimQSimEngine implements DepartureHandler, MobsimEngine { + + private final QSim qsim; + private final RailsimConfigGroup config; + private final RailResourceManager res; + private final TrainDisposition disposition; + private final Set modes; + private final TransitStopAgentTracker agentTracker; + private InternalInterface internalInterface; + + private RailsimEngine engine; + + @Inject + public RailsimQSimEngine(QSim qsim, RailResourceManager res, TrainDisposition disposition, TransitStopAgentTracker agentTracker) { + this.qsim = qsim; + this.config = ConfigUtils.addOrGetModule(qsim.getScenario().getConfig(), RailsimConfigGroup.class); + this.res = res; + this.disposition = disposition; + this.modes = config.getNetworkModes(); + this.agentTracker = agentTracker; + } + + @Override + public void setInternalInterface(InternalInterface internalInterface) { + this.internalInterface = internalInterface; + } + + @Override + public void onPrepareSim() { + engine = new RailsimEngine(qsim.getEventsManager(), config, res, disposition); + } + + @Override + public void afterSim() { + + } + + @Override + public void doSimStep(double time) { + engine.doSimStep(time); + } + + @Override + public boolean handleDeparture(double now, MobsimAgent agent, Id linkId) { + + if (!modes.contains(agent.getMode())) return false; + + NetsimLink link = qsim.getNetsimNetwork().getNetsimLink(linkId); + + // Lots of implicit type checking here to get the required information from the agent + if (!(agent instanceof MobsimDriverAgent driver)) { + throw new IllegalStateException("Departing agent " + agent.getId() + " is not a DriverAgent"); + } + if (!(agent instanceof PlanAgent plan)) { + throw new IllegalStateException("Agent " + agent + " is not of type PlanAgent and therefore incompatible."); + } + PlanElement el = plan.getCurrentPlanElement(); + if (!(el instanceof Leg leg)) { + throw new IllegalStateException("Plan element of agent " + agent + " is not a leg with a route."); + } + Route route = leg.getRoute(); + if (!(route instanceof NetworkRoute networkRoute)) { + throw new IllegalStateException("A network route is required for agent " + agent + "."); + } + + // Vehicles were inserted into the qsim as parked + // Remove them as soon as we depart + if (link instanceof QLinkI qLink) { + qLink.unregisterAdditionalAgentOnLink(agent.getId()); + qLink.removeParkedVehicle(driver.getVehicle().getId()); + } + + return engine.handleDeparture(now, driver, linkId, networkRoute); + } + +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimQSimModule.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimQSimModule.java new file mode 100644 index 00000000000..77e4e04133b --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimQSimModule.java @@ -0,0 +1,58 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.qsimengine.disposition.SimpleDisposition; +import ch.sbb.matsim.contrib.railsim.qsimengine.disposition.TrainDisposition; +import ch.sbb.matsim.contrib.railsim.qsimengine.router.TrainRouter; +import com.google.inject.multibindings.OptionalBinder; +import org.matsim.core.mobsim.qsim.AbstractQSimModule; +import org.matsim.core.mobsim.qsim.components.QSimComponentsConfig; +import org.matsim.core.mobsim.qsim.components.QSimComponentsConfigurator; +import org.matsim.core.mobsim.qsim.pt.TransitDriverAgentFactory; + +/** + * Module to install railsim functionality. + */ +public class RailsimQSimModule extends AbstractQSimModule implements QSimComponentsConfigurator { + + public static final String COMPONENT_NAME = "Railsim"; + + @Override + public void configure(QSimComponentsConfig components) { + components.addNamedComponent(COMPONENT_NAME); + } + + @Override + protected void configureQSim() { + bind(RailsimQSimEngine.class).asEagerSingleton(); + + bind(TrainRouter.class).asEagerSingleton(); + bind(RailResourceManager.class).asEagerSingleton(); + + // This Interface might be replaced with other implementations + bind(TrainDisposition.class).to(SimpleDisposition.class).asEagerSingleton(); + + addQSimComponentBinding(COMPONENT_NAME).to(RailsimQSimEngine.class); + + OptionalBinder.newOptionalBinder(binder(), TransitDriverAgentFactory.class) + .setBinding().to(RailsimDriverAgentFactory.class); + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimTransitDriverAgent.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimTransitDriverAgent.java new file mode 100644 index 00000000000..be2ebcb6ffb --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimTransitDriverAgent.java @@ -0,0 +1,117 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.matsim.api.core.v01.Id; +import org.matsim.core.mobsim.qsim.InternalInterface; +import org.matsim.core.mobsim.qsim.pt.TransitDriverAgentImpl; +import org.matsim.core.mobsim.qsim.pt.TransitStopAgentTracker; +import org.matsim.pt.Umlauf; +import org.matsim.pt.transitSchedule.api.TransitStopArea; +import org.matsim.pt.transitSchedule.api.TransitStopFacility; + +import java.util.List; +import java.util.Map; + +/** + * Railsim specific transit driver that can be re-routed. + */ +public final class RailsimTransitDriverAgent extends TransitDriverAgentImpl { + + private static final Logger log = LogManager.getLogger(RailsimTransitDriverAgent.class); + + /** + * Contains the original stop if it was overwritten by a detour. + */ + private TransitStopFacility overwrittenStop; + + private final Map, List> stopAreas; + + public RailsimTransitDriverAgent(Map, List> stopAreas, Umlauf umlauf, String transportMode, TransitStopAgentTracker thisAgentTracker, InternalInterface internalInterface) { + super(umlauf, transportMode, thisAgentTracker, internalInterface); + this.stopAreas = stopAreas; + } + + /** + * Add a detour to this driver schedule. + * + * @return next transit stop, if it needs to be changed. + */ + public TransitStopFacility addDetour(List original, List detour) { + + TransitStopFacility nextStop = getNextTransitStop(); + + // Adjust the link index so that it fits to the new size + // the original route inside this agent is not updated because it is currently not necessary + // after the detour the link index should be consistent again + setNextLinkIndex(getNextLinkIndex() + (original.size() - detour.size())); + + if (nextStop != null) { + + Id areaId = nextStop.getStopAreaId(); + + boolean adjust = false; + for (RailLink link : original) { + if (nextStop.getLinkId().equals(link.getLinkId())) { + adjust = true; + break; + } + } + + // pt stop needs to be remapped + if (adjust) { + + List inArea = stopAreas.get(areaId); + + for (TransitStopFacility stop : inArea) { + for (RailLink d : detour) { + + if (stop.getLinkId().equals(d.getLinkId())) { + this.overwrittenStop = nextStop; + return stop; + } + } + } + + log.warn("Could not re-route vehicle {} to a replacement transit stop", getVehicle().getId()); + } + } + + return null; + } + + @Override + public double handleTransitStop(TransitStopFacility stop, double now) { + + // This function will call the API with the original stop as if no reroute has happened + + // use the original stop exactly one time + if (overwrittenStop != null) { + stop = overwrittenStop; + double t = super.handleTransitStop(stop, now); + overwrittenStop = null; + return t; + } + + return super.handleTransitStop(stop, now); + } +} diff --git a/matsim/src/main/java/org/matsim/core/router/FastRouterType.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/TrackState.java similarity index 80% rename from matsim/src/main/java/org/matsim/core/router/FastRouterType.java rename to contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/TrackState.java index 0c70498ab49..976d2d2e9ad 100644 --- a/matsim/src/main/java/org/matsim/core/router/FastRouterType.java +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/TrackState.java @@ -1,10 +1,9 @@ /* *********************************************************************** * * project: org.matsim.* - * FastRouterType.java * * * *********************************************************************** * * * - * copyright : (C) 2012 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -18,15 +17,16 @@ * * * *********************************************************************** */ -package org.matsim.core.router; +package ch.sbb.matsim.contrib.railsim.qsimengine; /** - * Type Pointer is no longer supported. For now we still keep it here so we - * can throw an exception if somebody tries to us it. - * - * @author cdobler + * Current state of a track. */ -public enum FastRouterType { - ARRAY, POINTER -} +public enum TrackState { + FREE, + /** + * Blocked tracks that are exclusively available for trains. + */ + BLOCKED +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/TrainInfo.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/TrainInfo.java new file mode 100644 index 00000000000..9d395d785d0 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/TrainInfo.java @@ -0,0 +1,60 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.RailsimUtils; +import ch.sbb.matsim.contrib.railsim.config.RailsimConfigGroup; +import org.matsim.api.core.v01.Id; +import org.matsim.vehicles.VehicleType; + +/** + * Non-mutable static information for a single train. + */ +record TrainInfo( + Id id, + double length, + double maxVelocity, + double acceleration, + double deceleration, + double maxDeceleration +) { + + TrainInfo(VehicleType vehicle, RailsimConfigGroup config) { + this( + vehicle.getId(), + vehicle.getLength(), + vehicle.getMaximumVelocity(), + RailsimUtils.getTrainAcceleration(vehicle, config), + RailsimUtils.getTrainDeceleration(vehicle, config), + RailsimUtils.getTrainDeceleration(vehicle, config) + ); + } + + public void checkConsistency() { + if (!Double.isFinite(maxVelocity) || maxVelocity <= 0) + throw new IllegalArgumentException("Train of type " + id + " does not have a finite maximumVelocity."); + + if (!Double.isFinite(acceleration) || acceleration <= 0) + throw new IllegalArgumentException("Train of type " + id + " does not have a finite and positive acceleration."); + + if (!Double.isFinite(deceleration) || deceleration <= 0) + throw new IllegalArgumentException("Train of type " + id + " does not have a finite and positive deceleration."); + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/TrainState.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/TrainState.java new file mode 100644 index 00000000000..1c0f66cb969 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/TrainState.java @@ -0,0 +1,167 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.network.Link; +import org.matsim.core.mobsim.framework.MobsimDriverAgent; +import org.matsim.pt.transitSchedule.api.TransitStopFacility; + +import javax.annotation.Nullable; +import java.util.List; + +/** + * Stores the mutable current state of a train. + */ +final class TrainState { + + /** + * Driver of the train. + */ + final MobsimDriverAgent driver; + + /** + * Transit agent, if this is a pt transit. + */ + @Nullable + final RailsimTransitDriverAgent pt; + + /** + * Next transit stop. + */ + @Nullable + TransitStopFacility nextStop; + + /** + * Train specific parameters. + */ + final TrainInfo train; + + /** + * Route of this train. + */ + final List route; + + /** + * Current index in the list of route links. + */ + int routeIdx; + + /** + * Time of this state. + */ + double timestamp; + + /** + * The link the where the head of the train is on. Can be null if not yet departed. + */ + @Nullable + Id headLink; + + /** + * Current link the very end of the train is on. Can be null if not yet departed. + */ + @Nullable + Id tailLink; + + /** + * Trains target speed. + */ + double targetSpeed; + + /** + * Train plans to decelerate after this distance. + */ + double targetDecelDist; + + /** + * Current allowed speed, which depends on train type, links, but not on other trains or speed needed to stop. + */ + double allowedMaxSpeed; + + /** + * Distance in meters away from the {@code headLink}s {@code fromNode}. + */ + double headPosition; + + /** + * * Distance in meters away from the {@code tailLink}s {@code fromNode}. + */ + double tailPosition; + + /** + * Speed in m/s. + */ + double speed; + + /** + * Current Acceleration, (or deceleration if negative). + */ + double acceleration; + + TrainState(MobsimDriverAgent driver, TrainInfo train, double timestamp, @Nullable Id linkId, List route) { + this.driver = driver; + this.pt = driver instanceof RailsimTransitDriverAgent ptDriver ? ptDriver : null; + this.nextStop = pt != null ? pt.getNextTransitStop() : null; + this.train = train; + this.route = route; + this.timestamp = timestamp; + this.headLink = linkId; + this.tailLink = linkId; + this.targetDecelDist = Double.POSITIVE_INFINITY; + } + + @Override + public String toString() { + return "TrainState{" + + "driver=" + driver.getId() + + ", timestamp=" + timestamp + + ", headLink=" + headLink + + ", tailLink=" + tailLink + + ", targetSpeed=" + targetSpeed + + ", allowedMaxSpeed=" + allowedMaxSpeed + + ", headPosition=" + headPosition + + ", tailPosition=" + tailPosition + + ", speed=" + speed + + ", acceleration=" + acceleration + + '}'; + } + + + boolean isRouteAtEnd() { + return routeIdx >= route.size(); + } + + /** + * Check whether to stop at certain link. + */ + boolean isStop(Id link) { + return nextStop != null && nextStop.getLinkId().equals(link); + } + + RailsimTrainStateEvent asEvent(double time) { + return new RailsimTrainStateEvent(time, time, driver.getVehicle().getId(), + headLink, headPosition, + tailLink, tailPosition, + speed, acceleration, targetSpeed); + } + +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/UpdateEvent.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/UpdateEvent.java new file mode 100644 index 00000000000..52776792c9b --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/UpdateEvent.java @@ -0,0 +1,110 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import java.util.Objects; + +/** + * Internal event that describes, when a {@link TrainState} is supposed to be updated. + */ +final class UpdateEvent implements Comparable { + + final TrainState state; + double plannedTime; + Type type; + + /** + * Timestamp when next reservation will be checked. + */ + double checkReservation = -1; + + /** + * Whether train is waiting on the very link end for the next to be unblocked. + */ + boolean waitingForLink; + + /** + * Stores a link that is to be released. + */ + final RailLink unblockLink; + + UpdateEvent(TrainState state, Type type) { + this.state = state; + this.plannedTime = state.timestamp; + this.type = type; + this.waitingForLink = false; + this.unblockLink = null; + } + + UpdateEvent(TrainState state, RailLink unblockLink, double time) { + this.state = state; + this.unblockLink = unblockLink; + this.plannedTime = time + unblockLink.minimumHeadwayTime; + this.type = Type.UNBLOCK_LINK; + } + + @Override + public int compareTo(UpdateEvent o) { + int compare = Double.compare(plannedTime, o.plannedTime); + + if (compare == 0) + return state.driver.getId().compareTo(o.state.driver.getId()); + + return compare; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + UpdateEvent that = (UpdateEvent) o; + return Objects.equals(state, that.state); + } + + @Override + public int hashCode() { + return Objects.hash(state); + } + + /** + * This train currently waits for a reservation for blocked tracks. + */ + boolean isAwaitingReservation() { + return checkReservation >= 0; + } + + /** + * The type of the requested update. + */ + enum Type { + + IDLE, + DEPARTURE, + POSITION, + ENTER_LINK, + LEAVE_LINK, + BLOCK_TRACK, + WAIT_FOR_RESERVATION, + SPEED_CHANGE, + UNBLOCK_LINK + + } + +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/disposition/SimpleDisposition.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/disposition/SimpleDisposition.java new file mode 100644 index 00000000000..99418a7547b --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/disposition/SimpleDisposition.java @@ -0,0 +1,89 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine.disposition; + +import ch.sbb.matsim.contrib.railsim.qsimengine.RailLink; +import ch.sbb.matsim.contrib.railsim.qsimengine.RailResourceManager; +import ch.sbb.matsim.contrib.railsim.qsimengine.RailsimTransitDriverAgent; +import ch.sbb.matsim.contrib.railsim.qsimengine.router.TrainRouter; +import jakarta.inject.Inject; +import org.matsim.core.mobsim.framework.MobsimDriverAgent; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; + +/** + * Simple disposition without deadlock avoidance. + */ +public class SimpleDisposition implements TrainDisposition { + + private final RailResourceManager resources; + private final TrainRouter router; + + @Inject + public SimpleDisposition(RailResourceManager resources, TrainRouter router) { + this.resources = resources; + this.router = router; + } + + @Override + public void onDeparture(double time, MobsimDriverAgent driver, List route) { + // Nothing to do. + } + + @Nullable + @Override + public List requestRoute(double time, RailsimTransitDriverAgent driver, List segment, RailLink entry, RailLink exit) { + + // Only re-routes if the link segment is occupied + for (RailLink link : segment) { + if (!resources.isBlockedBy(link, driver) && !resources.hasCapacity(link.getLinkId())) + return router.calcRoute(entry, exit); + } + + return null; + } + + @Override + public List blockRailSegment(double time, MobsimDriverAgent driver, List segment) { + + List blocked = new ArrayList<>(); + + // Iterate all links that need to be blocked + for (RailLink link : segment) { + + // Check if single link can be reserved + if (resources.tryBlockTrack(time, driver, link)) { + blocked.add(link); + } else + break; + } + + return blocked; + } + + @Override + public void unblockRailLink(double time, MobsimDriverAgent driver, RailLink link) { + + // put resource handling into release track + resources.releaseTrack(time, driver, link); + } +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/disposition/TrainDisposition.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/disposition/TrainDisposition.java new file mode 100644 index 00000000000..eb178dc663c --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/disposition/TrainDisposition.java @@ -0,0 +1,64 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine.disposition; + +import ch.sbb.matsim.contrib.railsim.qsimengine.RailLink; +import ch.sbb.matsim.contrib.railsim.qsimengine.RailsimTransitDriverAgent; +import org.matsim.core.mobsim.framework.MobsimDriverAgent; + +import javax.annotation.Nullable; +import java.util.List; + +/** + * Disposition, handling route and track reservations. + */ +public interface TrainDisposition { + + /** + * Method invoked when a train is departing. + */ + void onDeparture(double time, MobsimDriverAgent driver, List route); + + /** + * Called by the driver when an entry link is within stop distance. + * + * @param segment the original link segment between entry and exit + * @return the route change, or null if nothing should be changed + */ + @Nullable + default List requestRoute(double time, RailsimTransitDriverAgent driver, List segment, + RailLink entry, RailLink exit) { + return null; + } + + /** + * Train is reaching the given links and is trying to block them. + * + * @return links of the request that are exclusively blocked for the train. + */ + List blockRailSegment(double time, MobsimDriverAgent driver, List segment); + + /** + * Inform the resource manager that the train has passed a link that can now be unblocked. + * This needs to be called after track states have been updated already. + */ + void unblockRailLink(double time, MobsimDriverAgent driver, RailLink link); + +} diff --git a/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/router/TrainRouter.java b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/router/TrainRouter.java new file mode 100644 index 00000000000..bb25b2ac3b2 --- /dev/null +++ b/contribs/railsim/src/main/java/ch/sbb/matsim/contrib/railsim/qsimengine/router/TrainRouter.java @@ -0,0 +1,84 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine.router; + +import ch.sbb.matsim.contrib.railsim.qsimengine.RailLink; +import ch.sbb.matsim.contrib.railsim.qsimengine.RailResourceManager; +import jakarta.inject.Inject; +import org.matsim.api.core.v01.network.Link; +import org.matsim.api.core.v01.network.Network; +import org.matsim.api.core.v01.network.Node; +import org.matsim.api.core.v01.population.Person; +import org.matsim.core.mobsim.qsim.QSim; +import org.matsim.core.router.speedy.SpeedyALTFactory; +import org.matsim.core.router.util.LeastCostPathCalculator; +import org.matsim.core.router.util.TravelDisutility; +import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; +import org.matsim.vehicles.Vehicle; + +import java.util.List; + +/** + * Calculates unblocked route between two {@link RailLink}. + */ +public final class TrainRouter { + + private final Network network; + private final RailResourceManager resources; + private final LeastCostPathCalculator lpc; + + @Inject + public TrainRouter(QSim qsim, RailResourceManager resources) { + this(qsim.getScenario().getNetwork(), resources); + } + + public TrainRouter(Network network, RailResourceManager resources) { + this.network = network; + this.resources = resources; + + // uses the full network, which should not be slower than filtered network as long as dijkstra is used + this.lpc = new SpeedyALTFactory().createPathCalculator(network, new DisUtility(), new FreeSpeedTravelTime()); + } + + /** + * Calculate the shortest path between two links. + */ + public List calcRoute(RailLink from, RailLink to) { + + Node fromNode = network.getLinks().get(from.getLinkId()).getToNode(); + Node toNode = network.getLinks().get(to.getLinkId()).getFromNode(); + + LeastCostPathCalculator.Path path = lpc.calcLeastCostPath(fromNode, toNode, 0, null, null); + + return path.links.stream().map(l -> resources.getLink(l.getId())).toList(); + } + + private final class DisUtility implements TravelDisutility { + @Override + public double getLinkTravelDisutility(Link link, double time, Person person, Vehicle vehicle) { + return resources.hasCapacity(link.getId()) ? 0 : 1; + } + + @Override + public double getLinkMinimumTravelDisutility(Link link) { + return 0; + } + } +} diff --git a/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/integration/RailsimIntegrationTest.java b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/integration/RailsimIntegrationTest.java new file mode 100644 index 00000000000..f49a5b0901c --- /dev/null +++ b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/integration/RailsimIntegrationTest.java @@ -0,0 +1,455 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.integration; + +import ch.sbb.matsim.contrib.railsim.RailsimModule; +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent; +import ch.sbb.matsim.contrib.railsim.qsimengine.RailsimQSimModule; +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.TransportMode; +import org.matsim.api.core.v01.events.Event; +import org.matsim.api.core.v01.network.Link; +import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; +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.scenario.ScenarioUtils; +import org.matsim.core.utils.io.IOUtils; +import org.matsim.examples.ExamplesUtils; +import org.matsim.pt.transitSchedule.api.Departure; +import org.matsim.pt.transitSchedule.api.TransitLine; +import org.matsim.pt.transitSchedule.api.TransitRoute; +import org.matsim.pt.transitSchedule.api.TransitScheduleFactory; +import org.matsim.testcases.MatsimTestUtils; +import org.matsim.testcases.utils.EventsCollector; +import org.matsim.vehicles.Vehicle; +import org.matsim.vehicles.VehicleType; + +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +public class RailsimIntegrationTest { + + @Rule + public MatsimTestUtils utils = new MatsimTestUtils(); + + @Test + public void testMicroSimpleBiDirectionalTrack() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microSimpleBiDirectionalTrack")); + } + + @Test + public void testMesoUniDirectionalVaryingCapacities() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "mesoUniDirectionalVaryingCapacities")); + + // print events of train1 for debugging + List train1events = filterTrainEvents(collector, "train1"); + train1events.forEach(System.out::println); + + // calculation of expected time for train1: acceleration = 0.5, length = 100 + // route: - station: 2.77777m/s + // - link: 50000m, 13.8889m/s + // - station: 200m, 2.777777m/s + // - link: 50000m, 13.8889m/s + // - station: 200m, 2.777777m/s + + double departureTime = 8 * 3600; + double trainLength = 100; + double acceleration = 0.5; + double stationSpeed = 2.7777777777777777; + double stationLength = 200; + double linkSpeed = 13.8889; + double linkLength = 50000; + + double currentTime = departureTime; + assertTrainState(currentTime, 0, 0, 0, stationLength, train1events); + + // train starts in the station, accelerates to station speed and continues until the train has left the station link + assertTrainState(currentTime, 0, stationSpeed, acceleration, 0, train1events); + + double accTime1 = timeToAccelerate(0, stationSpeed, acceleration); + double accDistance1 = distanceTravelled(0, acceleration, accTime1); + currentTime += accTime1; + assertTrainState(currentTime, stationSpeed, stationSpeed, 0, accDistance1, train1events); + + double cruiseTime2 = timeForDistance(trainLength - accDistance1, stationSpeed); + double cruiseDistance2 = distanceTravelled(stationSpeed, 0, cruiseTime2); // should be = trainLength - accDistance1 + currentTime += cruiseTime2; + assertTrainState(currentTime, stationSpeed, stationSpeed, 0, accDistance1 + cruiseDistance2, train1events); + + // train further accelerates to link speed + double accTime3 = timeToAccelerate(stationSpeed, linkSpeed, acceleration); + double accDistance3 = distanceTravelled(stationSpeed, acceleration, accTime3); + currentTime += accTime3; + assertTrainState(currentTime, linkSpeed, linkSpeed, 0, accDistance1 + cruiseDistance2 + accDistance3, train1events); + + // train can cruise with link speed until it needs to decelerate for next station + double decTime5 = timeToAccelerate(linkSpeed, stationSpeed, -acceleration); + double decDistance5 = distanceTravelled(linkSpeed, -acceleration, decTime5); + + double cruiseDistance4 = linkLength - accDistance1 - cruiseDistance2 - accDistance3 - decDistance5; + double cruiseTime4 = timeForDistance(cruiseDistance4, linkSpeed); + currentTime += cruiseTime4; + assertTrainState(currentTime, linkSpeed, linkSpeed, 0, linkLength - decDistance5, train1events); + // start deceleration + assertTrainState(currentTime, linkSpeed, stationSpeed, -acceleration, linkLength - decDistance5, train1events); + currentTime += decTime5; + assertTrainState(currentTime, stationSpeed, stationSpeed, 0, linkLength, train1events); + + // Trains stops at station in the middle, calculated directly + currentTime = 32524.2; + assertTrainState(currentTime, 0, 0, 0, stationLength, train1events); + + double accelAfterStation = timeToAccelerate(0, stationSpeed, acceleration); + double distAfterStation = distanceTravelled(0, acceleration, accelAfterStation); + + currentTime += accelAfterStation; + assertTrainState(currentTime, stationSpeed, stationSpeed, 0, distAfterStation, train1events); + + // train passes station completely + double leaveStation = timeForDistance(trainLength - distAfterStation, stationSpeed); + + currentTime += leaveStation; + assertTrainState(currentTime, stationSpeed, stationSpeed, 0, trainLength, train1events); + + // train can accelerate again to link speed + double accTime7 = timeToAccelerate(stationSpeed, linkSpeed, acceleration); + double accDistance7 = distanceTravelled(stationSpeed, acceleration, accTime7); + currentTime += accTime7; + assertTrainState(currentTime, linkSpeed, linkSpeed, 0, trainLength + accDistance7, train1events); + + // train can cruise with link speed until it needs to decelerate for final station + double decTime9 = timeToAccelerate(linkSpeed, stationSpeed, -acceleration); + double decDistance9 = distanceTravelled(linkSpeed, -acceleration, decTime9); + + double cruiseDistance8 = linkLength - trainLength - accDistance7 - decDistance9; + double cruiseTime8 = timeForDistance(cruiseDistance8, linkSpeed); + + currentTime += cruiseTime8 + decTime9; + + // end of link, entering station + assertTrainState(currentTime, stationSpeed, stationSpeed, 0, linkLength, train1events); + + // train can cruise into station link until it needs to fully brake + double decTime11 = timeToAccelerate(stationSpeed, 0, -acceleration); + double decDistance11 = distanceTravelled(stationSpeed, -acceleration, decTime11); + + double cruiseDistance10 = stationLength - decDistance11; + double cruiseTime10 = timeForDistance(cruiseDistance10, stationSpeed); + + currentTime += cruiseTime10; + assertTrainState(currentTime, stationSpeed, 0, -acceleration, cruiseDistance10, train1events); + + // final train arrival + currentTime += decTime11; + assertTrainState(currentTime, 0, 0, 0, stationLength, train1events); + } + + @Test + public void testMicroTrackOppositeTraffic() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microTrackOppositeTraffic")); + } + + @Test + public void testMicroTrackOppositeTrafficMany() { + // multiple trains, one slow train + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microTrackOppositeTrafficMany")); + } + + @Test + public void testMesoTwoSources() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "mesoTwoSources")); + } + + @Test + public void testMesoTwoSourcesComplex() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "mesoTwoSourcesComplex")); + } + + @Test + public void testScenarioMesoGenfBernAllTrains() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "scenarioMesoGenfBern")); + } + + @Test + public void testScenarioMesoGenfBernOneTrain() { + + // Remove vehicles except the first one + Consumer filter = scenario -> { + + Set> remove = scenario.getTransitVehicles().getVehicles().values().stream() + .filter(v -> !v.getId().toString().equals("Bummelzug_GE_BE_train_0")).map(Vehicle::getId).collect(Collectors.toSet()); + + for (TransitLine line : scenario.getTransitSchedule().getTransitLines().values()) { + + for (TransitRoute route : line.getRoutes().values()) { + + Collection values = new ArrayList<>(route.getDepartures().values()); + for (Departure departure : values) { + + if (remove.contains(departure.getVehicleId())) route.removeDeparture(departure); + } + } + } + + remove.forEach(v -> scenario.getTransitVehicles().removeVehicle(v)); + }; + + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "scenarioMesoGenfBern"), filter); + + } + + @Test + public void testMicroThreeUniDirectionalTracks() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microThreeUniDirectionalTracks")); + } + + @Test + public void testMicroTrainFollowingConstantSpeed() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microTrainFollowingConstantSpeed")); + } + + // This test is similar to testMicroTrainFollowingConstantSpeed but with varying speed levels along the corridor. + @Test + public void testMicroTrainFollowingVaryingSpeed() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microTrainFollowingVaryingSpeed")); + } + + @Test + public void testMicroStationSameLink() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microStationSameLink")); + } + + @Test + public void testMicroStationDifferentLink() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microStationDifferentLink")); + } + + @Test + public void testMicroJunctionCross() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microJunctionCross")); + } + + @Test + public void testMicroJunctionY() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microJunctionY")); + } + + @Test + public void testMesoStationCapacityOne() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "mesoStationCapacityOne")); + } + + @Test + public void testMesoStationCapacityTwo() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "mesoStationCapacityTwo")); + } + + @Test + public void testMesoStations() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "mesoStations")); + } + + @Test + public void testMicroSimpleUniDirectionalTrack() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microSimpleUniDirectionalTrack")); + + for (Event event : collector.getEvents()) { + if (event.getEventType().equals(VehicleArrivesAtFacilityEvent.EVENT_TYPE)) { + + VehicleArrivesAtFacilityEvent vehicleArrivesEvent = (VehicleArrivesAtFacilityEvent) event; + if (vehicleArrivesEvent.getVehicleId().toString().equals("train1") && vehicleArrivesEvent.getFacilityId().toString() + .equals("stop_3-4")) { + + Assert.assertEquals("The arrival time of train1 at stop_3-4 has changed.", 29594., event.getTime(), MatsimTestUtils.EPSILON); + } + } + } + } + + @Test + public void testMicroStationRerouting() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microStationRerouting")); + collector.getEvents().forEach(System.out::println); + // Checks end times + assertTrainState(30854, 0, 0, 0, 400, filterTrainEvents(collector, "train1")); + // 1min later + assertTrainState(30914, 0, 0, 0, 400, filterTrainEvents(collector, "train2")); + // These arrive closer together, because both waited + assertTrainState(30974, 0, 0, 0, 400, filterTrainEvents(collector, "train3")); + assertTrainState(30982, 0, 0, 0, 400, filterTrainEvents(collector, "train4")); + } + + @Test + public void testMicroStationReroutingConcurrent() { + Consumer filter = scenario -> { + + TransitScheduleFactory f = scenario.getTransitSchedule().getFactory(); + + for (TransitLine line : scenario.getTransitSchedule().getTransitLines().values()) { + + for (TransitRoute route : line.getRoutes().values()) { + + Collection values = new ArrayList<>(route.getDepartures().values()); + values.forEach(route::removeDeparture); + + // Re-create departure for same time + for (Departure departure : values) { + Departure d = f.createDeparture(departure.getId(), 8 * 3600); + d.setVehicleId(departure.getVehicleId()); + route.addDeparture(d); + } + } + } + }; + + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "microStationRerouting"), filter); + } + + @Test + public void testScenarioKelheim() { + + URL base = ExamplesUtils.getTestScenarioURL("kelheim"); + + Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(base, "config.xml")); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); + + Scenario scenario = ScenarioUtils.loadScenario(config); + + // Convert all pt to rail + for (Link link : scenario.getNetwork().getLinks().values()) { + if (link.getAllowedModes().contains(TransportMode.car)) link.setAllowedModes(Set.of(TransportMode.car, "ride", "freight")); + + if (link.getAllowedModes().contains(TransportMode.pt)) { + link.setFreespeed(50); + link.setAllowedModes(Set.of("rail")); + } + } + + // Maximum velocity must be configured + for (VehicleType type : scenario.getTransitVehicles().getVehicleTypes().values()) { + type.setMaximumVelocity(30); + type.setLength(100); + } + + SnzActivities.addScoringParams(config); + + Controler controler = new Controler(scenario); + controler.addOverridingModule(new RailsimModule()); + controler.configureQSimComponents(components -> new RailsimQSimModule().configure(components)); + + controler.run(); + } + + @Test + public void testScenarioMicroMesoCombination() { + EventsCollector collector = runSimulation(new File(utils.getPackageInputDirectory(), "scenarioMicroMesoCombination")); + } + + private EventsCollector runSimulation(File scenarioDir) { + return runSimulation(scenarioDir, null); + } + + private EventsCollector runSimulation(File scenarioDir, Consumer f) { + Config config = ConfigUtils.loadConfig(new File(scenarioDir, "config.xml").toString()); + + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setDumpDataAtEnd(true); + config.controller().setCreateGraphs(false); + config.controller().setLastIteration(0); + + Scenario scenario = ScenarioUtils.loadScenario(config); + + if (f != null) f.accept(scenario); + + Controler controler = new Controler(scenario); + controler.addOverridingModule(new RailsimModule()); + controler.configureQSimComponents(components -> new RailsimQSimModule().configure(components)); + + EventsCollector collector = new EventsCollector(); + controler.addOverridingModule(new AbstractModule() { + @Override + public void install() { + this.addEventHandlerBinding().toInstance(collector); + } + }); + + controler.run(); + + return collector; + } + + private double timeToAccelerate(double v0, double v, double a) { + return (v - v0) / a; + } + + private double distanceTravelled(double v0, double a, double t) { + return 0.5 * a * t * t + v0 * t; + } + + private double timeForDistance(double d, double v) { + return d / v; + } + + private void assertTrainState(double time, double speed, double targetSpeed, double acceleration, double headPosition, List events) { + + RailsimTrainStateEvent prev = null; + for (RailsimTrainStateEvent event : events) { + + if (event.getTime() > Math.ceil(time)) { + Assert.fail( + String.format("No matching event found for time %f, speed %f pos %f, Closest event is%s", time, speed, headPosition, prev)); + } + + // If all assertions are true, returns successfully + try { + Assert.assertEquals(Math.ceil(time), event.getTime(), 1e-7); + Assert.assertEquals(speed, event.getSpeed(), 1e-5); + Assert.assertEquals(targetSpeed, event.getTargetSpeed(), 1e-7); + Assert.assertEquals(acceleration, event.getAcceleration(), 1e-5); + Assert.assertEquals(headPosition, event.getHeadPosition(), 1e-5); + return; + } catch (AssertionError e) { + // Check further events in loop + } + + prev = event; + } + } + + private List filterTrainEvents(EventsCollector collector, String train) { + return collector.getEvents().stream().filter(event -> event instanceof RailsimTrainStateEvent).map(event -> (RailsimTrainStateEvent) event) + .filter(event -> event.getVehicleId().toString().equals(train)).toList(); + } +} diff --git a/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/integration/SnzActivities.java b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/integration/SnzActivities.java new file mode 100644 index 00000000000..ac3a039f5a5 --- /dev/null +++ b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/integration/SnzActivities.java @@ -0,0 +1,91 @@ +/* + * Avoid dependency on vsp contrib, copy from: + * https://github.com/matsim-org/matsim-libs/blob/b2305e5e0f744b357486c8bbab253bb7c38aaad4/contribs/vsp/src/main/java/org/matsim/contrib/vsp/scenario/SnzActivities.java + */ +package ch.sbb.matsim.contrib.railsim.integration; + +import org.matsim.core.config.Config; +import org.matsim.core.config.groups.ScoringConfigGroup; + +/** + * Defines available activities and open- and closing times in Snz scenarios at vsp. + */ +public enum SnzActivities { + + home, + other, + visit, + accomp_children, + accomp_other, + + educ_kiga(7, 17), + educ_primary(7, 16), + educ_secondary(7, 17), + educ_tertiary(7, 22), + educ_higher(7, 19), + educ_other(7, 22), + + work(6, 20), + business(8, 20), + errands(8, 20), + + leisure(9, 27), + restaurant(8, 27), + shop_daily(8, 20), + shop_other(8, 20); + + /** + * Start time of an activity in hours, can be -1 if not defined. + */ + private final double start; + + /** + * End time of an activity in hours, can be -1 if not defined. + */ + private final double end; + + SnzActivities(double start, double end) { + this.start = start; + this.end = end; + } + + SnzActivities() { + this.start = -1; + this.end = -1; + } + + + /** + * Apply start and end time to params. + */ + public ScoringConfigGroup.ActivityParams apply(ScoringConfigGroup.ActivityParams params) { + if (start >= 0) + params = params.setOpeningTime(start * 3600.); + if (end >= 0) + params = params.setClosingTime(end * 3600.); + + return params; + } + + /** + * Add activity params for the scenario config. + */ + public static void addScoringParams(Config config) { + + for (SnzActivities value : SnzActivities.values()) { + for (long ii = 600; ii <= 97200; ii += 600) { + config.scoring().addActivityParams(value.apply(new ScoringConfigGroup.ActivityParams(value.name() + "_" + ii).setTypicalDuration(ii))); + } + } + + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("car interaction").setTypicalDuration(60)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("ride interaction").setTypicalDuration(60)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("bike interaction").setTypicalDuration(60)); + + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("other").setTypicalDuration(600 * 3)); + + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("freight_start").setTypicalDuration(60 * 15)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("freight_end").setTypicalDuration(60 * 15)); + + } +} diff --git a/matsim/src/main/java/org/matsim/pt/counts/package-info.java b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/EventAssert.java similarity index 78% rename from matsim/src/main/java/org/matsim/pt/counts/package-info.java rename to contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/EventAssert.java index 6a25ff406fd..7614ac66c3f 100644 --- a/matsim/src/main/java/org/matsim/pt/counts/package-info.java +++ b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/EventAssert.java @@ -1,11 +1,9 @@ - /* *********************************************************************** * * project: org.matsim.* - * package-info.java * * * *********************************************************************** * * * - * copyright : (C) 2019 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,7 +17,13 @@ * * * *********************************************************************** */ - /** - * This package contains classes for Count functionality of "pt". Except OccupancyAnalyzer and SimpleWriter all the other classes in this package are modified copies of classes from org.matsim.counts. - */ -package org.matsim.pt.counts; \ No newline at end of file +package ch.sbb.matsim.contrib.railsim.qsimengine; + +import org.assertj.core.api.AbstractAssert; +import org.matsim.api.core.v01.events.Event; + +class EventAssert extends AbstractAssert { + protected EventAssert(Event event, Class selfType) { + super(event, selfType); + } +} diff --git a/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/EventsAssert.java b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/EventsAssert.java new file mode 100644 index 00000000000..726b229ba80 --- /dev/null +++ b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/EventsAssert.java @@ -0,0 +1,57 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent; +import org.assertj.core.api.AbstractCollectionAssert; +import org.assertj.core.api.Condition; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.Event; + +import java.util.Collection; +import java.util.stream.StreamSupport; + +class EventsAssert extends AbstractCollectionAssert, Event, EventAssert> { + protected EventsAssert(Collection events, Class selfType) { + super(events, selfType); + } + + public EventsAssert hasTrainState(String veh, double time, double headPosition, double speed) { + return haveExactly(1, + new Condition<>(event -> + (event instanceof RailsimTrainStateEvent ev) + && ev.getVehicleId().equals(Id.createVehicleId(veh)) + && FuzzyUtils.equals(ev.getTime(), time) + && FuzzyUtils.equals(ev.getHeadPosition(), headPosition) + && FuzzyUtils.equals(ev.getSpeed(), speed), + String.format("event with veh %s time %.0f headPosition: %.2f speed: %.2f", veh, time, headPosition, speed)) + ); + } + + @Override + protected EventAssert toAssert(Event value, String description) { + return null; + } + + @Override + protected EventsAssert newAbstractIterableAssert(Iterable iterable) { + return new EventsAssert(StreamSupport.stream(iterable.spliterator(), false).toList(), EventsAssert.class); + } +} diff --git a/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimCalcTest.java b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimCalcTest.java new file mode 100644 index 00000000000..e969aa3cb2c --- /dev/null +++ b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimCalcTest.java @@ -0,0 +1,150 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import org.assertj.core.data.Offset; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RailsimCalcTest { + + @Test + public void testCalcAndSolveTraveledDist() { + + assertThat(RailsimCalc.calcTraveledDist(5, 2, 0)) + .isEqualTo(10); + + assertThat(RailsimCalc.solveTraveledDist(5, 15, 0)) + .isEqualTo(3); + + double d = RailsimCalc.calcTraveledDist(5, 3, 1); + + assertThat(d) + .isEqualTo(19.5); + + assertThat(RailsimCalc.solveTraveledDist(5, 19.5, 1)) + .isEqualTo(3); + + + } + + @Test + public void testCalcAndSolveTraveledDistNegative() { + + double d = RailsimCalc.calcTraveledDist(5, 5, -1); + + assertThat(d).isEqualTo(12.5); + + assertThat(RailsimCalc.calcTraveledDist(5, 10, -1)) + .isEqualTo(0); + + double t = RailsimCalc.solveTraveledDist(5, 12.5, -1); + + assertThat(t) + .isEqualTo(5); + + } + + @Test + public void testMaxSpeed() { + + double dist = 1000; + + double current = 5; + double f = 0; + + RailsimCalc.SpeedTarget res = RailsimCalc.calcTargetSpeed(dist, 0.5, 0.5, + 5, 30, 0); + + double timeDecel = (res.targetSpeed() - f) / 0.5; + double distDecel = RailsimCalc.calcTraveledDist(res.targetSpeed(), timeDecel, -0.5); + + double timeAccel = (res.targetSpeed() - current) / 0.5; + double distAccel = RailsimCalc.calcTraveledDist(5, timeAccel, 0.5); + + assertThat(distDecel + distAccel) + .isCloseTo(dist, Offset.offset(0.001)); + + } + + @Test + public void testCalcTargetDecel() { + + double d = RailsimCalc.calcTargetDecel(1000, 0, 10); + + assertThat(RailsimCalc.calcTraveledDist(10, -10 / d, d)) + .isCloseTo(1000, Offset.offset(0.001)); + + d = RailsimCalc.calcTargetDecel(1000, 5, 10); + + assertThat(RailsimCalc.calcTraveledDist(10, -5 / d, d)) + .isCloseTo(1000, Offset.offset(0.001)); + + } + + @Test + public void testCalcTargetSpeed() { + + RailsimCalc.SpeedTarget target = RailsimCalc.calcTargetSpeed(100, 0.5, 0.5, 0, 23, 0); + + + double t = RailsimCalc.solveTraveledDist(0, 50, 0.5); + + // Train can not reach target speed and accelerates until 50m + assertThat(target.decelDist()) + .isCloseTo(50, Offset.offset(0.0001)); + + assertThat(RailsimCalc.calcTraveledDist(target.targetSpeed(), t, -0.5)) + .isCloseTo(50, Offset.offset(0.0001)); + + + target = RailsimCalc.calcTargetSpeed(200, 0.5, 0.5, 13, 13, 0); + + assertThat(target.targetSpeed()) + .isCloseTo(13, Offset.offset(0.0001)); + + // assume travelling at max speed for 31m + assertThat(target.decelDist()) + .isCloseTo(31, Offset.offset(0.0001)); + + t = RailsimCalc.solveTraveledDist(13, 200 - 31, -0.5); + + // speed is 0 after decelerating rest of the distance + assertThat(13 + t * -0.5) + .isCloseTo(0, Offset.offset(0.001)); + + } + + @Test + public void testCalcTargetSpeedForStop() { + + double v = RailsimCalc.calcTargetSpeedForStop(1000, 0.5, 0.5, 0); + + double accelTime = v / 0.5; + + double d1 = RailsimCalc.calcTraveledDist(0, accelTime, 0.5); + double d2 = RailsimCalc.calcTraveledDist(v, accelTime, -0.5); + + assertThat(d1 + d2) + .isCloseTo(1000, Offset.offset(0.0001)); + + } +} diff --git a/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimEngineTest.java b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimEngineTest.java new file mode 100644 index 00000000000..a993b46fd49 --- /dev/null +++ b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimEngineTest.java @@ -0,0 +1,274 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.RailsimUtils; +import ch.sbb.matsim.contrib.railsim.config.RailsimConfigGroup; +import ch.sbb.matsim.contrib.railsim.qsimengine.disposition.SimpleDisposition; +import ch.sbb.matsim.contrib.railsim.qsimengine.router.TrainRouter; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.matsim.api.core.v01.network.Link; +import org.matsim.api.core.v01.network.Network; +import org.matsim.core.api.experimental.events.EventsManager; +import org.matsim.core.events.EventsUtils; +import org.matsim.core.network.NetworkUtils; +import org.matsim.testcases.MatsimTestUtils; + +import javax.annotation.Nullable; +import java.io.File; +import java.util.function.Consumer; + +public class RailsimEngineTest { + + @Rule + public MatsimTestUtils utils = new MatsimTestUtils(); + + private EventsManager eventsManager; + private RailsimTestUtils.EventCollector collector; + + @Before + public void setUp() { + eventsManager = EventsUtils.createEventsManager(); + collector = new RailsimTestUtils.EventCollector(); + + eventsManager.addHandler(collector); + eventsManager.initProcessing(); + } + + private RailsimTestUtils.Holder getTestEngine(String network, @Nullable Consumer f) { + Network net = NetworkUtils.readNetwork(new File(utils.getPackageInputDirectory(), network).toString()); + RailsimConfigGroup config = new RailsimConfigGroup(); + + collector.clear(); + + if (f != null) { + for (Link link : net.getLinks().values()) { + f.accept(link); + } + } + RailResourceManager res = new RailResourceManager(eventsManager, config, net); + TrainRouter router = new TrainRouter(net, res); + + return new RailsimTestUtils.Holder(new RailsimEngine(eventsManager, config, res, new SimpleDisposition(res, router)), net); + } + + private RailsimTestUtils.Holder getTestEngine(String network) { + return getTestEngine(network, null); + } + + @Test + public void testSimple() { + + RailsimTestUtils.Holder test = getTestEngine("networkMicroBi.xml"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "train", 0, "l1-2", "l5-6"); + + test.doSimStepUntil(400); + + RailsimTestUtils.assertThat(collector) + .hasSizeGreaterThan(5) + .hasTrainState("train", 144, 0, 44) + .hasTrainState("train", 234, 2000, 0); + + test = getTestEngine("networkMicroBi.xml"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "train", 0, "l1-2", "l5-6"); + + test.doStateUpdatesUntil(400, 1); + + RailsimTestUtils.assertThat(collector) + .hasSizeGreaterThan(5) + .hasTrainState("train", 144, 0, 44) + .hasTrainState("train", 234, 2000, 0); + + } + + @Test + public void testCongested() { + + RailsimTestUtils.Holder test = getTestEngine("networkMicroBi.xml"); + + RailsimTestUtils.createDeparture(test, TestVehicle.Cargo, "cargo", 0, "l1-2", "l5-6"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio", 60, "l1-2", "l5-6"); + + test.doSimStepUntil(600); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("cargo", 359, 2000, 0) + .hasTrainState("regio", 474, 2000, 0); + + } + + @Test + public void testCongestedWithHeadway() { + + RailsimTestUtils.Holder test = getTestEngine("networkMicroBi.xml", l -> RailsimUtils.setMinimumHeadwayTime(l, 60)); + + RailsimTestUtils.createDeparture(test, TestVehicle.Cargo, "cargo", 0, "l1-2", "l5-6"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio", 60, "l1-2", "l5-6"); + + test.doSimStepUntil(600); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("cargo", 359, 2000, 0) + .hasTrainState("regio", 485, 2000, 0); + + } + + + @Test + public void testOpposite() { + + RailsimTestUtils.Holder test = getTestEngine("networkMicroBi.xml"); + + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio1", 0, "l1-2", "l7-8"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio2", 0, "l8-7", "l2-1"); + + test.doSimStepUntil(600); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("regio1", 293, 600, 0) + .hasTrainState("regio2", 358, 1000, 0); + + + test = getTestEngine("networkMicroBi.xml"); + + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio1", 0, "l1-2", "l7-8"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio2", 0, "l8-7", "l2-1"); + + test.doStateUpdatesUntil(600, 1); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("regio1", 293, 600, 0) + .hasTrainState("regio2", 358, 1000, 0); + + } + + @Test + public void testVaryingSpeedOne() { + + RailsimTestUtils.Holder test = getTestEngine("networkMesoUni.xml"); + + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio", 0, "t1_IN-t1_OUT", "t3_IN-t3_OUT"); + + test.doSimStepUntil(10000); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("regio", 7599, 0, 2.7777777) + .hasTrainState("regio", 7674, 200, 0); + + test = getTestEngine("networkMesoUni.xml"); + + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio", 0, "t1_IN-t1_OUT", "t3_IN-t3_OUT"); + + test.doStateUpdatesUntil(10000, 1); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("regio", 7599, 0, 2.7777777) + .hasTrainState("regio", 7674, 200, 0); + + } + + @Test + public void testVaryingSpeedMany() { + + RailsimTestUtils.Holder test = getTestEngine("networkMesoUni.xml"); + + for (int i = 0; i < 10; i++) { + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio" + i, 60 * i, "t1_IN-t1_OUT", "t3_IN-t3_OUT"); + } + + test.doSimStepUntil(30000); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("regio0", 7599, 0, 2.7777777) + .hasTrainState("regio0", 7674, 200, 0) + .hasTrainState("regio1", 7734, 200, 0) + .hasTrainState("regio9", 23107, 200, 0); + + test = getTestEngine("networkMesoUni.xml"); + + for (int i = 0; i < 10; i++) { + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio" + i, 60 * i, "t1_IN-t1_OUT", "t3_IN-t3_OUT"); + } + + test.doStateUpdatesUntil(30000, 1); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("regio0", 7599, 0, 2.7777777) + .hasTrainState("regio0", 7674, 200, 0) + .hasTrainState("regio1", 7734, 200, 0) + .hasTrainState("regio9", 23107, 200, 0); + + } + + @Test + public void testTrainFollowing() { + + RailsimTestUtils.Holder test = getTestEngine("networkMicroUni.xml"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio1", 0, "1-2", "20-21"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio2", 0, "1-2", "20-21"); + + test.doSimStepUntil(5000); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("regio1", 1138, 1000, 0) + .hasTrainState("regio2", 1517, 1000, 0); + + test = getTestEngine("networkMicroUni.xml"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio1", 0, "1-2", "20-21"); + RailsimTestUtils.createDeparture(test, TestVehicle.Regio, "regio2", 0, "1-2", "20-21"); + + test.doStateUpdatesUntil(5000, 1); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("regio1", 1138, 1000, 0) + .hasTrainState("regio2", 1517, 1000, 0); + } + + @Test + public void testMicroTrainFollowingVaryingSpeed() { + + RailsimTestUtils.Holder test = getTestEngine("networkMicroVaryingSpeed.xml"); + + RailsimTestUtils.createDeparture(test, TestVehicle.Cargo, "cargo1", 0, "1-2", "20-21"); + RailsimTestUtils.createDeparture(test, TestVehicle.Cargo, "cargo2", 15, "1-2", "20-21"); + + test.doSimStepUntil(3000); +// test.debugFiles(collector, "microVarying"); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("cargo1", 1278, 1000, 0) + .hasTrainState("cargo2", 2033, 1000, 0); + + // Same test with state updates + test = getTestEngine("networkMicroVaryingSpeed.xml"); + RailsimTestUtils.createDeparture(test, TestVehicle.Cargo, "cargo1", 0, "1-2", "20-21"); + RailsimTestUtils.createDeparture(test, TestVehicle.Cargo, "cargo2", 15, "1-2", "20-21"); + test.doStateUpdatesUntil(3000, 1); +// test.debugFiles(collector, "microVarying_detailed"); + + RailsimTestUtils.assertThat(collector) + .hasTrainState("cargo1", 1278, 1000, 0) + .hasTrainState("cargo2", 2033, 1000, 0); + + + } +} diff --git a/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimTestUtils.java b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimTestUtils.java new file mode 100644 index 00000000000..63f5249cef6 --- /dev/null +++ b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/RailsimTestUtils.java @@ -0,0 +1,175 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.contrib.railsim.qsimengine; + +import ch.sbb.matsim.contrib.railsim.analysis.RailsimCsvWriter; +import ch.sbb.matsim.contrib.railsim.events.RailsimLinkStateChangeEvent; +import ch.sbb.matsim.contrib.railsim.events.RailsimTrainStateEvent; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.events.Event; +import org.matsim.api.core.v01.network.Link; +import org.matsim.api.core.v01.network.Network; +import org.matsim.core.events.algorithms.EventWriterXML; +import org.matsim.core.events.handler.BasicEventHandler; +import org.matsim.core.mobsim.framework.MobsimDriverAgent; +import org.matsim.core.mobsim.qsim.interfaces.MobsimVehicle; +import org.matsim.core.population.routes.NetworkRoute; +import org.matsim.core.population.routes.RouteUtils; +import org.matsim.core.router.DijkstraFactory; +import org.matsim.core.router.costcalculators.OnlyTimeDependentTravelDisutility; +import org.matsim.core.router.util.LeastCostPathCalculator; +import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; +import org.matsim.vehicles.MatsimVehicleReader; +import org.matsim.vehicles.Vehicle; +import org.matsim.vehicles.VehicleType; +import org.matsim.vehicles.VehicleUtils; +import org.matsim.vehicles.Vehicles; +import org.mockito.Answers; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +/** + * Helper class for test cases. + */ +public class RailsimTestUtils { + + static Map vehicles = new EnumMap<>(TestVehicle.class); + + static { + + Vehicles veh = VehicleUtils.createVehiclesContainer(); + + MatsimVehicleReader reader = new MatsimVehicleReader(veh); + reader.readURL(RailsimTestUtils.class.getResource("/trainVehicleTypes.xml")); + + vehicles.put(TestVehicle.Sprinter, veh.getVehicleTypes().get(Id.create("Sprinter", VehicleType.class))); + vehicles.put(TestVehicle.Express, veh.getVehicleTypes().get(Id.create("Express", VehicleType.class))); + vehicles.put(TestVehicle.Regio, veh.getVehicleTypes().get(Id.create("Regio", VehicleType.class))); + vehicles.put(TestVehicle.Cargo, veh.getVehicleTypes().get(Id.create("Cargo", VehicleType.class))); + } + + /** + * Create a departure within the engine. Route will be determined automatically. + */ + public static void createDeparture(Holder test, TestVehicle type, String veh, double time, String from, String to) { + + DijkstraFactory f = new DijkstraFactory(); + LeastCostPathCalculator lcp = f.createPathCalculator(test.network(), new OnlyTimeDependentTravelDisutility(new FreeSpeedTravelTime()), + new FreeSpeedTravelTime()); + + Link fromLink = test.network.getLinks().get(Id.createLinkId(from)); + Link toLink = test.network.getLinks().get(Id.createLinkId(to)); + + LeastCostPathCalculator.Path path = lcp.calcLeastCostPath(fromLink.getFromNode(), toLink.getToNode(), 0, null, null); + NetworkRoute route = RouteUtils.createNetworkRoute(path.links.stream().map(Link::getId).toList()); + + System.out.println("Creating departure with route" + route); + + // Setup mocks for driver and vehicle + Id vehicleId = Id.createVehicleId(veh); + + MobsimDriverAgent driver = Mockito.mock(MobsimDriverAgent.class, Answers.RETURNS_MOCKS); + MobsimVehicle mobVeh = Mockito.mock(MobsimVehicle.class, Answers.RETURNS_MOCKS); + + Vehicle vehicle = VehicleUtils.createVehicle(vehicleId, vehicles.get(type)); + + Mockito.when(mobVeh.getVehicle()).thenReturn(vehicle); + Mockito.when(mobVeh.getId()).thenReturn(vehicleId); + Mockito.when(driver.getVehicle()).thenReturn(mobVeh); + + test.engine.handleDeparture(time, driver, route.getStartLinkId(), route); + } + + /** + * Collect events during testing + */ + public static class EventCollector implements BasicEventHandler { + + List events = new ArrayList<>(); + + @Override + public void handleEvent(Event event) { + System.out.println(event); + events.add(event); + } + + public void clear() { + events.clear(); + } + + public void dump(String out) { + EventWriterXML writer = new EventWriterXML(out); + events.forEach(writer::handleEvent); + writer.closeFile(); + } + + } + + public record Holder(RailsimEngine engine, Network network) { + + /** + * Step at one second until time is reached. + */ + public void doSimStepUntil(double time) { + for (double t = 0; t < time; t++) { + engine().doSimStep(t); + } + } + + /** + * Call state updates until time is reached with fixed interval. + */ + public void doStateUpdatesUntil(double time, double interval) { + + for (double t = 0; t < time; t += interval) { + engine().updateAllStates(t); + } + } + + public void debugFiles(EventCollector collector, String out) { + RailsimCsvWriter.writeTrainStatesCsv( + collector.events.stream().filter(ev -> ev instanceof RailsimTrainStateEvent) + .map(ev -> (RailsimTrainStateEvent) ev) + .toList(), + network, + out + "_trainStates.csv" + ); + + RailsimCsvWriter.writeLinkStatesCsv( + collector.events.stream().filter(ev -> ev instanceof RailsimLinkStateChangeEvent) + .map(ev -> (RailsimLinkStateChangeEvent) ev) + .toList(), + out + "_linkStates.csv" + ); + } + } + + /** + * Helper method for event assertions. + */ + static EventsAssert assertThat(EventCollector events) { + return new EventsAssert(events.events, EventsAssert.class); + } + +} diff --git a/contribs/vsp/src/main/java/playground/vsp/randomizedtransitrouter/package-info.java b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/TestVehicle.java similarity index 83% rename from contribs/vsp/src/main/java/playground/vsp/randomizedtransitrouter/package-info.java rename to contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/TestVehicle.java index ce2cbb4e8ff..0094ab53c15 100644 --- a/contribs/vsp/src/main/java/playground/vsp/randomizedtransitrouter/package-info.java +++ b/contribs/railsim/src/test/java/ch/sbb/matsim/contrib/railsim/qsimengine/TestVehicle.java @@ -1,10 +1,9 @@ /* *********************************************************************** * * project: org.matsim.* - * package-info * * * *********************************************************************** * * * - * copyright : (C) 2013 by the members listed in the COPYING, * + * copyright : (C) 2023 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -17,10 +16,15 @@ * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ + +package ch.sbb.matsim.contrib.railsim.qsimengine; + /** - * Package providing functionality for transit routing with randomized utility parameters. - * - * @author dgrether - * + * Vehicle types that are defined for the test cases. */ -package playground.vsp.randomizedtransitrouter; \ No newline at end of file +public enum TestVehicle { + Sprinter, + Express, + Regio, + Cargo +} diff --git a/contribs/railsim/src/test/resources/trainVehicleTypes.xml b/contribs/railsim/src/test/resources/trainVehicleTypes.xml new file mode 100644 index 00000000000..9e70862fe68 --- /dev/null +++ b/contribs/railsim/src/test/resources/trainVehicleTypes.xml @@ -0,0 +1,50 @@ + + + + + + + 0.7 + 0.7 + + + + + + + + + + + 0.7 + 0.7 + + + + + + + + + + 0.5 + 0.5 + + + + + + + + + + 0.2 + 0.2 + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/trainNetwork.xml new file mode 100644 index 00000000000..f27451d8c21 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/trainNetwork.xml @@ -0,0 +1,73 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 999 + + + + + 999 + + + + + + + 999 + + + + + 999 + + + + + + + 1 + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/transitSchedule.xml new file mode 100644 index 00000000000..4926a4cecb6 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/transitSchedule.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/transitVehicles.xml new file mode 100644 index 00000000000..de84fed864e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityOne/transitVehicles.xml @@ -0,0 +1,32 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/trainNetwork.xml new file mode 100644 index 00000000000..3d91ff4b191 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/trainNetwork.xml @@ -0,0 +1,73 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 999 + + + + + 999 + + + + + + + 999 + + + + + 999 + + + + + + + 2 + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/transitSchedule.xml new file mode 100644 index 00000000000..4926a4cecb6 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/transitSchedule.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/transitVehicles.xml new file mode 100644 index 00000000000..de84fed864e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStationCapacityTwo/transitVehicles.xml @@ -0,0 +1,32 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/trainNetwork.xml new file mode 100644 index 00000000000..c278432ef21 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/trainNetwork.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 2 + + + + + 2 + + + + + 2 + + + + + 2 + + + + + 2 + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/transitSchedule.xml new file mode 100644 index 00000000000..cac9c1a1ebf --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/transitSchedule.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/transitVehicles.xml new file mode 100644 index 00000000000..1002d65f560 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoStations/transitVehicles.xml @@ -0,0 +1,28 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/trainNetwork.xml new file mode 100644 index 00000000000..49ed9222e98 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/trainNetwork.xml @@ -0,0 +1,124 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 999 + + + + + 999 + + + + + + 1 + + + + + 999 + + + + + + 999 + + + + + 999 + + + + + + 999 + + + + + 999 + + + + + + 999 + + + + + 999 + + + + + + bottleneck + 1 + + + + + bottleneck + 1 + + + + + + 999 + + + + + 999 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/transitSchedule.xml new file mode 100644 index 00000000000..92e5e3b25ae --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/transitSchedule.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/transitVehicles.xml new file mode 100644 index 00000000000..a74a653efb2 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSources/transitVehicles.xml @@ -0,0 +1,36 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/trainNetwork.xml new file mode 100644 index 00000000000..c68b481d038 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/trainNetwork.xml @@ -0,0 +1,82 @@ + + + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + 1 + + + + + + + + + + + + + + + 1 + + + + + 1 + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/transitSchedule.xml new file mode 100644 index 00000000000..09d5c02e458 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/transitSchedule.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/transitVehicles.xml new file mode 100644 index 00000000000..76d6e266237 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoTwoSourcesComplex/transitVehicles.xml @@ -0,0 +1,36 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/config.xml new file mode 100644 index 00000000000..fd5d50bb1b6 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/config.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/trainNetwork.xml new file mode 100644 index 00000000000..db1e86a0c4f --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/trainNetwork.xml @@ -0,0 +1,57 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + 999 + + + + + 2 + + + + + 999 + + + + + 5 + + + + + 999 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/transitSchedule.xml new file mode 100644 index 00000000000..3db3029cd5d --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/transitSchedule.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/transitVehicles.xml new file mode 100644 index 00000000000..262b655b7e3 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/mesoUniDirectionalVaryingCapacities/transitVehicles.xml @@ -0,0 +1,36 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/config.xml new file mode 100644 index 00000000000..b6491cf5f34 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/config.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/trainNetwork.xml new file mode 100644 index 00000000000..2f3d6815f1e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/trainNetwork.xml @@ -0,0 +1,106 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + c1 + + + + + c1 + + + + + + + + + + + + + c1 + + + + + c1 + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/transitSchedule.xml new file mode 100644 index 00000000000..c9add0e102c --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/transitSchedule.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/transitVehicles.xml new file mode 100644 index 00000000000..8a32c984f1a --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionCross/transitVehicles.xml @@ -0,0 +1,28 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/trainNetwork.xml new file mode 100644 index 00000000000..0bfe206efc8 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/trainNetwork.xml @@ -0,0 +1,94 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 999 + + + + + 1 + + + + + 1 + + + + + 999 + + + + + 1 + + + + + 1 + + + + + 3 + + + + + 1 + + + + + 999 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/transitSchedule.xml new file mode 100644 index 00000000000..8642858618f --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/transitSchedule.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/transitVehicles.xml new file mode 100644 index 00000000000..5c4aa7acf39 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/transitVehicles.xml @@ -0,0 +1,48 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/config.xml new file mode 100644 index 00000000000..53f168e5c17 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/config.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/trainNetwork.xml new file mode 100644 index 00000000000..193f08d66a3 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/trainNetwork.xml @@ -0,0 +1,78 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + l45 + + + + + l45 + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/transitSchedule.xml new file mode 100644 index 00000000000..748f927f15f --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/transitSchedule.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/transitVehicles.xml new file mode 100644 index 00000000000..20ebec4e74b --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleBiDirectionalTrack/transitVehicles.xml @@ -0,0 +1,30 @@ + + + + + + + 5.0 + serial + 5.0 + 0.5 + 0.5 + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/config.xml new file mode 100644 index 00000000000..be63f574384 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/config.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/trainNetwork.xml new file mode 100644 index 00000000000..52ae1533206 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/trainNetwork.xml @@ -0,0 +1,50 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + 1 + + + + + 1 + + + + + 5 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/transitSchedule.xml new file mode 100644 index 00000000000..88106a724e8 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/transitSchedule.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/transitVehicles.xml new file mode 100644 index 00000000000..00506a3afee --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microSimpleUniDirectionalTrack/transitVehicles.xml @@ -0,0 +1,26 @@ + + + + + + + 0.2 + 0.3 + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/trainNetwork.xml new file mode 100644 index 00000000000..aed5d10a9f7 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/trainNetwork.xml @@ -0,0 +1,425 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + r1 + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + r1 + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/transitSchedule.xml new file mode 100644 index 00000000000..113ee046b2c --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/transitSchedule.xml @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/transitVehicles.xml new file mode 100644 index 00000000000..f942a748536 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationDifferentLink/transitVehicles.xml @@ -0,0 +1,27 @@ + + + + + + + 0.2 + 0.2 + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/trainNetwork.xml new file mode 100644 index 00000000000..1ebe818b2c5 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/trainNetwork.xml @@ -0,0 +1,108 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + 2 + + + + + 2 + true + + + + + + + + + + + + + + 2 + true + + + + + 2 + + + + + + 2 + true + + + + + 2 + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/transitSchedule.xml new file mode 100644 index 00000000000..5e5f412f9fb --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/transitSchedule.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/transitVehicles.xml new file mode 100644 index 00000000000..e0e618e9b8e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/transitVehicles.xml @@ -0,0 +1,30 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/trainNetwork.xml new file mode 100644 index 00000000000..3119cbdaf75 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/trainNetwork.xml @@ -0,0 +1,423 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/transitSchedule.xml new file mode 100644 index 00000000000..44cb586edf2 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/transitSchedule.xml @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/transitVehicles.xml new file mode 100644 index 00000000000..5bdf728353f --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationSameLink/transitVehicles.xml @@ -0,0 +1,28 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/trainNetwork.xml new file mode 100644 index 00000000000..5721ac18c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/trainNetwork.xml @@ -0,0 +1,188 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 5 + + + + + 5 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 5 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 5 + + + + + 5 + + + + + 1 + + + + + 1 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/transitSchedule.xml new file mode 100644 index 00000000000..0d6c5472cca --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/transitSchedule.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/transitVehicles.xml new file mode 100644 index 00000000000..7e98d72953d --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microThreeUniDirectionalTracks/transitVehicles.xml @@ -0,0 +1,28 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/trainNetwork.xml new file mode 100644 index 00000000000..46f01336767 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/trainNetwork.xml @@ -0,0 +1,79 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + 5 + + + + + + + + + t2_A-t2_B + 1 + + + + + t2_A-t2_B + 1 + + + + + + + + + 5 + + + + + 5 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/transitSchedule.xml new file mode 100644 index 00000000000..cc3851daffe --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/transitSchedule.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/transitVehicles.xml new file mode 100644 index 00000000000..7d91bf38fee --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTraffic/transitVehicles.xml @@ -0,0 +1,36 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/trainNetwork.xml new file mode 100644 index 00000000000..46f01336767 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/trainNetwork.xml @@ -0,0 +1,79 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + 5 + + + + + + + + + t2_A-t2_B + 1 + + + + + t2_A-t2_B + 1 + + + + + + + + + 5 + + + + + 5 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/transitSchedule.xml new file mode 100644 index 00000000000..5d12af79465 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/transitSchedule.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/transitVehicles.xml new file mode 100644 index 00000000000..b359674db22 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/transitVehicles.xml @@ -0,0 +1,54 @@ + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + 5.0 + serial + 5.0 + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/trainNetwork.xml new file mode 100644 index 00000000000..840d9311577 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/trainNetwork.xml @@ -0,0 +1,169 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 5 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/transitSchedule.xml new file mode 100644 index 00000000000..673009a1ed0 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/transitSchedule.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/transitVehicles.xml new file mode 100644 index 00000000000..893a13e980f --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingConstantSpeed/transitVehicles.xml @@ -0,0 +1,46 @@ + + + + + + + 0.4 + 0.4 + + + + + + + + + + + + + + + + + + 0.1 + 0.1 + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/config.xml new file mode 100644 index 00000000000..da3761b5c4e --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/trainNetwork.xml new file mode 100644 index 00000000000..9094a12079c --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/trainNetwork.xml @@ -0,0 +1,170 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 5 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/transitSchedule.xml new file mode 100644 index 00000000000..673009a1ed0 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/transitSchedule.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/transitVehicles.xml new file mode 100644 index 00000000000..893a13e980f --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrainFollowingVaryingSpeed/transitVehicles.xml @@ -0,0 +1,46 @@ + + + + + + + 0.4 + 0.4 + + + + + + + + + + + + + + + + + + 0.1 + 0.1 + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/config.xml new file mode 100644 index 00000000000..c7ac9dffc64 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/config.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/trainNetwork.xml.gz b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/trainNetwork.xml.gz new file mode 100644 index 00000000000..17ecdf4768f Binary files /dev/null and b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/trainNetwork.xml.gz differ diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/transitSchedule.xml.gz b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/transitSchedule.xml.gz new file mode 100644 index 00000000000..5989dd29a2d Binary files /dev/null and b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/transitSchedule.xml.gz differ diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/transitVehicles.xml.gz b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/transitVehicles.xml.gz new file mode 100644 index 00000000000..25ad72a9773 Binary files /dev/null and b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMesoGenfBern/transitVehicles.xml.gz differ diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/config.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/config.xml new file mode 100644 index 00000000000..245af478051 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/config.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/trainNetwork.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/trainNetwork.xml new file mode 100644 index 00000000000..0f47de2b222 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/trainNetwork.xml @@ -0,0 +1,327 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + a + 12 + true + + + + + a + 12 + true + + + + + + + ab1 + + + + + ab1 + + + + + + ab2_1 + + + + + ab2_1 + + + + + + ab2_2 + + + + + ab2_2 + + + + + + ab2_3 + + + + + ab2_3 + + + + + + + b + 3 + true + + + + + b + 3 + true + + + + + + + bc + 2 + true + + + + + bc + 2 + true + + + + + + + c1 + + + + + c1 + + + + + + c1_c2_1 + + + + + c1_c2_1 + + + + + + c2 + + + + + c2 + + + + + + c1_c2_2 + + + + + c1_c2_2 + + + + + + c2_c3_1 + + + + + c2_c3_1 + + + + + + c3 + + + + + c3 + + + + + + c2_c3_2 + + + + + c2_c3_2 + + + + + + + cd + 2 + true + + + + + cd + 2 + true + + + + + + + d + 6 + + + + + d + 6 + + + + + + + ce_1 + 2 + true + + + + + ce_1 + 2 + true + + + + + ce_2 + 2 + + + + + ce_2 + 2 + + + + + + + e + 6 + true + + + + + e + 6 + true + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/transitSchedule.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/transitSchedule.xml new file mode 100644 index 00000000000..1f4d16bb781 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/transitSchedule.xml @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + rail + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/transitVehicles.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/transitVehicles.xml new file mode 100644 index 00000000000..c6faae55120 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/scenarioMicroMesoCombination/transitVehicles.xml @@ -0,0 +1,54 @@ + + + + + + + 0.3 + 0.3 + + + + + + + + + + + 0.4 + 0.4 + + + + + + + + + + + 0.1 + 0.1 + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMesoUni.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMesoUni.xml new file mode 100644 index 00000000000..e1296d25fea --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMesoUni.xml @@ -0,0 +1,58 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + 999 + + + + + 2 + + + + + 999 + + + + + 5 + + + + + 999 + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMicroBi.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMicroBi.xml new file mode 100644 index 00000000000..4596bfb98cd --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMicroBi.xml @@ -0,0 +1,78 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + l45 + + + + + l45 + + + + + + + + + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMicroUni.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMicroUni.xml new file mode 100644 index 00000000000..d7d57e30f32 --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMicroUni.xml @@ -0,0 +1,173 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 5 + + + + + + + + + diff --git a/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMicroVaryingSpeed.xml b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMicroVaryingSpeed.xml new file mode 100644 index 00000000000..9094a12079c --- /dev/null +++ b/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/qsimengine/networkMicroVaryingSpeed.xml @@ -0,0 +1,170 @@ + + + + + + Atlantis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 5 + + + + + + + diff --git a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingModuleDefaults.java b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingModuleDefaults.java index 296165c88be..ef3f8c3a02a 100644 --- a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingModuleDefaults.java +++ b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingModuleDefaults.java @@ -126,7 +126,7 @@ public TravelDisutilityFactory get() { final Config config = scenario.getConfig(); final TravelDisutilityFactory originalTravelDisutilityFactory = ControlerDefaults.createDefaultTravelDisutilityFactory(scenario); RoadPricingTravelDisutilityFactory travelDisutilityFactory = new RoadPricingTravelDisutilityFactory( originalTravelDisutilityFactory, scheme, config ); - travelDisutilityFactory.setSigma(config.plansCalcRoute().getRoutingRandomness()); + travelDisutilityFactory.setSigma(config.routing().getRoutingRandomness()); return travelDisutilityFactory; } diff --git a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingNetworkRouting.java b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingNetworkRouting.java index cd6a1b1906f..20fa27be345 100644 --- a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingNetworkRouting.java +++ b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingNetworkRouting.java @@ -4,8 +4,8 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.PopulationFactory; -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.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; import org.matsim.core.router.DefaultRoutingModules; @@ -48,10 +48,10 @@ class RoadPricingNetworkRouting implements Provider { SingleModeNetworksCache singleModeNetworksCache; @Inject - PlanCalcScoreConfigGroup planCalcScoreConfigGroup; + ScoringConfigGroup scoringConfigGroup; @Inject - PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; + RoutingConfigGroup routingConfigGroup; @Inject Network network; @@ -94,7 +94,7 @@ public RoutingModule get() { filteredNetwork, travelDisutilityFactory.createTravelDisutility(travelTime), travelTime); - if (!plansCalcRouteConfigGroup.getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none)) { + if (!routingConfigGroup.getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none)) { return DefaultRoutingModules.createAccessEgressNetworkRouter(TransportMode.car, routeAlgo, scenario, filteredNetwork, walkRouter, timeInterpretation, multimodalLinkChooser ); } else { diff --git a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingTravelDisutilityFactory.java b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingTravelDisutilityFactory.java index 06217074a2a..a3a85307170 100644 --- a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingTravelDisutilityFactory.java +++ b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingTravelDisutilityFactory.java @@ -50,7 +50,7 @@ public RoadPricingTravelDisutilityFactory(TravelDisutilityFactory previousTravel } public RoadPricingTravelDisutilityFactory(TravelDisutilityFactory previousTravelDisutilityFactory, RoadPricingScheme scheme, Config config) { - this( previousTravelDisutilityFactory, scheme, config.planCalcScore().getMarginalUtilityOfMoney() ) ; + this( previousTravelDisutilityFactory, scheme, config.scoring().getMarginalUtilityOfMoney() ) ; } @Override diff --git a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingWriterXMLv1.java b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingWriterXMLv1.java index 053359bf14e..6049a2a6d73 100644 --- a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingWriterXMLv1.java +++ b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/RoadPricingWriterXMLv1.java @@ -21,13 +21,13 @@ package org.matsim.contrib.roadpricing; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.List; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.roadpricing.RoadPricingSchemeImpl.Cost; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.Time; /** diff --git a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/TravelDisutilityIncludingToll.java b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/TravelDisutilityIncludingToll.java index 2654a3d75b3..22106c5ee41 100644 --- a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/TravelDisutilityIncludingToll.java +++ b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/TravelDisutilityIncludingToll.java @@ -30,7 +30,7 @@ import org.matsim.vehicles.Vehicle; /** - * Calculates the travel disutility for links, including tolls. Currently + * Calculates the travel disutility for links, including tolls. Currently * supports distance, cordon and area tolls. * * @author mrieser @@ -50,7 +50,7 @@ class TravelDisutilityIncludingToll implements TravelDisutility { TravelDisutilityIncludingToll(final TravelDisutility normalTravelDisutility, final RoadPricingScheme scheme, Config config) { - this( normalTravelDisutility, scheme, config.planCalcScore().getMarginalUtilityOfMoney(), 0. ) ; + this( normalTravelDisutility, scheme, config.scoring().getMarginalUtilityOfMoney(), 0. ) ; // this is using sigma=0 for backwards compatibility (not sure how often this is needed) } @@ -82,7 +82,7 @@ class TravelDisutilityIncludingToll implements TravelDisutility { } @Override - public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle) + public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle) { double normalTravelDisutilityForLink = this.normalTravelDisutility.getLinkTravelDisutility(link, time, person, vehicle); @@ -94,7 +94,7 @@ public double getLinkTravelDisutility(final Link link, final double time, final // end randomize double tollCost = this.tollCostHandler.getTypicalTollCost(link, time ); - + return normalTravelDisutilityForLink + tollCost*this.marginalUtilityOfMoney*logNormalRnd ; // sign convention: these are all costs (= disutilities), so they are all normally positive. tollCost is positive, marginalUtilityOfMoney as well. } diff --git a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/run/RunRoadPricingFromCode.java b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/run/RunRoadPricingFromCode.java index c2e185ee8ca..0c317cb4ff2 100644 --- a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/run/RunRoadPricingFromCode.java +++ b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/run/RunRoadPricingFromCode.java @@ -43,8 +43,8 @@ private static void run(String[] args){ parameteres specified) and just remove the road pricing file. */ Config config = ConfigUtils.loadConfig(args[0], RoadPricingUtils.createConfigGroup()); ConfigUtils.addOrGetModule(config, RoadPricingConfigGroup.class).setTollLinksFile(null); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(10); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(10); // prepare scenario: @@ -71,8 +71,8 @@ private static void runFromFile(String[] args){ /* Start with a known config file (with population, network, and scoring parameteres specified) and just remove the road pricing file. */ Config config = ConfigUtils.loadConfig(args[0], RoadPricingUtils.createConfigGroup()); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(10); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(10); // prepare scenario: diff --git a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/run/RunRoadPricingUsingTollFactorExample.java b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/run/RunRoadPricingUsingTollFactorExample.java index ecdecf2c373..4f53fa930ea 100644 --- a/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/run/RunRoadPricingUsingTollFactorExample.java +++ b/contribs/roadpricing/src/main/java/org/matsim/contrib/roadpricing/run/RunRoadPricingUsingTollFactorExample.java @@ -49,7 +49,7 @@ public static void main(String[] args) { } else { config = ConfigUtils.loadConfig(TEST_CONFIG, RoadPricingUtils.createConfigGroup()); } - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); // "materialize" the road pricing config group: RoadPricingConfigGroup rpConfig = ConfigUtils.addOrGetModule(config, RoadPricingConfigGroup.class); diff --git a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/AvoidTolledRouteTest.java b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/AvoidTolledRouteTest.java index 265164b14b5..2f79155d1e4 100644 --- a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/AvoidTolledRouteTest.java +++ b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/AvoidTolledRouteTest.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.contrib.roadpricing; @@ -40,17 +40,17 @@ import org.matsim.testcases.MatsimTestUtils; /** - * + * * Tests the integration of the roadpricing-package into the Controler. - * + * * Compares a base case (no pricing) against a policy case (link-based pricing) * and tests if all agents adjust their routes in order to avoid the toll payments. - * + * * @author ikaddoura * */ public class AvoidTolledRouteTest { - + @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); @@ -58,68 +58,68 @@ public class AvoidTolledRouteTest { public final void test1(){ String configFile = testUtils.getClassInputDirectory() + "/config.xml"; - + // baseCase Config config1 = ConfigUtils.loadConfig( configFile, RoadPricingUtils.createConfigGroup()); - config1.controler().setOutputDirectory(testUtils.getOutputDirectory() + "bc"); - + config1.controller().setOutputDirectory(testUtils.getOutputDirectory() + "bc"); + Scenario scenario1 = ScenarioUtils.loadScenario(config1); Controler controler1 = new Controler(scenario1); - + final Map,Integer> linkId2demand1 = new HashMap<>(); controler1.getEvents().addHandler(new LinkLeaveEventHandler() { - + @Override public void reset(int iteration) { linkId2demand1.clear(); } - + @Override public void handleEvent(LinkLeaveEvent event) { if (linkId2demand1.containsKey(event.getLinkId())) { int agents = linkId2demand1.get(event.getLinkId()); linkId2demand1.put(event.getLinkId(), agents + 1); - + } else { linkId2demand1.put(event.getLinkId(), 1); - } + } } }); - - controler1.getConfig().controler().setCreateGraphs(false); + + controler1.getConfig().controller().setCreateGraphs(false); controler1.run(); - + // link-based toll Config config2 = ConfigUtils.loadConfig( configFile, RoadPricingUtils.createConfigGroup()); - config2.controler().setOutputDirectory(testUtils.getOutputDirectory() + "cordon"); - + config2.controller().setOutputDirectory(testUtils.getOutputDirectory() + "cordon"); + Scenario scenario2 = ScenarioUtils.loadScenario(config2); Controler controler2 = new Controler(scenario2); controler2.addOverridingModule(new RoadPricingModule()); - + final Map,Integer> linkId2demand2 = new HashMap, Integer>(); controler2.getEvents().addHandler(new LinkLeaveEventHandler() { - + @Override public void reset(int iteration) { linkId2demand2.clear(); } - + @Override public void handleEvent(LinkLeaveEvent event) { if (linkId2demand2.containsKey(event.getLinkId())) { int agents = linkId2demand2.get(event.getLinkId()); linkId2demand2.put(event.getLinkId(), agents + 1); - + } else { linkId2demand2.put(event.getLinkId(), 1); - } + } } }); - - controler2.getConfig().controler().setCreateGraphs(false); + + controler2.getConfig().controller().setCreateGraphs(false); controler2.run(); - + Assert.assertEquals("Base Case: all agents should use the faster route.", 3, (Integer) linkId2demand1.get(Id.createLinkId("link_4_5")), 0); Assert.assertEquals("Pricing: all agents should use the slow but untolled route.", 3, linkId2demand2.get(Id.createLinkId("link_1_2")), 0); diff --git a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/ModuleTest.java b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/ModuleTest.java index 9d6d2066644..118dac01eb9 100644 --- a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/ModuleTest.java +++ b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/ModuleTest.java @@ -67,14 +67,14 @@ public void testControlerWithRoadPricingByScenarioWorks() { @Test public void testControlerWithRoadPricingByScenarioWorksTwice() { Config config = utils.loadConfig(utils.getClassInputDirectory() + "/config.xml"); - config.controler().setOutputDirectory(utils.getOutputDirectory()+"/1"); + config.controller().setOutputDirectory(utils.getOutputDirectory()+"/1"); Scenario scenario = ScenarioUtils.loadScenario(config); Controler controler1 = new Controler(scenario); // controler1.setModules(new RoadPricingModuleDefaults()); controler1.addOverridingModule( new RoadPricingModule() ); controler1.run(); - config.controler().setOutputDirectory(utils.getOutputDirectory()+"/2"); + config.controller().setOutputDirectory(utils.getOutputDirectory()+"/2"); Controler controler2 = new Controler(scenario); controler2.addOverridingModule( new RoadPricingModule() ); // controler2.setModules(new RoadPricingModuleDefaults()); diff --git a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/PlansCalcRouteWithTollOrNotTest.java b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/PlansCalcRouteWithTollOrNotTest.java index f2d0ed25808..df6e547c898 100644 --- a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/PlansCalcRouteWithTollOrNotTest.java +++ b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/PlansCalcRouteWithTollOrNotTest.java @@ -36,7 +36,7 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.api.core.v01.population.Population; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; import org.matsim.core.controler.Injector; import org.matsim.core.controler.NewControlerModule; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -68,17 +68,17 @@ public class PlansCalcRouteWithTollOrNotTest { public MatsimTestUtils matsimTestUtils = new MatsimTestUtils(); /** - * Tests a few cases where the router can decide if it is better to pay the + * Tests a few cases where the router can decide if it is better to pay the * toll or not. */ @Test public void testBestAlternatives() { Config config = matsimTestUtils.createConfig(); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config); RoadPricingTestUtils.createNetwork2(scenario); - log.warn( "access/egress?" + config.plansCalcRoute().getAccessEgressType() ); + log.warn( "access/egress?" + config.routing().getAccessEgressType() ); // a basic toll where only the morning hours are tolled RoadPricingSchemeImpl toll = RoadPricingUtils.addOrGetMutableRoadPricingScheme(scenario ); @@ -97,17 +97,17 @@ public void testBestAlternatives() { Id id1 = Id.createPersonId("1"); // case 1: toll only in morning, it is cheaper to drive around - log.warn( "access/egress?" + config.plansCalcRoute().getAccessEgressType() ); + log.warn( "access/egress?" + config.routing().getAccessEgressType() ); runOnAll(testee(scenario, toll), population); - log.warn( "access/egress?" + config.plansCalcRoute().getAccessEgressType() ); + log.warn( "access/egress?" + config.routing().getAccessEgressType() ); RoadPricingTestUtils.compareRoutes("2 3 4 6", (NetworkRoute) getLeg1(config, population, id1).getRoute()); RoadPricingTestUtils.compareRoutes("8 11 12", (NetworkRoute) getLeg3(config, population, id1).getRoute()); // case 2: now add a toll in the afternoon too, so it is cheaper to pay the toll Cost afternoonCost = toll.createAndAddCost(14*3600, 18*3600, 0.12); - log.warn( "access/egress? " + config.plansCalcRoute().getAccessEgressType() ); + log.warn( "access/egress? " + config.routing().getAccessEgressType() ); runOnAll(testee(scenario, toll), population); - log.warn( "access/egress? " + config.plansCalcRoute().getAccessEgressType() ); + log.warn( "access/egress? " + config.routing().getAccessEgressType() ); RoadPricingTestUtils.compareRoutes("2 5 6", (NetworkRoute) getLeg1(config, population, id1).getRoute()); RoadPricingTestUtils.compareRoutes("8 11 12", (NetworkRoute) getLeg3(config, population, id1).getRoute()); @@ -140,7 +140,7 @@ private static Leg getLeg1(Config config, Population population, Id id1) for ( PlanElement pe : planElements ) { log.warn( pe ); } - if ( config.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + if ( config.routing().getAccessEgressType().equals(AccessEgressType.none) ) { return (Leg) (planElements.get(1)); } else { return (Leg) (planElements.get(3)); @@ -163,11 +163,11 @@ private PlansCalcRouteWithTollOrNot testee(final Scenario scenario, final RoadPr // new ControlerDefaultCoreListenersModule(), // new NewControlerModule()) // .getInstance(PlansCalcRouteWithTollOrNot.class); - + Provider tripRouterProvider = Injector.createInjector(scenario.getConfig(), - new RoadPricingModuleDefaults(toll), + new RoadPricingModuleDefaults(toll), new ScenarioByInstanceModule(scenario), - new ControlerDefaultCoreListenersModule(), + new ControlerDefaultCoreListenersModule(), new NewControlerModule()).getProvider(TripRouter.class); return new PlansCalcRouteWithTollOrNot( toll, tripRouterProvider, TimeInterpretation.create(scenario.getConfig()) ) ; @@ -229,7 +229,7 @@ public void testAllAlternativesTolled() { private static Leg getLeg3(Config config, Population population, Id id1) { List planElements = population.getPersons().get(id1).getPlans().get(0).getPlanElements() ; - if ( config.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + if ( config.routing().getAccessEgressType().equals(AccessEgressType.none) ) { return (Leg) (planElements.get(3)); } else { List trips = TripStructureUtils.getTrips(planElements) ; diff --git a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/RoadPricingControlerIT.java b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/RoadPricingControlerIT.java index a3bb95296bd..e45608b4fbd 100644 --- a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/RoadPricingControlerIT.java +++ b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/RoadPricingControlerIT.java @@ -38,42 +38,42 @@ * @author mrieser */ public class RoadPricingControlerIT { - + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - + @Test public void testPaidTollsEndUpInScores() { // first run basecase Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil-extended"), "config.xml")); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); config.plans().setInputFile("plans1.xml"); - config.controler().setOutputDirectory(utils.getOutputDirectory() + "/basecase/"); - config.controler().setWritePlansInterval(0); + config.controller().setOutputDirectory(utils.getOutputDirectory() + "/basecase/"); + config.controller().setWritePlansInterval(0); Controler controler1 = new Controler(config); - controler1.getConfig().controler().setCreateGraphs(false); - controler1.getConfig().controler().setDumpDataAtEnd(false); - controler1.getConfig().controler().setWriteEventsInterval(0); + controler1.getConfig().controller().setCreateGraphs(false); + controler1.getConfig().controller().setDumpDataAtEnd(false); + controler1.getConfig().controller().setWriteEventsInterval(0); controler1.run(); double scoreBasecase = controler1.getScenario().getPopulation().getPersons().get(Id.create("1", Person.class)).getPlans().get(0).getScore(); - + // now run toll case // ConfigUtils.addOrGetModule(config, RoadPricingConfigGroup.GROUP_NAME, RoadPricingConfigGroup.class).setUseRoadpricing(true); // ConfigUtils.addOrGetModule(config, RoadPricingConfigGroup.GROUP_NAME, RoadPricingConfigGroup.class).setTollLinksFile(IOUtils.newUrl(utils.inputResourcePath(), "distanceToll.xml").toString()); ConfigUtils.addOrGetModule(config, RoadPricingConfigGroup.GROUP_NAME, RoadPricingConfigGroup.class).setTollLinksFile( "distanceToll.xml" ) ; - config.controler().setOutputDirectory(utils.getOutputDirectory() + "/tollcase/"); + config.controller().setOutputDirectory(utils.getOutputDirectory() + "/tollcase/"); Controler controler2 = new Controler(config); /* FIXME Check if the following is correct, jwj '19. What's the difference? */ // controler2.setModules(new RoadPricingModuleDefaults()); controler2.addOverridingModule( new RoadPricingModule() ); - controler2.getConfig().controler().setCreateGraphs(false); - controler2.getConfig().controler().setDumpDataAtEnd(false); - controler2.getConfig().controler().setWriteEventsInterval(0); + controler2.getConfig().controller().setCreateGraphs(false); + controler2.getConfig().controller().setDumpDataAtEnd(false); + controler2.getConfig().controller().setWriteEventsInterval(0); controler2.run(); double scoreTollcase = controler2.getScenario().getPopulation().getPersons().get(Id.create("1", Person.class)).getPlans().get(0).getScore(); - + // there should be a score difference Assert.assertEquals(3.0, scoreBasecase - scoreTollcase, MatsimTestUtils.EPSILON); // toll amount: 10000*0.00020 + 5000*0.00020 } - + } diff --git a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/TollTravelCostCalculatorTest.java b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/TollTravelCostCalculatorTest.java index 4e90d000787..b0c99aab041 100644 --- a/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/TollTravelCostCalculatorTest.java +++ b/contribs/roadpricing/src/test/java/org/matsim/contrib/roadpricing/TollTravelCostCalculatorTest.java @@ -42,7 +42,7 @@ import org.matsim.contrib.roadpricing.RoadPricingSchemeImpl.Cost; 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.ControlerDefaults; import org.matsim.core.population.algorithms.PersonAlgorithm; import org.matsim.core.population.routes.NetworkRoute; @@ -89,7 +89,7 @@ public void testDisutilityResults() { scheme.createAndAddCost(0, 10*3600, 0.0007); - TravelTime timeCalculator = new FreespeedTravelTimeAndDisutility(config.planCalcScore()); + TravelTime timeCalculator = new FreespeedTravelTimeAndDisutility(config.scoring()); double margUtlOfMoney = 1. ; final TravelDisutilityFactory defaultDisutilityFactory = ControlerDefaults.createDefaultTravelDisutilityFactory(scenario); @@ -135,7 +135,7 @@ public void testDistanceTollRouter() { toll.addLink(Id.create("11", Link.class)); RoadPricingTestUtils.createPopulation2(scenario); Population population = scenario.getPopulation(); - TravelTime timeCalc = new FreespeedTravelTimeAndDisutility(config.planCalcScore()); + TravelTime timeCalc = new FreespeedTravelTimeAndDisutility(config.scoring()); // yy note: this returns a combined TravelTime and TravelDisutility object. The TravelDisutility object is used in the next three lines to be wrapped, // and then never again. Would be nice to be able to get them separately ... kai, oct'13 @@ -147,7 +147,7 @@ public void testDistanceTollRouter() { commonRouterData.run(network); int carLegIndex = 1 ; - if ( !config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { carLegIndex = 3 ; } @@ -220,7 +220,7 @@ public void testLinkTollRouter() { toll.addLink(Id.create("11", Link.class)); RoadPricingTestUtils.createPopulation2(scenario); Population population = scenario.getPopulation(); - FreespeedTravelTimeAndDisutility timeCostCalc = new FreespeedTravelTimeAndDisutility(config.planCalcScore()); + FreespeedTravelTimeAndDisutility timeCostCalc = new FreespeedTravelTimeAndDisutility(config.scoring()); TravelDisutility costCalc = new TravelDisutilityIncludingToll(timeCostCalc, toll, config); // we use freespeedTravelCosts as base costs AStarLandmarksFactory routerFactory = new AStarLandmarksFactory(2); @@ -229,7 +229,7 @@ public void testLinkTollRouter() { commonRouterData.run(network); int carLegIndex = 1 ; - if (! config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if (! config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { carLegIndex = 3 ; } @@ -316,13 +316,13 @@ public void testCordonTollRouter() { toll.addLink(Id.create("11", Link.class)); RoadPricingTestUtils.createPopulation2(scenario); Population population = scenario.getPopulation(); - FreespeedTravelTimeAndDisutility timeCostCalc = new FreespeedTravelTimeAndDisutility(config.planCalcScore()); + FreespeedTravelTimeAndDisutility timeCostCalc = new FreespeedTravelTimeAndDisutility(config.scoring()); TravelDisutility costCalc = new TravelDisutilityIncludingToll(timeCostCalc, toll, config); // we use freespeedTravelCosts as base costs AStarLandmarksFactory routerFactory = new AStarLandmarksFactory(2); int carLegIndex = 1 ; - if ( !config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { carLegIndex = 3 ; } diff --git a/contribs/roadpricing/test/input/org/matsim/contrib/roadpricing/run/RoadPricingByConfigfileTest/testMain/output_events.xml.gz b/contribs/roadpricing/test/input/org/matsim/contrib/roadpricing/run/RoadPricingByConfigfileTest/testMain/output_events.xml.gz index 4be81d33278..cdef4d42023 100644 Binary files a/contribs/roadpricing/test/input/org/matsim/contrib/roadpricing/run/RoadPricingByConfigfileTest/testMain/output_events.xml.gz and b/contribs/roadpricing/test/input/org/matsim/contrib/roadpricing/run/RoadPricingByConfigfileTest/testMain/output_events.xml.gz differ diff --git a/contribs/roadpricing/test/input/org/matsim/contrib/roadpricing/run/RoadPricingByConfigfileTest/testMain/output_plans.xml.gz b/contribs/roadpricing/test/input/org/matsim/contrib/roadpricing/run/RoadPricingByConfigfileTest/testMain/output_plans.xml.gz index da6affd458d..65c83679568 100644 Binary files a/contribs/roadpricing/test/input/org/matsim/contrib/roadpricing/run/RoadPricingByConfigfileTest/testMain/output_plans.xml.gz and b/contribs/roadpricing/test/input/org/matsim/contrib/roadpricing/run/RoadPricingByConfigfileTest/testMain/output_plans.xml.gz differ diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/RunSBBExtension.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/RunSBBExtension.java index dc0163d4b5a..9176cb181fc 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/RunSBBExtension.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/RunSBBExtension.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim; import ch.sbb.matsim.mobsim.qsim.SBBTransitModule; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/BeelineDistanceMatrix.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/BeelineDistanceMatrix.java index aaf9a280f9c..a665bff984d 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/BeelineDistanceMatrix.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/BeelineDistanceMatrix.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import java.util.Map; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java index c3ec95d33aa..f4d8494dbed 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import ch.sbb.matsim.analysis.skims.NetworkSkimMatrices.NetworkIndicators; @@ -175,7 +190,7 @@ public static void main(String[] args) throws IOException { "", (line, route) -> route.getTransportMode().equals("train")); } - + skims.calculateAndWriteBeelineMatrix(); } diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/FloatMatrix.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/FloatMatrix.java index a8c79473186..9ed2b13025b 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/FloatMatrix.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/FloatMatrix.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import java.util.Arrays; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/FloatMatrixIO.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/FloatMatrixIO.java index bfb6ce901a4..936b3d68122 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/FloatMatrixIO.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/FloatMatrixIO.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import java.io.BufferedReader; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/MatricesToXY.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/MatricesToXY.java index 7d42ac60c4e..1facd37be1e 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/MatricesToXY.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/MatricesToXY.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import java.io.BufferedWriter; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/NetworkSkimMatrices.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/NetworkSkimMatrices.java index 6470e231043..afc16f51ec0 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/NetworkSkimMatrices.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/NetworkSkimMatrices.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import org.matsim.core.router.speedy.SpeedyGraph; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/PTSkimMatrices.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/PTSkimMatrices.java index 1916ddbd263..56121f8558a 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/PTSkimMatrices.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/PTSkimMatrices.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import ch.sbb.matsim.analysis.skims.RooftopUtils.ODConnection; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/RooftopUtils.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/RooftopUtils.java index f7937b6d763..809f4582a65 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/RooftopUtils.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/RooftopUtils.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorCore.TravelInfo; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/StreamingFacilities.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/StreamingFacilities.java index a2e9833d342..d75de1a5080 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/StreamingFacilities.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/StreamingFacilities.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import org.matsim.api.core.v01.Id; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/config/SBBTransitConfigGroup.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/config/SBBTransitConfigGroup.java index 24abf75a992..f78b3caaf93 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/config/SBBTransitConfigGroup.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/config/SBBTransitConfigGroup.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.config; import java.util.HashSet; @@ -20,7 +35,7 @@ public class SBBTransitConfigGroup extends ReflectiveConfigGroup { static private final String PARAM_DETERMINISTIC_SERVICE_MODES = "deterministicServiceModes"; static private final String PARAM_CREATE_LINK_EVENTS_INTERVAL = "createLinkEventsInterval"; - private Set deterministicServiceModes = new HashSet<>(); + private final Set deterministicServiceModes = new HashSet<>(); private int createLinkEventsInterval = 0; public SBBTransitConfigGroup() { diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/SBBTransitModule.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/SBBTransitModule.java index 81fd1456970..8b43874f104 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/SBBTransitModule.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/SBBTransitModule.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim; import ch.sbb.matsim.config.SBBTransitConfigGroup; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBPassengerAccessEgress.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBPassengerAccessEgress.java index bb67c1ee09e..d7c0f0ffc9e 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBPassengerAccessEgress.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBPassengerAccessEgress.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim.pt; import java.util.ArrayList; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitDriverAgent.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitDriverAgent.java index 4b1ce4be675..7674797dd28 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitDriverAgent.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitDriverAgent.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim.pt; import java.util.LinkedList; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitDriverAgentFactory.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitDriverAgentFactory.java index e5c7ac247af..bf4e3c6d719 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitDriverAgentFactory.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitDriverAgentFactory.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim.pt; import java.util.Set; @@ -18,23 +33,19 @@ */ public class SBBTransitDriverAgentFactory implements TransitDriverAgentFactory { - private final InternalInterface internalInterface; - private final TransitStopAgentTracker transitStopAgentTracker; private final Set deterministicModes; - SBBTransitDriverAgentFactory(InternalInterface internalInterface, TransitStopAgentTracker transitStopAgentTracker, Set deterministicModes) { - this.internalInterface = internalInterface; - this.transitStopAgentTracker = transitStopAgentTracker; + SBBTransitDriverAgentFactory(Set deterministicModes) { this.deterministicModes = deterministicModes; } @Override - public AbstractTransitDriverAgent createTransitDriver(Umlauf umlauf) { + public AbstractTransitDriverAgent createTransitDriver(Umlauf umlauf, InternalInterface internalInterface, TransitStopAgentTracker transitStopAgentTracker) { String mode = umlauf.getUmlaufStuecke().get(0).getRoute().getTransportMode(); if (this.deterministicModes.contains(mode)) { - return new SBBTransitDriverAgent(umlauf, mode, this.transitStopAgentTracker, this.internalInterface); + return new SBBTransitDriverAgent(umlauf, mode,transitStopAgentTracker, internalInterface); } - return new TransitDriverAgentImpl(umlauf, TransportMode.car, this.transitStopAgentTracker, this.internalInterface); + return new TransitDriverAgentImpl(umlauf, TransportMode.car, transitStopAgentTracker, internalInterface); } } diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitEngineQSimModule.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitEngineQSimModule.java index 30753a4a576..c05b7852bab 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitEngineQSimModule.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitEngineQSimModule.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim.pt; import org.matsim.core.mobsim.qsim.AbstractQSimModule; diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngine.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngine.java index 96efff76eaf..9e8ccf83ee6 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngine.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngine.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim.pt; import ch.sbb.matsim.config.SBBTransitConfigGroup; @@ -83,14 +98,14 @@ public class SBBTransitQSimEngine extends TransitQSimEngine /*implements Departu private boolean createLinkEvents = false; @Inject - public SBBTransitQSimEngine(QSim qSim, ReplanningContext context) { - super(qSim, new SimpleTransitStopHandlerFactory(), new ReconstructingUmlaufBuilder(qSim.getScenario())); + public SBBTransitQSimEngine(QSim qSim, ReplanningContext context, TransitStopAgentTracker agentTracker, TransitDriverAgentFactory networkDriverFactory) { + super(qSim, new SimpleTransitStopHandlerFactory(), new ReconstructingUmlaufBuilder(qSim.getScenario()), agentTracker, networkDriverFactory); this.qSim = qSim; this.context = context; this.config = ConfigUtils.addOrGetModule(qSim.getScenario().getConfig(), SBBTransitConfigGroup.GROUP_NAME, SBBTransitConfigGroup.class); this.ptConfig = qSim.getScenario().getConfig().transit(); this.schedule = qSim.getScenario().getTransitSchedule(); - this.agentTracker = new TransitStopAgentTracker(qSim.getEventsManager()); + this.agentTracker = agentTracker; if (this.config.getCreateLinkEventsInterval() > 0) { this.linkEventQueue = new PriorityQueue<>(); this.linksCache = new ConcurrentHashMap<>(); @@ -116,8 +131,8 @@ public void setTransitStopHandlerFactory(final TransitStopHandlerFactory stopHan @Override public void setInternalInterface(InternalInterface internalInterface) { this.internalInterface = internalInterface; - this.deterministicDriverFactory = new SBBTransitDriverAgentFactory(internalInterface, this.agentTracker, this.config.getDeterministicServiceModes()); - this.networkDriverFactory = new DefaultTransitDriverAgentFactory(internalInterface, this.agentTracker); + this.deterministicDriverFactory = new SBBTransitDriverAgentFactory(this.config.getDeterministicServiceModes()); + this.networkDriverFactory = new DefaultTransitDriverAgentFactory(); } @Override @@ -230,9 +245,9 @@ private void createVehiclesAndDrivers() { private void createAndScheduleDriver(Vehicle veh, Umlauf umlauf, boolean isDeterministic) { AbstractTransitDriverAgent driver; if (isDeterministic) { - driver = this.deterministicDriverFactory.createTransitDriver(umlauf); + driver = this.deterministicDriverFactory.createTransitDriver(umlauf, internalInterface, agentTracker); } else { - driver = this.networkDriverFactory.createTransitDriver(umlauf); + driver = this.networkDriverFactory.createTransitDriver(umlauf, internalInterface, agentTracker); } TransitQVehicle qVeh = new TransitQVehicle(veh); qVeh.setDriver(driver); diff --git a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/analysis/skims/FloatMatrixIOTest.java b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/analysis/skims/FloatMatrixIOTest.java index a3f0ff2e822..1eb96dd4e35 100644 --- a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/analysis/skims/FloatMatrixIOTest.java +++ b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/analysis/skims/FloatMatrixIOTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import java.io.ByteArrayInputStream; @@ -55,4 +70,4 @@ public void testIO() throws IOException { Assert.assertEquals(27.0f, matrix2.get("tres", "dos"), epsilon); Assert.assertEquals(64.0f, matrix2.get("tres", "tres"), epsilon); } -} \ No newline at end of file +} diff --git a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/analysis/skims/RooftopUtilsTest.java b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/analysis/skims/RooftopUtilsTest.java index 560ff62468c..7f42f0b8f0b 100644 --- a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/analysis/skims/RooftopUtilsTest.java +++ b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/analysis/skims/RooftopUtilsTest.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.analysis.skims; import ch.sbb.matsim.analysis.skims.RooftopUtils.ODConnection; @@ -410,4 +429,4 @@ public void testCalculationShares_singleDepartureLate() { Map shares = RooftopUtils.calcConnectionShares(connections, Time.parseTime("07:00:00"), Time.parseTime("08:00:00")); Assert.assertEquals(1.0, shares.get(c0), 1e-7); } -} \ No newline at end of file +} diff --git a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/config/SBBTransitConfigGroupTest.java b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/config/SBBTransitConfigGroupTest.java index 49e81b819a0..5624833ef10 100644 --- a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/config/SBBTransitConfigGroupTest.java +++ b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/config/SBBTransitConfigGroupTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.config; import java.io.ByteArrayInputStream; diff --git a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/SBBQSimModuleTest.java b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/SBBQSimModuleTest.java index f647d8449a1..59043264ed7 100644 --- a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/SBBQSimModuleTest.java +++ b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/SBBQSimModuleTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim; import ch.sbb.matsim.config.SBBTransitConfigGroup; @@ -55,7 +70,7 @@ public void testIntegration() { Config config = ConfigUtils.createConfig(); new ConfigReader(config).parse(new ByteArrayInputStream(xmlConfig.getBytes(StandardCharsets.UTF_8))); - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); Scenario scenario = ScenarioUtils.createScenario(config); Controler controler = new Controler(scenario); @@ -83,4 +98,4 @@ QSimComponentsConfig provideQSimComponentsConfig() { Assert.assertTrue(config.getModules().get(SBBTransitConfigGroup.GROUP_NAME) instanceof SBBTransitConfigGroup); } -} \ No newline at end of file +} diff --git a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngineIntegrationTest.java b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngineIntegrationTest.java index ee97222a5a2..579f960e19b 100644 --- a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngineIntegrationTest.java +++ b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngineIntegrationTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim.pt; import ch.sbb.matsim.mobsim.qsim.SBBTransitModule; @@ -31,8 +46,8 @@ public class SBBTransitQSimEngineIntegrationTest { public void testIntegration() { TestFixture f = new TestFixture(); - f.config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - f.config.controler().setLastIteration(0); + f.config.controller().setOutputDirectory(this.utils.getOutputDirectory()); + f.config.controller().setLastIteration(0); Controler controler = new Controler(f.scenario); controler.addOverridingModule(new SBBTransitModule()); @@ -60,8 +75,8 @@ public void testIntegration_misconfiguration() { mainModes.add("car"); mainModes.add("train"); f.config.qsim().setMainModes(mainModes); - f.config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - f.config.controler().setLastIteration(0); + f.config.controller().setOutputDirectory(this.utils.getOutputDirectory()); + f.config.controller().setLastIteration(0); Controler controler = new Controler(f.scenario); controler.addOverridingModule(new SBBTransitModule()); diff --git a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngineTest.java b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngineTest.java index 1fb69377aee..d80dc5793d5 100644 --- a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngineTest.java +++ b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/SBBTransitQSimEngineTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim.pt; import java.util.List; @@ -34,6 +49,8 @@ import org.matsim.core.mobsim.qsim.PopulationModule; import org.matsim.core.mobsim.qsim.QSim; import org.matsim.core.mobsim.qsim.QSimBuilder; +import org.matsim.core.mobsim.qsim.pt.DefaultTransitDriverAgentFactory; +import org.matsim.core.mobsim.qsim.pt.TransitStopAgentTracker; import org.matsim.core.utils.collections.CollectionUtils; import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.pt.transitSchedule.api.TransitRouteStop; @@ -58,7 +75,7 @@ public void testDriver() { EventsManager eventsManager = EventsUtils.createEventsManager(f.config); QSim qSim = new QSimBuilder(f.config).useDefaults().build(f.scenario, eventsManager); - SBBTransitQSimEngine trEngine = new SBBTransitQSimEngine(qSim, null); + SBBTransitQSimEngine trEngine = new SBBTransitQSimEngine(qSim, null, new TransitStopAgentTracker(eventsManager), new DefaultTransitDriverAgentFactory()); qSim.addMobsimEngine(trEngine); trEngine.insertAgentsIntoMobsim(); diff --git a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/TestFixture.java b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/TestFixture.java index 030d3cc43b8..5e497fe5165 100644 --- a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/TestFixture.java +++ b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/TestFixture.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim.pt; import ch.sbb.matsim.config.SBBTransitConfigGroup; diff --git a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/TestQSimModule.java b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/TestQSimModule.java index f57e5e54ab6..668b6662288 100644 --- a/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/TestQSimModule.java +++ b/contribs/sbb-extensions/src/test/java/ch/sbb/matsim/mobsim/qsim/pt/TestQSimModule.java @@ -1,13 +1,31 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.mobsim.qsim.pt; +import com.google.inject.Provides; +import com.google.inject.Singleton; import org.matsim.core.config.Config; +import org.matsim.core.events.EventsUtils; import org.matsim.core.mobsim.qsim.AbstractQSimModule; -import org.matsim.core.mobsim.qsim.pt.ComplexTransitStopHandlerFactory; -import org.matsim.core.mobsim.qsim.pt.TransitStopHandlerFactory; +import org.matsim.core.mobsim.qsim.QSim; +import org.matsim.core.mobsim.qsim.pt.*; import org.matsim.core.replanning.ReplanningContext; /** @@ -29,8 +47,15 @@ public TestQSimModule(Config config) { protected void configureQSim() { bind(ReplanningContext.class).toInstance(context); bind(TransitStopHandlerFactory.class).to(ComplexTransitStopHandlerFactory.class); + bind(TransitDriverAgentFactory.class).to(DefaultTransitDriverAgentFactory.class); } + @Provides + @Singleton + public TransitStopAgentTracker transitStopAgentTracker(QSim qSim) { + return new TransitStopAgentTracker(qSim.getEventsManager()); + } + public static final class DummyReplanningContext implements ReplanningContext { private int iteration = 0; diff --git a/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunCarsharing.java b/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunCarsharing.java index 114870703bf..79a013fd40e 100644 --- a/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunCarsharing.java +++ b/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunCarsharing.java @@ -13,11 +13,11 @@ import org.matsim.core.config.CommandLine.ConfigurationException; 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.controler.Controler; /** - * + * * This is an example of a station-based oneway car-sharing service * siouxfalls-2014 can be used to run the simulation with the provided example * input file in the resources/example * @@ -61,24 +61,24 @@ static public void main(String[] args) throws ConfigurationException { // We need to add interaction activity types to scoring ActivityParams pickupParams = new ActivityParams(SharingUtils.PICKUP_ACTIVITY); pickupParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(pickupParams); + config.scoring().addActivityParams(pickupParams); ActivityParams dropoffParams = new ActivityParams(SharingUtils.DROPOFF_ACTIVITY); dropoffParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(dropoffParams); - + config.scoring().addActivityParams(dropoffParams); + ActivityParams bookingParams = new ActivityParams(SharingUtils.BOOKING_ACTIVITY); bookingParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(bookingParams); + config.scoring().addActivityParams(bookingParams); // We need to score car ModeParams carScoringParams = new ModeParams("car"); - config.planCalcScore().addModeParams(carScoringParams); + config.scoring().addModeParams(carScoringParams); // Write out all events (DEBUG) - config.controler().setWriteEventsInterval(1); - config.controler().setWritePlansInterval(1); - config.controler().setLastIteration(10); + config.controller().setWriteEventsInterval(1); + config.controller().setWritePlansInterval(1); + config.controller().setLastIteration(10); // Set up controller (no specific settings needed for scenario) Controler controller = new Controler(config); diff --git a/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunParisVelib.java b/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunParisVelib.java index f5625e1445d..1de6a4f161c 100644 --- a/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunParisVelib.java +++ b/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunParisVelib.java @@ -13,8 +13,8 @@ import org.matsim.core.config.CommandLine.ConfigurationException; 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.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.Controler; public class RunParisVelib { @@ -56,15 +56,15 @@ static public void main(String[] args) throws ConfigurationException { // We need to add interaction activity types to scoring ActivityParams pickupParams = new ActivityParams(SharingUtils.PICKUP_ACTIVITY); pickupParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(pickupParams); + config.scoring().addActivityParams(pickupParams); ActivityParams dropoffParams = new ActivityParams(SharingUtils.DROPOFF_ACTIVITY); dropoffParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(dropoffParams); + config.scoring().addActivityParams(dropoffParams); ActivityParams bookingParams = new ActivityParams(SharingUtils.BOOKING_ACTIVITY); bookingParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(bookingParams); + config.scoring().addActivityParams(bookingParams); { // Remove some standard eqasim config groups @@ -74,7 +74,7 @@ static public void main(String[] args) throws ConfigurationException { // Replace some standard eqasim settings - for (StrategySettings strategy : config.strategy().getStrategySettings()) { + for (StrategySettings strategy : config.replanning().getStrategySettings()) { if (strategy.getStrategyName().equals("DiscreteModeChoice")) { strategy.setStrategyName("SubtourModeChoice"); } else if (strategy.getStrategyName().equals("KeepLastSelected")) { @@ -82,15 +82,15 @@ static public void main(String[] args) throws ConfigurationException { } } - config.strategy().setPlanSelectorForRemoval("WorstPlanSelector"); + config.replanning().setPlanSelectorForRemoval("WorstPlanSelector"); config.transit().setUseTransit(true); config.transit().setUsingTransitInMobsim(true); } // Write out all events (DEBUG) - config.controler().setWriteEventsInterval(1); - config.controler().setWritePlansInterval(1); - config.controler().setLastIteration(10); + config.controller().setWriteEventsInterval(1); + config.controller().setWritePlansInterval(1); + config.controller().setLastIteration(10); // Set up controller (no specific settings needed for scenario) Controler controller = new Controler(config); diff --git a/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunTeleportationBikesharing.java b/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunTeleportationBikesharing.java index 7d1c01f0ec1..1bdaee4a8b8 100644 --- a/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunTeleportationBikesharing.java +++ b/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/examples/RunTeleportationBikesharing.java @@ -13,9 +13,9 @@ import org.matsim.core.config.CommandLine.ConfigurationException; 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.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.Controler; /** @@ -34,16 +34,16 @@ static public void main(String[] args) throws ConfigurationException { Config config = ConfigUtils.loadConfig(cmd.getOptionStrict("config-path")); // We define bike to be routed based on Euclidean distance. - PlansCalcRouteConfigGroup.TeleportedModeParams bikeRoutingParams = new PlansCalcRouteConfigGroup.TeleportedModeParams("bike"); + RoutingConfigGroup.TeleportedModeParams bikeRoutingParams = new RoutingConfigGroup.TeleportedModeParams("bike"); bikeRoutingParams.setTeleportedModeSpeed(5.0); bikeRoutingParams.setBeelineDistanceFactor(1.3); - config.plansCalcRoute().addTeleportedModeParams(bikeRoutingParams); + config.routing().addTeleportedModeParams(bikeRoutingParams); // Walk is deleted by adding bike here, we need to re-add it ... - PlansCalcRouteConfigGroup.TeleportedModeParams walkRoutingParams = new PlansCalcRouteConfigGroup.TeleportedModeParams("walk"); + RoutingConfigGroup.TeleportedModeParams walkRoutingParams = new RoutingConfigGroup.TeleportedModeParams("walk"); walkRoutingParams.setTeleportedModeSpeed(2.0); walkRoutingParams.setBeelineDistanceFactor(1.3); - config.plansCalcRoute().addTeleportedModeParams(walkRoutingParams); + config.routing().addTeleportedModeParams(walkRoutingParams); // By default, "bike" will be simulated using teleportation. @@ -79,24 +79,24 @@ static public void main(String[] args) throws ConfigurationException { // We need to add interaction activity types to scoring ActivityParams pickupParams = new ActivityParams(SharingUtils.PICKUP_ACTIVITY); pickupParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(pickupParams); + config.scoring().addActivityParams(pickupParams); ActivityParams dropoffParams = new ActivityParams(SharingUtils.DROPOFF_ACTIVITY); dropoffParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(dropoffParams); + config.scoring().addActivityParams(dropoffParams); ActivityParams bookingParams = new ActivityParams(SharingUtils.BOOKING_ACTIVITY); bookingParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(bookingParams); + config.scoring().addActivityParams(bookingParams); // We need to score bike ModeParams bikeScoringParams = new ModeParams("bike"); - config.planCalcScore().addModeParams(bikeScoringParams); + config.scoring().addModeParams(bikeScoringParams); // Write out all events (DEBUG) - config.controler().setWriteEventsInterval(1); - config.controler().setWritePlansInterval(1); - config.controler().setLastIteration(10); + config.controller().setWriteEventsInterval(1); + config.controller().setWritePlansInterval(1); + config.controller().setLastIteration(10); // Set up controller (no specific settings needed for scenario) Controler controller = new Controler(config); diff --git a/contribs/shared_mobility/src/test/java/org/matsim/contrib/shared_mobility/RunIT.java b/contribs/shared_mobility/src/test/java/org/matsim/contrib/shared_mobility/RunIT.java index a7279182dc9..4afd46b468d 100644 --- a/contribs/shared_mobility/src/test/java/org/matsim/contrib/shared_mobility/RunIT.java +++ b/contribs/shared_mobility/src/test/java/org/matsim/contrib/shared_mobility/RunIT.java @@ -1,5 +1,6 @@ package org.matsim.contrib.shared_mobility; +import java.io.UncheckedIOException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; @@ -26,13 +27,12 @@ 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.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.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.examples.ExamplesUtils; public class RunIT { @@ -43,9 +43,9 @@ public final void test() throws UncheckedIOException, ConfigurationException, UR Config config = ConfigUtils.loadConfig(ConfigGroup.getInputFileURL(scenarioUrl, "config_default.xml")); - config.controler().setLastIteration(2); + config.controller().setLastIteration(2); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); // We need to add the sharing config group SharingConfigGroup sharingConfig = new SharingConfigGroup(); config.addModule(sharingConfig); @@ -126,23 +126,23 @@ public final void test() throws UncheckedIOException, ConfigurationException, UR // We need to add interaction activity types to scoring ActivityParams pickupParams = new ActivityParams(SharingUtils.PICKUP_ACTIVITY); pickupParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(pickupParams); + config.scoring().addActivityParams(pickupParams); ActivityParams dropoffParams = new ActivityParams(SharingUtils.DROPOFF_ACTIVITY); dropoffParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(dropoffParams); + config.scoring().addActivityParams(dropoffParams); ActivityParams bookingParams = new ActivityParams(SharingUtils.BOOKING_ACTIVITY); bookingParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(bookingParams); + config.scoring().addActivityParams(bookingParams); // We need to score car ModeParams carScoringParams = new ModeParams("car"); - config.planCalcScore().addModeParams(carScoringParams); + config.scoring().addModeParams(carScoringParams); // We need to score bike ModeParams bikeScoringParams = new ModeParams("bike"); - config.planCalcScore().addModeParams(bikeScoringParams); + config.scoring().addModeParams(bikeScoringParams); // Set up controller (no specific settings needed for scenario) Controler controller = new Controler(config); @@ -157,18 +157,18 @@ public final void test() throws UncheckedIOException, ConfigurationException, UR OutputData data = countLegs(controller.getControlerIO().getOutputPath() + "/output_events.xml.gz"); - Assert.assertEquals(82689, (long) data.counts.get("car")); - Assert.assertEquals(29890, (long) data.counts.get("walk")); - Assert.assertEquals(30, (long) data.counts.get("bike")); - Assert.assertEquals(19115, (long) data.counts.get("pt")); + Assert.assertEquals(82629, (long) data.counts.get("car")); + Assert.assertEquals(29739, (long) data.counts.get("walk")); + Assert.assertEquals(31, (long) data.counts.get("bike")); + Assert.assertEquals(19029, (long) data.counts.get("pt")); Assert.assertEquals(21, (long) data.pickupCounts.get("wheels")); Assert.assertEquals(2, (long) data.pickupCounts.get("mobility")); - Assert.assertEquals(9, (long) data.pickupCounts.get("velib")); + Assert.assertEquals(10, (long) data.pickupCounts.get("velib")); Assert.assertEquals(21, (long) data.dropoffCounts.get("wheels")); Assert.assertEquals(0, (long) data.dropoffCounts.getOrDefault("mobility", 0L)); - Assert.assertEquals(9, (long) data.dropoffCounts.get("velib")); + Assert.assertEquals(10, (long) data.dropoffCounts.get("velib")); Assert.assertEquals(0, (long) data.failedPickupCounts.getOrDefault("wheels",0L)); Assert.assertEquals(0, (long) data.failedPickupCounts.getOrDefault("mobility",0L)); diff --git a/contribs/signals/examples/tutorial/example90TrafficLights/useSignalInput/withLanes/config.xml b/contribs/signals/examples/tutorial/example90TrafficLights/useSignalInput/withLanes/config.xml index d77841bccdb..7dd3d3f36ca 100644 --- a/contribs/signals/examples/tutorial/example90TrafficLights/useSignalInput/withLanes/config.xml +++ b/contribs/signals/examples/tutorial/example90TrafficLights/useSignalInput/withLanes/config.xml @@ -2,18 +2,6 @@ - - - - - - - - - - - - @@ -55,7 +43,7 @@ - @@ -65,7 +53,7 @@ - + @@ -234,7 +222,7 @@ - + @@ -507,35 +495,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -650,7 +609,7 @@ - + @@ -663,7 +622,7 @@ - + @@ -760,9 +719,6 @@ - - - diff --git a/contribs/signals/examples/tutorial/example90TrafficLights/useSignalInput/woLanes/config.xml b/contribs/signals/examples/tutorial/example90TrafficLights/useSignalInput/woLanes/config.xml index cf4e7db82ab..fb9df9f07f9 100644 --- a/contribs/signals/examples/tutorial/example90TrafficLights/useSignalInput/woLanes/config.xml +++ b/contribs/signals/examples/tutorial/example90TrafficLights/useSignalInput/woLanes/config.xml @@ -2,18 +2,6 @@ - - - - - - - - - - - - @@ -55,7 +43,7 @@ - @@ -65,7 +53,7 @@ - + @@ -234,7 +222,7 @@ - + @@ -249,7 +237,7 @@ - + @@ -507,35 +495,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -734,9 +693,6 @@ - - - diff --git a/contribs/signals/src/main/java/org/matsim/codeexamples/adaptiveSignals/RunAdaptiveSignalsExample.java b/contribs/signals/src/main/java/org/matsim/codeexamples/adaptiveSignals/RunAdaptiveSignalsExample.java index 11fd915ebda..4511e4d41b2 100644 --- a/contribs/signals/src/main/java/org/matsim/codeexamples/adaptiveSignals/RunAdaptiveSignalsExample.java +++ b/contribs/signals/src/main/java/org/matsim/codeexamples/adaptiveSignals/RunAdaptiveSignalsExample.java @@ -23,16 +23,16 @@ * intersection is signalized by traffic-adaptive signals. The logic of the * traffic-adaptive signals is based on the basic version of Stefan Laemmer from * his phd from 2007 and can be found in LaemmerSignalController. - * + * * If you want to use other implementations of traffic-adaptive signals you have * to adjust the identifiers in the signal control file and add a factory class * for your specific implementation to the SignalsModule (see comment below). - * + * * @author tthunig */ public class RunAdaptiveSignalsExample { // do not change name of class; EWGT-paper (ThunigKuehnelNagel2018...) refers to it. theresa, aug'18 - + private static final Logger log = LogManager.getLogger(RunAdaptiveSignalsExample.class); public static void main(String[] args) { @@ -43,27 +43,27 @@ public static void main(String[] args) { } run(configFileName, "output/runAdaptiveSignalsExampleOutput/", true); // The run method is extracted so that a test can operate on it. } - + public static void run(String configFileName, String outputDir, boolean visualize) { - + Config config = ConfigUtils.loadConfig(configFileName) ; - - config.controler().setOutputDirectory(outputDir); - + + config.controller().setOutputDirectory(outputDir); + // adjustments for live visualization OTFVisConfigGroup otfvisConfig = ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.class); otfvisConfig.setDrawTime(true); config.qsim().setSnapshotStyle(QSimConfigGroup.SnapshotStyle.withHoles); Scenario scenario = ScenarioUtils.loadScenario( config ) ; - + SignalSystemsConfigGroup signalsConfigGroup = ConfigUtils.addOrGetModule(config, SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class); - + if (signalsConfigGroup.isUseSignalSystems()) { scenario.addScenarioElement(SignalsData.ELEMENT_NAME, new SignalsDataLoader(config).loadSignalsData()); } - + // here are some examples how to change parameters for the laemmer control LaemmerConfigGroup laemmerConfigGroup = ConfigUtils.addOrGetModule(config, LaemmerConfigGroup.GROUP_NAME, LaemmerConfigGroup.class); @@ -71,9 +71,9 @@ public static void run(String configFileName, String outputDir, boolean visualiz laemmerConfigGroup.setDesiredCycleTime(90); laemmerConfigGroup.setMinGreenTime(5); // ... - + Controler controler = new Controler( scenario ); - + // add the signals extension to the simulation if signal systems are enabled in the config if (signalsConfigGroup.isUseSignalSystems()) { Signals.configure( controler ); @@ -87,22 +87,22 @@ public static void run(String configFileName, String outputDir, boolean visualiz * Signals.configure( controler ); */ } - + // add live visualization module - if (visualize) { + if (visualize) { controler.addOverridingModule(new OTFVisWithSignalsLiveModule()); } - - controler.addOverridingModule(new AbstractModule() { + + controler.addOverridingModule(new AbstractModule() { @Override public void install() { // add analysis tools here if you like // ... } }); - + controler.run(); - + } - + } diff --git a/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExample.java b/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExample.java index b7a22bfa0d1..71920b51e3e 100644 --- a/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExample.java +++ b/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExample.java @@ -35,7 +35,7 @@ /** * Minimal example how to start your matsim run with traffic signals - * + * * @author tthunig */ public class RunSignalSystemsExample { @@ -44,28 +44,28 @@ public class RunSignalSystemsExample { /** * @param args the path to your config file */ - public static void main(String[] args) { + public static void main(String[] args) { Config config; if (args.length==0 || args.length>1) { // --- create a config for the example scenario config = ConfigUtils.loadConfig("./examples/tutorial/example90TrafficLights/useSignalInput/withLanes/config.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory("output/runSignalSystemsExample/"); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory("output/runSignalSystemsExample/"); } else { // --- create a config from the arguments you provided config = ConfigUtils.loadConfig(args[0]); } - + run(config, true); // The run method is extracted so that a test can operate on it. } - + public static void run(Config config, boolean visualize) { // adjustments for live visualization OTFVisConfigGroup otfvisConfig = ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.class); otfvisConfig.setDrawTime(true); config.qsim().setSnapshotStyle(QSimConfigGroup.SnapshotStyle.withHoles); - + // --- create the scenario Scenario scenario = ScenarioUtils.loadScenario(config); // load the information about signals data (i.e. fill the SignalsData object) and add it to the scenario as scenario element @@ -81,7 +81,7 @@ public static void run(Config config, boolean visualize) { if (visualize) { c.addOverridingModule(new OTFVisWithSignalsLiveModule()); } - + // --- run the simulation c.run(); } diff --git a/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExampleWithHoles.java b/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExampleWithHoles.java index 1a07422a619..768283ca922 100644 --- a/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExampleWithHoles.java +++ b/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExampleWithHoles.java @@ -40,12 +40,12 @@ /** * Configures and runs MATSim with traffic signals from input files - * and visualizes it with OTFVis. - * + * and visualizes it with OTFVis. + * * @author dgrether, tthunig */ public class RunSignalSystemsExampleWithHoles { - + public static void main(String[] args) { run(true); } @@ -53,24 +53,24 @@ public static void main(String[] args) { static void run(boolean useOTFVis) { // load a config (without signal information) Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil-extended"), "config.xml")); - config.controler().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists); - + config.controller().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists); + // use higher values if you want to iterate - config.controler().setLastIteration(0); - + config.controller().setLastIteration(0); + config.network().setInputFile("network.xml"); config.plans().setInputFile("plans2000.xml.gz"); - + // simulate traffic dynamics with holes (default would be without) config.qsim().setTrafficDynamics(TrafficDynamics.withHoles); config.qsim().setSnapshotStyle(SnapshotStyle.withHoles); config.qsim().setNodeOffset(5.); config.qsim().setUsingFastCapacityUpdate(false); - + // add the signal config group to the config file - SignalSystemsConfigGroup signalConfig = + SignalSystemsConfigGroup signalConfig = ConfigUtils.addOrGetModule(config, SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class ) ; - + // the following makes the contrib load the signal input files, but not to do anything with them // (this switch will eventually go away) signalConfig.setUseSignalSystems(true); @@ -79,7 +79,7 @@ static void run(boolean useOTFVis) { signalConfig.setSignalSystemFile("signalSystems_v2.0.xml"); signalConfig.setSignalGroupsFile("signalGroups_v2.0.xml"); signalConfig.setSignalControlFile("signalControl_v2.0.xml"); - + // // here is how to also use intergreen and amber times: // signalConfig.setUseIntergreenTimes(true); // signalConfig.setIntergreenTimesFile(intergreenTimesFile); @@ -87,17 +87,17 @@ static void run(boolean useOTFVis) { // signalConfig.setActionOnIntergreenViolation(SignalSystemsConfigGroup.ActionOnIntergreenViolation.WARN); // signalConfig.setUseAmbertimes(true); // signalConfig.setAmberTimesFile(amberTimesFile); - + // // here is how to switch on link to link travel times if lanes are used: // config.travelTimeCalculator().setCalculateLinkToLinkTravelTimes(true); // config.controler().setLinkToLinkRoutingEnabled(true); - + if (useOTFVis) { // add the OTFVis config group - OTFVisConfigGroup otfvisConfig = + OTFVisConfigGroup otfvisConfig = ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class); // make links visible beyond screen edge - otfvisConfig.setScaleQuadTreeRect(true); + otfvisConfig.setScaleQuadTreeRect(true); otfvisConfig.setColoringScheme(ColoringScheme.byId); otfvisConfig.setAgentSize(240); } @@ -107,22 +107,22 @@ static void run(boolean useOTFVis) { /* load the information about signals data (i.e. fill the SignalsData object) * and add it to the scenario as scenario element */ scenario.addScenarioElement(SignalsData.ELEMENT_NAME, new SignalsDataLoader(config).loadSignalsData()); - + // --- create the controler Controler c = new Controler( scenario ); /* add the signals module to the simulation - * such that SignalsData is not only contained in the scenario + * such that SignalsData is not only contained in the scenario * but also used in the simulation */ // c.addOverridingModule(new SignalsModule()); Signals.configure( c ); - + /* add the visualization module to the simulation * such that it is used */ if ( useOTFVis ) { c.addOverridingModule( new OTFVisWithSignalsLiveModule() ); } - + // run the simulation c.run(); } diff --git a/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/VisualizeSignalScenario.java b/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/VisualizeSignalScenario.java index 1f3dbcf4129..b80a6106253 100644 --- a/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/VisualizeSignalScenario.java +++ b/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/VisualizeSignalScenario.java @@ -36,24 +36,24 @@ /** * This class contains a simple example how to visualize a simple scenario * with signalized intersections. - * + * * @author dgrether */ -public class VisualizeSignalScenario { +public class VisualizeSignalScenario { private static final String INPUT_DIR = "./examples/tutorial/example90TrafficLights/useSignalInput/woLanes/"; - + public static void run(boolean startOtfvis) throws IOException { // --- load the configuration file Config config = ConfigUtils.loadConfig(INPUT_DIR + "config.xml"); - config.controler().setLastIteration(0); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - + config.controller().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + // --- create the scenario Scenario scenario = ScenarioUtils.loadScenario(config); // load the information about signals data (i.e. fill the SignalsData object) and add it to the scenario as scenario element scenario.addScenarioElement(SignalsData.ELEMENT_NAME, new SignalsDataLoader(config).loadSignalsData()); - + // --- create the controler Controler c = new Controler(scenario); // add the signals module to the simulation such that SignalsData is not only @@ -64,11 +64,11 @@ public static void run(boolean startOtfvis) throws IOException { // add the module that start the otfvis visualization with signals c.addOverridingModule(new OTFVisWithSignalsLiveModule()); } - + // --- run the simulation c.run(); } - + public static void main(String[] args) throws IOException { run(true); } diff --git a/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/VisualizeSignalScenarioWithLanes.java b/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/VisualizeSignalScenarioWithLanes.java index f1c49c85168..0b080a7fa38 100644 --- a/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/VisualizeSignalScenarioWithLanes.java +++ b/contribs/signals/src/main/java/org/matsim/codeexamples/fixedTimeSignals/VisualizeSignalScenarioWithLanes.java @@ -32,7 +32,7 @@ /** * This class contains a simple example how to visualize a scenario with lanes and signalized intersections. - * + * * @author dgrether */ public class VisualizeSignalScenarioWithLanes { @@ -42,9 +42,9 @@ public class VisualizeSignalScenarioWithLanes { public static void run(boolean startOtfvis) { // --- load the configuration file Config config = ConfigUtils.loadConfig(INPUT_DIR + "config.xml"); - config.controler().setLastIteration(0); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - + config.controller().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + // --- create the scenario Scenario scenario = ScenarioUtils.loadScenario(config); // load the information about signals data (i.e. fill the SignalsData object) and add it to the scenario as scenario element diff --git a/contribs/signals/src/main/java/org/matsim/codeexamples/simpleResponsiveSignalEngine/RunSimpleResponsiveSignalExample.java b/contribs/signals/src/main/java/org/matsim/codeexamples/simpleResponsiveSignalEngine/RunSimpleResponsiveSignalExample.java index 02859e2a582..2e4303d48c1 100644 --- a/contribs/signals/src/main/java/org/matsim/codeexamples/simpleResponsiveSignalEngine/RunSimpleResponsiveSignalExample.java +++ b/contribs/signals/src/main/java/org/matsim/codeexamples/simpleResponsiveSignalEngine/RunSimpleResponsiveSignalExample.java @@ -55,8 +55,8 @@ import org.matsim.contrib.signals.utils.SignalUtils; 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.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.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule.DefaultSelector; @@ -64,12 +64,12 @@ /** * Creates a simple one-crossing-scenario and starts it with the simple responsive signal from this package. - * + * * @author tthunig * */ public class RunSimpleResponsiveSignalExample { - + private final Controler controler; public static void main(String[] args) { @@ -81,12 +81,12 @@ public RunSimpleResponsiveSignalExample() { final Scenario scenario = defineScenario(config); controler = new Controler(scenario); - /* the signals extensions works for planbased, sylvia and laemmer signal controller + /* the signals extensions works for planbased, sylvia and laemmer signal controller * by default and is pluggable for your own signal controller like this: */ new Configurator(controler).addSignalControllerFactory(SimpleResponsiveSignal.IDENTIFIER, SimpleResponsiveSignal.SimpleResponsiveSignalFactory.class); } - + public void run(){ controler.run(); } @@ -108,7 +108,7 @@ private static Scenario defineScenario(Config config) { } /** creates a network like this: - * + * * 6 * ^ * | @@ -125,14 +125,14 @@ private static Scenario defineScenario(Config config) { * ^ * | * v - * 9 - * + * 9 + * * @param scenario */ private static void createNetwork(Scenario scenario) { Network net = scenario.getNetwork(); NetworkFactory fac = net.getFactory(); - + net.addNode(fac.createNode(Id.createNodeId(1), new Coord(-2000, 0))); net.addNode(fac.createNode(Id.createNodeId(2), new Coord(-1000, 0))); net.addNode(fac.createNode(Id.createNodeId(3), new Coord(0, 0))); @@ -142,15 +142,15 @@ private static void createNetwork(Scenario scenario) { net.addNode(fac.createNode(Id.createNodeId(7), new Coord(0, 1000))); net.addNode(fac.createNode(Id.createNodeId(8), new Coord(0, -1000))); net.addNode(fac.createNode(Id.createNodeId(9), new Coord(0, -2000))); - - String[] links = {"1_2", "2_1", "2_3", "3_2", "3_4", "4_3", "4_5", "5_4", + + String[] links = {"1_2", "2_1", "2_3", "3_2", "3_4", "4_3", "4_5", "5_4", "6_7", "7_6", "7_3", "3_7", "3_8", "8_3", "8_9", "9_8"}; - + for (String linkId : links){ String fromNodeId = linkId.split("_")[0]; String toNodeId = linkId.split("_")[1]; - Link link = fac.createLink(Id.createLinkId(linkId), - net.getNodes().get(Id.createNodeId(fromNodeId)), + Link link = fac.createLink(Id.createLinkId(linkId), + net.getNodes().get(Id.createNodeId(fromNodeId)), net.getNodes().get(Id.createNodeId(toNodeId))); link.setCapacity(7200); link.setLength(1000); @@ -161,32 +161,32 @@ private static void createNetwork(Scenario scenario) { private static void createPopulation(Scenario scenario) { Population population = scenario.getPopulation(); - + String[] odRelations = {"1_2-4_5", "4_5-2_1", "6_7-8_9", "9_8-7_6"}; - + for (String od : odRelations) { String fromLinkId = od.split("-")[0]; String toLinkId = od.split("-")[1]; - + for (int i = 0; i < 3600; i++) { // create a person Person person = population.getFactory().createPerson(Id.createPersonId(od + "-" + i)); population.addPerson(person); - + // create a plan for the person that contains all this // information Plan plan = population.getFactory().createPlan(); person.addPlan(plan); - + // create a start activity at the from link Activity startAct = population.getFactory().createActivityFromLinkId("dummy", Id.createLinkId(fromLinkId)); // distribute agents uniformly during one hour. startAct.setEndTime(i); plan.addActivity(startAct); - + // create a dummy leg plan.addLeg(population.getFactory().createLeg(TransportMode.car)); - + // create a drain activity at the to link Activity drainAct = population.getFactory().createActivityFromLinkId("dummy", Id.createLinkId(toLinkId)); plan.addActivity(drainAct); @@ -201,19 +201,19 @@ private static void createSignals(Scenario scenario) { SignalGroupsData signalGroups = signalsData.getSignalGroupsData(); SignalControlData signalControl = signalsData.getSignalControlData(); SignalControlDataFactory conFac = new SignalControlDataFactoryImpl(); - + // create signal system Id signalSystemId = Id.create("SignalSystem1", SignalSystem.class); SignalSystemData signalSystem = sysFac.createSignalSystemData(signalSystemId); signalSystems.addSignalSystemData(signalSystem); - + // create a signal for every inLink for (Id inLinkId : scenario.getNetwork().getNodes().get(Id.createNodeId(3)).getInLinks().keySet()) { SignalData signal = sysFac.createSignalData(Id.create("Signal" + inLinkId, Signal.class)); signalSystem.addSignalData(signal); signal.setLinkId(inLinkId); } - + // group signals with non conflicting streams Id signalGroupId1 = Id.create("SignalGroup1", SignalGroup.class); SignalGroupData signalGroup1 = signalGroups.getFactory() @@ -221,23 +221,23 @@ private static void createSignals(Scenario scenario) { signalGroup1.addSignalId(Id.create("Signal2_3", Signal.class)); signalGroup1.addSignalId(Id.create("Signal4_3", Signal.class)); signalGroups.addSignalGroupData(signalGroup1); - + Id signalGroupId2 = Id.create("SignalGroup2", SignalGroup.class); SignalGroupData signalGroup2 = signalGroups.getFactory() .createSignalGroupData(signalSystemId, signalGroupId2); signalGroup2.addSignalId(Id.create("Signal7_3", Signal.class)); signalGroup2.addSignalId(Id.create("Signal8_3", Signal.class)); signalGroups.addSignalGroupData(signalGroup2); - + // create the signal control SignalSystemControllerData signalSystemControl = conFac.createSignalSystemControllerData(signalSystemId); signalSystemControl.setControllerIdentifier(SimpleResponsiveSignal.IDENTIFIER); signalControl.addSignalSystemControllerData(signalSystemControl); - + // create a plan for the signal system (with defined cycle time and offset 0) SignalPlanData signalPlan = SignalUtils.createSignalPlan(conFac, 60, 0, Id.create("SignalPlan1", SignalPlan.class)); signalSystemControl.addSignalPlanData(signalPlan); - + // specify signal group settings for both signal groups signalPlan.addSignalGroupSettings(SignalUtils.createSetting4SignalGroup(conFac, signalGroupId1, 0, 5)); signalPlan.addSignalGroupSettings(SignalUtils.createSetting4SignalGroup(conFac, signalGroupId2, 10, 55)); @@ -246,20 +246,20 @@ private static void createSignals(Scenario scenario) { private static Config defineConfig() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory("output/simpleResponsiveSignalEngineExample/"); + config.controller().setOutputDirectory("output/simpleResponsiveSignalEngineExample/"); - config.controler().setLastIteration(40); + config.controller().setLastIteration(40); config.travelTimeCalculator().setMaxTime(3600 * 5); config.qsim().setStartTime(0); config.qsim().setEndTime(3600 * 5); config.qsim().setUsingFastCapacityUpdate(false); - + SignalSystemsConfigGroup signalConfigGroup = ConfigUtils.addOrGetModule(config, SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class); signalConfigGroup.setUseSignalSystems(true); ActivityParams dummyAct = new ActivityParams("dummy"); dummyAct.setTypicalDuration(12 * 3600); - config.planCalcScore().addActivityParams(dummyAct); + config.scoring().addActivityParams(dummyAct); // { // StrategySettings strat = new StrategySettings(); @@ -279,16 +279,16 @@ private static Config defineConfig() { StrategySettings strat = new StrategySettings(); strat.setStrategyName(DefaultSelector.KeepLastSelected.toString()); strat.setWeight(0.0); - strat.setDisableAfter(config.controler().getLastIteration()); - config.strategy().addStrategySettings(strat); + strat.setDisableAfter(config.controller().getLastIteration()); + config.replanning().addStrategySettings(strat); } - config.controler().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ) ; - config.controler().setWriteEventsInterval(config.controler().getLastIteration()); - config.controler().setWritePlansInterval(config.controler().getLastIteration()); + config.controller().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ) ; + config.controller().setWriteEventsInterval(config.controller().getLastIteration()); + config.controller().setWritePlansInterval(config.controller().getLastIteration()); config.vspExperimental().setWritingOutputEvents(true); - config.planCalcScore().setWriteExperiencedPlans(true); - config.controler().setCreateGraphs(true); + config.scoring().setWriteExperiencedPlans(true); + config.controller().setCreateGraphs(true); return config; } diff --git a/contribs/signals/src/main/java/org/matsim/codeexamples/simpleResponsiveSignalEngine/SimpleResponsiveSignal.java b/contribs/signals/src/main/java/org/matsim/codeexamples/simpleResponsiveSignalEngine/SimpleResponsiveSignal.java index 76b19f3d815..935a85ca0f0 100644 --- a/contribs/signals/src/main/java/org/matsim/codeexamples/simpleResponsiveSignalEngine/SimpleResponsiveSignal.java +++ b/contribs/signals/src/main/java/org/matsim/codeexamples/simpleResponsiveSignalEngine/SimpleResponsiveSignal.java @@ -110,7 +110,7 @@ void setFactory(SignalModelFactory factory) { @Override public void notifyAfterMobsim(AfterMobsimEvent event) { // change signal green split every INTERVAL iteration - if (event.getIteration() % INTERVAL == 0 && event.getIteration() != scenario.getConfig().controler().getFirstIteration()){ + if (event.getIteration() % INTERVAL == 0 && event.getIteration() != scenario.getConfig().controller().getFirstIteration()){ computeDelays(event); LOG.info("+++ Iteration " + event.getIteration() + ". Update signal green split..."); updateSignals(); diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/analysis/SignalEvents2ViaCSVWriter.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/analysis/SignalEvents2ViaCSVWriter.java index 516c9d1f539..5ea233f38ed 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/analysis/SignalEvents2ViaCSVWriter.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/analysis/SignalEvents2ViaCSVWriter.java @@ -92,7 +92,7 @@ public void reset(int iteration) { @Override public void notifyIterationStarts(IterationStartsEvent event) { - if (event.getIteration() == scenario.getConfig().controler().getFirstIteration()) { + if (event.getIteration() == scenario.getConfig().controller().getFirstIteration()) { /* * do all the stuff that is needed only once a simulation: - calculating coordinations for the via file - getting the signals data out of the scenario */ @@ -100,9 +100,9 @@ public void notifyIterationStarts(IterationStartsEvent event) { } // write signal events in the same interval als usual matsim events - if (event.isLastIteration() || (scenario.getConfig().controler().getWriteEventsInterval() != 0 && event.getIteration() % scenario.getConfig().controler().getWriteEventsInterval() == 0)) { + if (event.isLastIteration() || (scenario.getConfig().controller().getWriteEventsInterval() != 0 && event.getIteration() % scenario.getConfig().controller().getWriteEventsInterval() == 0)) { writeThisIteration = true; - String signalCSVFilename = scenario.getConfig().controler().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/signalEvents2Via.csv"; + String signalCSVFilename = scenario.getConfig().controller().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/signalEvents2Via.csv"; // log.info("Initializing SignalsCSVWriter ..."); signalsCSVWriter = IOUtils.getBufferedWriter(signalCSVFilename); diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/builder/SignalsModule.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/builder/SignalsModule.java index e185debcf1a..acbb5cfa31c 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/builder/SignalsModule.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/builder/SignalsModule.java @@ -52,7 +52,7 @@ * signal controllers, you can add a respective factory by calling the method * addSignalControllerFactory. It is also possible to use different control * schemes in one scenario at different intersections (i.e. signal systems). - * + * * @author tthunig */ class SignalsModule extends AbstractModule { @@ -70,7 +70,7 @@ class SignalsModule extends AbstractModule { signalControllerFactoryClassNames.put(SylviaSignalController.IDENTIFIER, SylviaSignalController.SylviaFactory.class); signalControllerFactoryClassNames.put(LaemmerSignalController.IDENTIFIER, LaemmerSignalController.LaemmerFactory.class); } - + @Override public void install() { @@ -79,7 +79,7 @@ public void install() { // yyyy move to individual config files??? kai, feb'19 this.signalControllerFactoryMultibinder = MapBinder.newMapBinder(binder(), new TypeLiteral() {}, new TypeLiteral() {}); - + if ((boolean) ConfigUtils.addOrGetModule(getConfig(), SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class).isUseSignalSystems()) { // bindings for sensor-based signals (also works for fixed-time signals) bind(SignalModelFactory.class).to(SignalModelFactoryImpl.class); @@ -93,7 +93,7 @@ public void install() { * configure()... theresa, aug'18 */ signalControllerFactoryMultibinder.addBinding(identifier).to(signalControllerFactoryClassNames.get(identifier)); } - + // general signal bindings bind(SignalSystemsManager.class).toProvider(FromDataBuilder.class).in(Singleton.class); addMobsimListenerBinding().to(QSimSignalEngine.class); @@ -108,16 +108,16 @@ public void install() { throw new RuntimeException("Fast flow capacity update does not support signals"); } } - if (getConfig().controler().isLinkToLinkRoutingEnabled()){ + if (getConfig().controller().isLinkToLinkRoutingEnabled()){ //use the extended NetworkWithSignalsTurnInfoBuilder (instead of NetworkTurnInfoBuilder) //michalm, jan'17 bind(NetworkTurnInfoBuilderI.class).to(NetworkWithSignalsTurnInfoBuilder.class); } } - + /** * Call this method when you want to add your own SignalController. E.g. via signalsModule.addSignalControllerFactory().to(LaemmerSignalController.LaemmerFactory.class) - * + * * @param signalControllerFactoryClassName */ final void addSignalControllerFactory(String key, Class signalControllerFactoryClassName) { diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/AbstractSignalsReader.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/AbstractSignalsReader.java index ecf64bfdb9e..14051c475ae 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/AbstractSignalsReader.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/AbstractSignalsReader.java @@ -4,11 +4,11 @@ import org.apache.logging.log4j.Logger; import org.matsim.core.api.internal.MatsimReader; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.xml.sax.InputSource; import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.URL; /** diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/SignalsDataLoader.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/SignalsDataLoader.java index 62e4a3bf966..93f86f8c301 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/SignalsDataLoader.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/SignalsDataLoader.java @@ -31,16 +31,16 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.utils.io.UncheckedIOException; import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.URL; /** * Loads all data files related to the traffic signal systems model. - * + * * @author dgrether * */ @@ -147,7 +147,7 @@ private void loadSystems(SignalsData data){ log.info("Signals: No signal systems file set, can't load signal systems information!"); } } - + private void loadConflicts(SignalsData data) { if (this.signalConfig.getConflictingDirectionsFile() != null) { ConflictingDirectionsReader reader = new ConflictingDirectionsReader(data.getConflictingDirectionsData()); diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/ambertimes/v10/AmberTimesReader10.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/ambertimes/v10/AmberTimesReader10.java index 56f621e8387..dfeab1679d9 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/ambertimes/v10/AmberTimesReader10.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/ambertimes/v10/AmberTimesReader10.java @@ -29,13 +29,15 @@ import org.matsim.contrib.signals.data.AbstractSignalsReader; import org.matsim.contrib.signals.model.Signal; import org.matsim.contrib.signals.model.SignalSystem; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.jaxb.amberTimes10.XMLAmberTimes; import org.matsim.jaxb.amberTimes10.XMLAmberTimes.XMLSignalSystem; import org.matsim.jaxb.amberTimes10.XMLAmberTimes.XMLSignalSystem.XMLSignal; import org.xml.sax.InputSource; import org.xml.sax.SAXException; +import java.io.IOException; +import java.io.UncheckedIOException; + /** * @author jbischoff * @author dgrether @@ -60,7 +62,7 @@ public void read( InputSource stream ) { u.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(getClass().getResource("/dtd/amberTimes_v1.0.xsd"))); xmlatdefs = (XMLAmberTimes) u.unmarshal(stream); } catch (JAXBException | SAXException e) { - throw new UncheckedIOException(e); + throw new UncheckedIOException(new IOException(e)); } // convert from Jaxb types to MATSim-API conform types diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/conflicts/io/ConflictingDirectionsWriter.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/conflicts/io/ConflictingDirectionsWriter.java index 77f0fe953d3..4ec961748a0 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/conflicts/io/ConflictingDirectionsWriter.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/conflicts/io/ConflictingDirectionsWriter.java @@ -21,13 +21,13 @@ package org.matsim.contrib.signals.data.conflicts.io; import java.io.IOException; +import java.io.UncheckedIOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.contrib.signals.data.conflicts.ConflictData; import org.matsim.core.api.internal.MatsimWriter; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; /** * @author tthunig @@ -35,20 +35,20 @@ public final class ConflictingDirectionsWriter extends MatsimXmlWriter implements MatsimWriter { private static final Logger LOG = LogManager.getLogger(ConflictingDirectionsWriter.class); - + private ConflictData conflictData; private ConflictingDirectionsWriterHandlerImpl handler; - - + + public ConflictingDirectionsWriter(ConflictData conflictData) { this.conflictData = conflictData; this.handler = new ConflictingDirectionsWriterHandlerImpl(); } - + @Override public void write(String filename) { LOG.info("Writing conflicting direction data to file: " + filename + "..."); - + try { this.openFile(filename); this.handler.writeHeaderAndStartElement(this.writer); @@ -57,11 +57,11 @@ public void write(String filename) { this.handler.endConflictData(this.writer); LOG.info("Conflict data written to: " + filename); } catch (IOException e) { - throw new UncheckedIOException(e); + throw new UncheckedIOException(new IOException(e)); } finally { this.close(); } - + LOG.info("done."); } diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/intergreens/v10/IntergreenTimesReader10.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/intergreens/v10/IntergreenTimesReader10.java index 3635967e656..c91244bb51a 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/intergreens/v10/IntergreenTimesReader10.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/intergreens/v10/IntergreenTimesReader10.java @@ -29,24 +29,26 @@ import org.matsim.contrib.signals.data.AbstractSignalsReader; import org.matsim.contrib.signals.model.SignalGroup; import org.matsim.contrib.signals.model.SignalSystem; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.jaxb.intergreenTimes10.XMLEndingSignalGroupType; import org.matsim.jaxb.intergreenTimes10.XMLIntergreenTimes; import org.matsim.jaxb.intergreenTimes10.XMLIntergreenTimes.XMLSignalSystem; import org.xml.sax.InputSource; import org.xml.sax.SAXException; +import java.io.IOException; +import java.io.UncheckedIOException; + /** * @author dgrether */ public final class IntergreenTimesReader10 extends AbstractSignalsReader{ - + private IntergreenTimesData intergreensData; public IntergreenTimesReader10(IntergreenTimesData intergreenTimesData) { this.intergreensData = intergreenTimesData; } - + public void read(InputSource stream) throws UncheckedIOException { try { Unmarshaller u = JAXBContext.newInstance(org.matsim.jaxb.intergreenTimes10.ObjectFactory.class).createUnmarshaller(); @@ -66,7 +68,7 @@ public void read(InputSource stream) throws UncheckedIOException { } } } catch (JAXBException | SAXException e) { - throw new UncheckedIOException(e); + throw new UncheckedIOException(new IOException(e)); } } } diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalcontrol/v20/SignalControlReader20.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalcontrol/v20/SignalControlReader20.java index 9cbd9f1a73d..35ead4e1f22 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalcontrol/v20/SignalControlReader20.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalcontrol/v20/SignalControlReader20.java @@ -19,7 +19,9 @@ * *********************************************************************** */ package org.matsim.contrib.signals.data.signalcontrol.v20; +import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import javax.xml.XMLConstants; import jakarta.xml.bind.JAXBContext; @@ -34,7 +36,6 @@ import org.matsim.contrib.signals.model.SignalGroup; import org.matsim.contrib.signals.model.SignalPlan; import org.matsim.contrib.signals.model.SignalSystem; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.jaxb.signalcontrol20.XMLSignalControl; import org.matsim.jaxb.signalcontrol20.XMLSignalGroupSettingsType; import org.matsim.jaxb.signalcontrol20.XMLSignalPlanType; @@ -63,7 +64,7 @@ private XMLSignalControl readSignalControl20Stream(InputStream stream) { u.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(getClass().getResource("/dtd/signalControl_v2.0.xsd"))); return (XMLSignalControl) u.unmarshal(stream); } catch (JAXBException | SAXException e) { - throw new UncheckedIOException(e); + throw new UncheckedIOException(new IOException(e)); } } diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalgroups/v20/SignalGroupsReader20.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalgroups/v20/SignalGroupsReader20.java index 4128a60fe83..edbedf63002 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalgroups/v20/SignalGroupsReader20.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalgroups/v20/SignalGroupsReader20.java @@ -19,7 +19,9 @@ * *********************************************************************** */ package org.matsim.contrib.signals.data.signalgroups.v20; +import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.URL; import javax.xml.XMLConstants; @@ -34,7 +36,6 @@ import org.matsim.contrib.signals.model.SignalSystem; import org.matsim.core.api.internal.MatsimReader; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.jaxb.signalgroups20.XMLIdRefType; import org.matsim.jaxb.signalgroups20.XMLSignalGroupType; import org.matsim.jaxb.signalgroups20.XMLSignalGroups; @@ -97,7 +98,7 @@ private XMLSignalGroups readXmlSignalGroups( InputSource stream ) { u.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(getClass().getResource("/dtd/signalGroups_v2.0.xsd"))); return (XMLSignalGroups) u.unmarshal(stream); } catch (SAXException | JAXBException e) { - throw new UncheckedIOException(e); + throw new UncheckedIOException(new IOException(e)); } } diff --git a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalsystems/v20/SignalSystemsReader20.java b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalsystems/v20/SignalSystemsReader20.java index 40a74ea839d..3d1bb1fab5a 100644 --- a/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalsystems/v20/SignalSystemsReader20.java +++ b/contribs/signals/src/main/java/org/matsim/contrib/signals/data/signalsystems/v20/SignalSystemsReader20.java @@ -19,7 +19,9 @@ * *********************************************************************** */ package org.matsim.contrib.signals.data.signalsystems.v20; +import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import javax.xml.XMLConstants; import jakarta.xml.bind.JAXBContext; @@ -32,7 +34,6 @@ import org.matsim.contrib.signals.data.AbstractSignalsReader; import org.matsim.contrib.signals.model.Signal; import org.matsim.contrib.signals.model.SignalSystem; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.jaxb.signalsystems20.XMLIdRefType; import org.matsim.jaxb.signalsystems20.XMLSignalSystemType; import org.matsim.jaxb.signalsystems20.XMLSignalSystems; @@ -91,7 +92,7 @@ private XMLSignalSystems getXmlSignalSystems(InputStream stream) { u.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(getClass().getResource("/dtd/signalSystems_v2.0.xsd"))); return (XMLSignalSystems) u.unmarshal(stream); } catch (JAXBException | SAXException e) { - throw new UncheckedIOException(e); + throw new UncheckedIOException(new IOException(e)); } } } diff --git a/contribs/signals/src/test/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExampleTest.java b/contribs/signals/src/test/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExampleTest.java index e894ac9deaf..ee8adba17bf 100644 --- a/contribs/signals/src/test/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExampleTest.java +++ b/contribs/signals/src/test/java/org/matsim/codeexamples/fixedTimeSignals/RunSignalSystemsExampleTest.java @@ -44,15 +44,15 @@ public final void testExampleWithHoles() { Assert.fail("something went wrong: " + ee.getMessage()) ; } } - + @Test public final void testMinimalExample() { try { Config config = ConfigUtils.loadConfig("./examples/tutorial/example90TrafficLights/useSignalInput/withLanes/config.xml"); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); - + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + RunSignalSystemsExample.run(config, false); } catch (Exception ee ) { ee.printStackTrace(); diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/Fixture.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/Fixture.java index 5a761cbe2f8..63f18a921a9 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/Fixture.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/Fixture.java @@ -45,8 +45,8 @@ import org.matsim.contrib.signals.model.SignalSystem; 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.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.lanes.Lane; @@ -86,15 +86,15 @@ private Config createConfigOneSignal(Boolean useIntergreens) { e.printStackTrace(); } Config conf = ConfigUtils.createConfig(testUtils.classInputResourcePath()); - conf.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + conf.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); ActivityParams params = new ActivityParams("h"); params.setTypicalDuration(24.0 * 3600.0); - conf.planCalcScore().addActivityParams(params); + conf.scoring().addActivityParams(params); StrategySettings settings = new StrategySettings(Id.create("1", StrategySettings.class)); settings.setStrategyName("ChangeExpBeta"); settings.setWeight(1.0); - conf.strategy().addStrategySettings(settings); + conf.replanning().addStrategySettings(settings); conf.network().setInputFile("network.xml.gz"); conf.network().setLaneDefinitionsFile("testLaneDefinitions_v2.0.xml"); conf.plans().setInputFile("plans1Agent.xml"); diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/TravelTimeFourWaysTest.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/TravelTimeFourWaysTest.java index 826e90c1f3f..da098163ddb 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/TravelTimeFourWaysTest.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/TravelTimeFourWaysTest.java @@ -48,16 +48,16 @@ public class TravelTimeFourWaysTest { private static final String EVENTSFILE = "events.xml.gz"; - + @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); - + @Test public void testTrafficLightIntersection4arms() { Scenario scenario = this.createTestScenario(); scenario.getConfig().plans().setInputFile("plans.xml.gz"); ScenarioUtils.loadScenario(scenario); - + runQSimWithSignals(scenario); } @@ -72,13 +72,13 @@ public void testTrafficLightIntersection4armsWithUTurn() { private Scenario createTestScenario(){ Config conf = ConfigUtils.createConfig(testUtils.classInputResourcePath()); - conf.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - conf.controler().setMobsim("qsim"); + conf.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + conf.controller().setMobsim("qsim"); conf.network().setInputFile("network.xml.gz"); conf.network().setLaneDefinitionsFile("testLaneDefinitions_v2.0.xml"); conf.qsim().setUseLanes(true); conf.qsim().setUsingFastCapacityUpdate(false); - + SignalSystemsConfigGroup signalsConfig = ConfigUtils.addOrGetModule(conf, SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class ); signalsConfig.setUseSignalSystems(true); signalsConfig.setSignalSystemFile("testSignalSystems_v2.0.xml"); @@ -86,7 +86,7 @@ private Scenario createTestScenario(){ signalsConfig.setSignalControlFile("testSignalControl_v2.0.xml"); signalsConfig.setUseAmbertimes(true); signalsConfig.setAmberTimesFile("testAmberTimes_v1.0.xml"); - + Scenario scenario = ScenarioUtils.createScenario(conf); scenario.addScenarioElement( SignalsData.ELEMENT_NAME , new SignalsDataLoader(scenario.getConfig()).loadSignalsData()); return scenario; @@ -103,7 +103,7 @@ private void runQSimWithSignals(final Scenario scenario) { // install(new ScenarioByInstanceModule(scenario)); // } // }), new SignalsModule())); - + // EventsManager events = injector.getInstance(EventsManager.class); // events.initProcessing(); @@ -122,10 +122,10 @@ private void runQSimWithSignals(final Scenario scenario) { .addOverridingModule( new SignalsModule() ) .addOverridingQSimModule( new SignalsQSimModule() ) .build( scenario, events ).run(); - + eventsXmlWriter.closeFile(); // Assert.assertEquals("different events files", EventsFileComparator.compareAndReturnInt(this.testUtils.getInputDirectory() + EVENTSFILE, eventsOut), 0); Assert.assertEquals( Result.FILES_ARE_EQUAL, new EventsFileComparator().setIgnoringCoordinates( true ).runComparison( this.testUtils.getInputDirectory() + EVENTSFILE, eventsOut ) ); } - + } diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/TravelTimeOneWayTestIT.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/TravelTimeOneWayTestIT.java index 1fbeee55fcf..fde085e7b61 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/TravelTimeOneWayTestIT.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/builder/TravelTimeOneWayTestIT.java @@ -78,12 +78,12 @@ public void testSignalOutflow_withLanes() { public void testSignalOutflow_woLanes() { runAndTestDifferentGreensplitSignals(this.loadAllGreenScenario(false)); } - + @Test public void testAllGreenSignalVsNoSignal_withLanes() { runAndCompareAllGreenWithNoSignals(this.loadAllGreenScenario(true)); } - + @Test public void testAllGreenSignalVsNoSignal_woLanes() { runAndCompareAllGreenWithNoSignals(this.loadAllGreenScenario(false)); @@ -91,8 +91,8 @@ public void testAllGreenSignalVsNoSignal_woLanes() { private Scenario loadAllGreenScenario(boolean useLanes) { Config conf = ConfigUtils.createConfig(testUtils.classInputResourcePath()); - conf.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); - conf.controler().setMobsim("qsim"); + conf.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + conf.controller().setMobsim("qsim"); conf.network().setInputFile("network.xml"); conf.plans().setInputFile("plans.xml.gz"); conf.qsim().setStuckTime(1000); @@ -122,7 +122,7 @@ private static void runAndCompareAllGreenWithNoSignals(final Scenario scenario) StubLinkEnterEventHandler stubLinkEnterEventHandler = new StubLinkEnterEventHandler(); runQsimWithSignals(scenario, stubLinkEnterEventHandler); MeasurementPoint resultsWithSignals = stubLinkEnterEventHandler.beginningOfLink2; - + // without signals EventsManager events = EventsUtils.createEventsManager(); StubLinkEnterEventHandler eventHandler = new StubLinkEnterEventHandler(); @@ -140,7 +140,7 @@ private static void runAndCompareAllGreenWithNoSignals(final Scenario scenario) } else { Assert.fail("seems like no LinkEnterEvent was handled, as this.beginningOfLink2 is not set."); } - + // compare values Assert.assertEquals(5000.0, resultsWithSignals.numberOfVehPassed, MatsimTestUtils.EPSILON); Assert.assertEquals(resultsWithSignals.firstVehPassTime_s, resultsWoSignals.firstVehPassTime_s, MatsimTestUtils.EPSILON); @@ -163,7 +163,7 @@ private static void runAndTestDifferentGreensplitSignals(final Scenario scenario StubLinkEnterEventHandler stubLinkEnterEventHandler = new StubLinkEnterEventHandler(); runQsimWithSignals(scenario, stubLinkEnterEventHandler); - + log.debug("circulationTime: " + circulationTime); log.debug("dropping : " + dropping); @@ -183,7 +183,7 @@ public void install() { install(new ScenarioByInstanceModule(scenario)); } }), new SignalsModule())); - + EventsManager events = injector.getInstance(EventsManager.class); events.initProcessing(); for (EventHandler handler : eventHandlers){ diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/fixedTime/DefaultPlanbasedSignalSystemControllerIT.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/fixedTime/DefaultPlanbasedSignalSystemControllerIT.java index 86e74ce1dba..9e5a726548a 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/fixedTime/DefaultPlanbasedSignalSystemControllerIT.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/fixedTime/DefaultPlanbasedSignalSystemControllerIT.java @@ -61,8 +61,8 @@ import org.matsim.contrib.signals.utils.SignalUtils; 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.StrategyConfigGroup.StrategySettings; +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.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -73,14 +73,14 @@ /** * Tests fixed-time control, especially for multiple fixed-time plans over a day. - * + * * @author tthunig * */ public class DefaultPlanbasedSignalSystemControllerIT { private static final Logger log = LogManager.getLogger(DefaultPlanbasedSignalSystemControllerIT.class); - + @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); @@ -89,7 +89,7 @@ public void test2SequentialPlansCompleteDay(){ ScenarioRunner runner = new ScenarioRunner(0.0, 3600*1.0, 3600*1.0, 3600*24.0); runner.setNoSimHours(1); SignalEventAnalyzer signalAnalyzer = runner.run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -99,19 +99,19 @@ public void test2SequentialPlansCompleteDay(){ log.info("First cycle time after 1am " + signalAnalyzer.getCycleTimeOfFirstCycleInHour(1)); // test time when signal plans are switched on and off Assert.assertEquals("First signal state event unexpected.", 0.0, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); Assert.assertNull("There was an unexpected event that switches off signals.", signalAnalyzer.getLastSignalOffEventTime()); - Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); + Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); // test if signal plans are both running Assert.assertEquals("Cycle time of first signal plan wrong.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(0), MatsimTestUtils.EPSILON); Assert.assertEquals("Cycle time of second signal plan wrong.", 60, signalAnalyzer.getCycleTimeOfFirstCycleInHour(1), MatsimTestUtils.EPSILON); } - + @Test public void test2SequentialPlansUncompleteDayEnd(){ SignalEventAnalyzer signalAnalyzer = (new ScenarioRunner(0.0, 3600*1.0, 3600*1.0, 3600*2.0)).run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -123,9 +123,9 @@ public void test2SequentialPlansUncompleteDayEnd(){ log.info("Number of signal events after 2am " + signalAnalyzer.getNumberOfSignalEventsInHour(2)); // test time when signal plans are switched on and off Assert.assertEquals("First signal state event unexpected.", 0.0, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); - Assert.assertEquals("Time when signals are finally switched off is wrong.", 3600*2, signalAnalyzer.getLastSignalOffEventTime(), 5 + MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); + Assert.assertEquals("Time when signals are finally switched off is wrong.", 3600*2, signalAnalyzer.getLastSignalOffEventTime(), 5 + MatsimTestUtils.EPSILON); /* "5 + " because there is SignalSystemImpl.SWITCH_OFF_SEQUENCE_LENGTH of 5 seconds that is added to each signal plans end time as buffer */ Assert.assertEquals("Number of signal off events is wrong.", 1, signalAnalyzer.getNumberOfOffEvents()); Assert.assertEquals("Signals where unexpectedly switched on after 2am.", 0, signalAnalyzer.getCycleTimeOfFirstCycleInHour(2), MatsimTestUtils.EPSILON); @@ -135,11 +135,11 @@ public void test2SequentialPlansUncompleteDayEnd(){ Assert.assertEquals("Cycle time of first signal plan wrong.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(0), MatsimTestUtils.EPSILON); Assert.assertEquals("Cycle time of second signal plan wrong.", 60, signalAnalyzer.getCycleTimeOfFirstCycleInHour(1), MatsimTestUtils.EPSILON); } - + @Test public void test2SequentialPlansUncompleteDayStart(){ SignalEventAnalyzer signalAnalyzer = (new ScenarioRunner(3600*1.0, 3600*2.0, 3600*2.0, 3600*24.0)).run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -148,13 +148,13 @@ public void test2SequentialPlansUncompleteDayStart(){ log.info("First cycle time after 0am " + signalAnalyzer.getCycleTimeOfFirstCycleInHour(0)); log.info("First cycle time after 1am " + signalAnalyzer.getCycleTimeOfFirstCycleInHour(1)); log.info("First cycle time after 2am " + signalAnalyzer.getCycleTimeOfFirstCycleInHour(2)); - log.info("Number of signal events between 0am and 1am " + signalAnalyzer.getNumberOfSignalEventsInHour(0)); + log.info("Number of signal events between 0am and 1am " + signalAnalyzer.getNumberOfSignalEventsInHour(0)); // test time when signal plans are switched on and off Assert.assertEquals("First signal state event unexpected.", 3600*1, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*2, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*2, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); Assert.assertNull("There was an unexpected event that switches off signals.", signalAnalyzer.getLastSignalOffEventTime()); - Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); + Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); // test if first hour is simulated correctly without signals Assert.assertEquals("Signals where unexpectedly switched on between 0am and 1am.", 0, signalAnalyzer.getCycleTimeOfFirstCycleInHour(0), MatsimTestUtils.EPSILON); Assert.assertTrue("Signals where unexpectedly switched on between 0am and 1am.", 1 > signalAnalyzer.getNumberOfSignalEventsInHour(0)); @@ -163,13 +163,13 @@ public void test2SequentialPlansUncompleteDayStart(){ Assert.assertEquals("Cycle time of first signal plan wrong.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(1), MatsimTestUtils.EPSILON); Assert.assertEquals("Cycle time of second signal plan wrong.", 60, signalAnalyzer.getCycleTimeOfFirstCycleInHour(2), MatsimTestUtils.EPSILON); } - + @Test public void test2SequentialPlans1SecGap(){ ScenarioRunner runner = new ScenarioRunner(0.0, 3600*1.0, 3600*1.0+1, 3600*24.0); runner.setNoSimHours(1); SignalEventAnalyzer signalAnalyzer = runner.run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -179,19 +179,19 @@ public void test2SequentialPlans1SecGap(){ log.info("First cycle time after 1am " + signalAnalyzer.getCycleTimeOfFirstCycleInHour(1)); // test time when signal plans are switched on and off Assert.assertEquals("First signal state event unexpected.", 0.0, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1+1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1+1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); Assert.assertNull("There was an unexpected event that switches off signals.", signalAnalyzer.getLastSignalOffEventTime()); - Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); + Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); // test if signal plans are both running Assert.assertEquals("Cycle time of first signal plan wrong.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(0), MatsimTestUtils.EPSILON); Assert.assertEquals("Cycle time of second signal plan wrong.", 60, signalAnalyzer.getCycleTimeOfFirstCycleInHour(1), MatsimTestUtils.EPSILON); } - + @Test public void test2SequentialPlans1HourGap(){ SignalEventAnalyzer signalAnalyzer = (new ScenarioRunner(3600*0.0, 3600*1.0, 3600*2.0, 3600*24.0)).run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -203,11 +203,11 @@ public void test2SequentialPlans1HourGap(){ log.info("Number of signal events between 1am and 2am " + signalAnalyzer.getNumberOfSignalEventsInHour(1)); // test time when signal plans are switched on and off Assert.assertEquals("First signal state event unexpected.", 0.0, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*2, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); - Assert.assertEquals("Time when signals are finally switched off is wrong.", 3600*1, signalAnalyzer.getLastSignalOffEventTime(), 5 + MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*2, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); + Assert.assertEquals("Time when signals are finally switched off is wrong.", 3600*1, signalAnalyzer.getLastSignalOffEventTime(), 5 + MatsimTestUtils.EPSILON); /* "5 + " because there is SignalSystemImpl.SWITCH_OFF_SEQUENCE_LENGTH of 5 seconds that is added to each signal plans end time as buffer */ - Assert.assertEquals("Number of signal off events is wrong.", 1, signalAnalyzer.getNumberOfOffEvents()); + Assert.assertEquals("Number of signal off events is wrong.", 1, signalAnalyzer.getNumberOfOffEvents()); // test if break between signal plans is simulated correctly Assert.assertEquals("Signals where unexpectedly switched on between the signal plans.", 0, signalAnalyzer.getCycleTimeOfFirstCycleInHour(1), MatsimTestUtils.EPSILON); Assert.assertTrue("Signals where unexpectedly switched on between the signal plans.", 3 > signalAnalyzer.getNumberOfSignalEventsInHour(1)); @@ -216,13 +216,13 @@ public void test2SequentialPlans1HourGap(){ Assert.assertEquals("Cycle time of first signal plan wrong.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(0), MatsimTestUtils.EPSILON); Assert.assertEquals("Cycle time of second signal plan wrong.", 60, signalAnalyzer.getCycleTimeOfFirstCycleInHour(2), MatsimTestUtils.EPSILON); } - + @Test public void test2SequentialPlans1HourGap2TimesOff(){ ScenarioRunner runner = new ScenarioRunner(3600*0.0, 3600*1.0, 3600*2.0, 3600*3.0); runner.setNoSimHours(3); SignalEventAnalyzer signalAnalyzer = runner.run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -238,7 +238,7 @@ public void test2SequentialPlans1HourGap2TimesOff(){ Assert.assertEquals("First signal state event unexpected.", 0.0, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); Assert.assertEquals("Time when signals are finally switched off is wrong.", 3600*3, signalAnalyzer.getLastSignalOffEventTime(), 5 + MatsimTestUtils.EPSILON); /* "5 + " because there is SignalSystemImpl.SWITCH_OFF_SEQUENCE_LENGTH of 5 seconds that is added to each signal plans end time as buffer */ - Assert.assertEquals("Number of signal off events is wrong.", 2, signalAnalyzer.getNumberOfOffEvents()); + Assert.assertEquals("Number of signal off events is wrong.", 2, signalAnalyzer.getNumberOfOffEvents()); Assert.assertEquals("Signals where unexpectedly switched on between the signal plans.", 0, signalAnalyzer.getCycleTimeOfFirstCycleInHour(1), MatsimTestUtils.EPSILON); Assert.assertTrue("Signals where unexpectedly switched on between the signal plans.", 3 > signalAnalyzer.getNumberOfSignalEventsInHour(1)); /* "3 >" because last signal switches of the first plan are allowed at 1am and switch off is only after 5 seconds (in 1:00:05 am) */ @@ -249,11 +249,11 @@ public void test2SequentialPlans1HourGap2TimesOff(){ Assert.assertEquals("Cycle time of first signal plan wrong.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(0), MatsimTestUtils.EPSILON); Assert.assertEquals("Cycle time of second signal plan wrong.", 60, signalAnalyzer.getCycleTimeOfFirstCycleInHour(2), MatsimTestUtils.EPSILON); } - + @Test public void test2SequentialPlansOverMidnight(){ SignalEventAnalyzer signalAnalyzer = (new ScenarioRunner(3600*22.0, 3600*1.0, 3600*1.0, 3600*22.0)).run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -263,19 +263,19 @@ public void test2SequentialPlansOverMidnight(){ log.info("First cycle time after 1am " + signalAnalyzer.getCycleTimeOfFirstCycleInHour(1)); // test time when signal plans are switched on and off Assert.assertEquals("First signal state event unexpected.", 0.0, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); Assert.assertNull("There was an unexpected event that switches off signals.", signalAnalyzer.getLastSignalOffEventTime()); Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); // test if signal plans are both running Assert.assertEquals("Cycle time of first signal plan wrong.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(0), MatsimTestUtils.EPSILON); Assert.assertEquals("Cycle time of second signal plan wrong.", 60, signalAnalyzer.getCycleTimeOfFirstCycleInHour(1), MatsimTestUtils.EPSILON); } - + @Test public void test1SignalPlanUncompleteDay(){ SignalEventAnalyzer signalAnalyzer = (new ScenarioRunner(3600*1.0, 3600*2.0, null, null)).run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -288,9 +288,9 @@ public void test1SignalPlanUncompleteDay(){ log.info("Number of signal events after 2am " + signalAnalyzer.getNumberOfSignalEventsInHour(2)); // test time when signal plan is switched on and off Assert.assertEquals("First signal state event unexpected.", 3600.0, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 1, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); - Assert.assertEquals("Time when signals are finally switched off is wrong.", 3600*2, signalAnalyzer.getLastSignalOffEventTime(), 5 + MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 1, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*1, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); + Assert.assertEquals("Time when signals are finally switched off is wrong.", 3600*2, signalAnalyzer.getLastSignalOffEventTime(), 5 + MatsimTestUtils.EPSILON); Assert.assertEquals("Number of signal off events is wrong.", 1, signalAnalyzer.getNumberOfOffEvents()); Assert.assertEquals("Signals where unexpectedly switched on before 1am.", 0, signalAnalyzer.getCycleTimeOfFirstCycleInHour(0), MatsimTestUtils.EPSILON); Assert.assertTrue("Signals where unexpectedly switched on before 1am.", 1 > signalAnalyzer.getNumberOfSignalEventsInHour(0)); @@ -300,7 +300,7 @@ public void test1SignalPlanUncompleteDay(){ Assert.assertTrue("Signals where unexpectedly switched on after 2am.", 3 > signalAnalyzer.getNumberOfSignalEventsInHour(2)); /* "3 >" because last signal switches of the first plan are allowed at 2am and switch off is only after 5 seconds (in 2:00:05 am) */ } - + /** * test * 1. one signal plan with default start and end times. should give all day signal plan @@ -311,7 +311,7 @@ public void test1AllDaySignalPlanOverMidnightLateStart(){ ScenarioRunner runner = new ScenarioRunner(null, null, null, null); // i.e. new ScenarioRunner(0.0, 0.0, null, null); runner.setSimStart_h(23); SignalEventAnalyzer signalAnalyzer = runner.run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -321,15 +321,15 @@ public void test1AllDaySignalPlanOverMidnightLateStart(){ log.info("First cycle time after 0am next day " + signalAnalyzer.getCycleTimeOfFirstCycleInHour(24)); // test time when signal plan is switched on and off Assert.assertEquals("First signal state event unexpected.", 3600*23, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*24, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*24, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); Assert.assertNull("There was an unexpected event that switches off signals.", signalAnalyzer.getLastSignalOffEventTime()); Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); // test if signal plan is running for more than 24h Assert.assertEquals("Signal plan is not active between 11pmam and 12pm.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(23), MatsimTestUtils.EPSILON); Assert.assertEquals("Signal plan is not active anymore after 0am next day.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(24), MatsimTestUtils.EPSILON); } - + /** * test * 1. one signal plan with default start and end times. should give all day signal plan @@ -338,7 +338,7 @@ public void test1AllDaySignalPlanOverMidnightLateStart(){ @Test public void test1AllDaySignalPlanMidnightStart(){ SignalEventAnalyzer signalAnalyzer = (new ScenarioRunner(null, null, null, null)).run(); // i.e. new ScenarioRunner(0.0, 0.0, null, null); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -347,20 +347,20 @@ public void test1AllDaySignalPlanMidnightStart(){ log.info("First cycle time after 0am " + signalAnalyzer.getCycleTimeOfFirstCycleInHour(0)); // test time when signal plan is switched on and off Assert.assertEquals("First signal state event unexpected.", 0.0, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 1, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 0.0, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 1, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 0.0, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); Assert.assertNull("There was an unexpected event that switches off signals.", signalAnalyzer.getLastSignalOffEventTime()); Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); // test if signal plan is running for more than 24h Assert.assertEquals("Signal plan is not active between 0am and 1am.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(0), MatsimTestUtils.EPSILON); } - + @Test public void test2SignalPlanFor25h(){ ScenarioRunner runner = new ScenarioRunner(3600*0.0, 3600*12.0, 3600*12.0, 3600*24.0); runner.setNoSimHours(25); SignalEventAnalyzer signalAnalyzer = runner.run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -371,8 +371,8 @@ public void test2SignalPlanFor25h(){ log.info("First cycle time after 0am next day " + signalAnalyzer.getCycleTimeOfFirstCycleInHour(24)); // test time when signal plans are switched on and off Assert.assertEquals("First signal state event unexpected.", 0.0, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 3, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*24, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 3, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*24, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); Assert.assertNull("There was an unexpected event that switches off signals.", signalAnalyzer.getLastSignalOffEventTime()); Assert.assertEquals("Number of signal off events is wrong.", 0, signalAnalyzer.getNumberOfOffEvents()); // test if signal plans are correctly running for more than 24h @@ -380,14 +380,14 @@ public void test2SignalPlanFor25h(){ Assert.assertEquals("Second signal plan is not active between 12am and 1pm.", 60, signalAnalyzer.getCycleTimeOfFirstCycleInHour(12), MatsimTestUtils.EPSILON); Assert.assertEquals("First signal plan is not active again after 0am next day.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(24), MatsimTestUtils.EPSILON); } - + @Test public void testSimStartAfterFirstDayPlan(){ ScenarioRunner runner = new ScenarioRunner(3600*0.0, 3600*1.0, 3600*23.0, 3600*24.0); runner.setSimStart_h(23); runner.setNoSimHours(3); SignalEventAnalyzer signalAnalyzer = runner.run(); - + log.info("First signal event at time " + signalAnalyzer.getFirstSignalEventTime()); log.info("Last start plan event at time " + signalAnalyzer.getLastPlanStartEventTime()); log.info("Number of start plan events " + signalAnalyzer.getNumberOfPlanStartEvents()); @@ -401,9 +401,9 @@ public void testSimStartAfterFirstDayPlan(){ log.info("Number of signal events after 1am next day " + signalAnalyzer.getNumberOfSignalEventsInHour(25)); // test time when signal plans are switched on and off Assert.assertEquals("First signal state event unexpected.", 23*3600, signalAnalyzer.getFirstSignalEventTime(), MatsimTestUtils.EPSILON); -// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); -// Assert.assertEquals("Time when last plan starts is wrong.", 3600*24, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); - Assert.assertEquals("Time when signals are finally switched off is wrong.", 3600*25, signalAnalyzer.getLastSignalOffEventTime(), 5 + MatsimTestUtils.EPSILON); +// Assert.assertEquals("Number of plan start events is wrong.", 2, signalAnalyzer.getNumberOfPlanStartEvents()); +// Assert.assertEquals("Time when last plan starts is wrong.", 3600*24, signalAnalyzer.getLastPlanStartEventTime(), MatsimTestUtils.EPSILON); + Assert.assertEquals("Time when signals are finally switched off is wrong.", 3600*25, signalAnalyzer.getLastSignalOffEventTime(), 5 + MatsimTestUtils.EPSILON); Assert.assertEquals("Number of signal off events is wrong.", 1, signalAnalyzer.getNumberOfOffEvents()); Assert.assertEquals("Signals where unexpectedly switched on before 11pm.", 0, signalAnalyzer.getCycleTimeOfFirstCycleInHour(22), MatsimTestUtils.EPSILON); Assert.assertTrue("Signals where unexpectedly switched on before 11pm.", 1 > signalAnalyzer.getNumberOfSignalEventsInHour(22)); @@ -413,7 +413,7 @@ public void testSimStartAfterFirstDayPlan(){ Assert.assertEquals("Second signal plan is not active between 11pm and 12pm.", 60, signalAnalyzer.getCycleTimeOfFirstCycleInHour(23), MatsimTestUtils.EPSILON); Assert.assertEquals("First signal plan is not active between 0am and 1pm next day.", 120, signalAnalyzer.getCycleTimeOfFirstCycleInHour(24), MatsimTestUtils.EPSILON); } - + /** * tests: * 1. overlapping signal plans (uncomplete day) result in an exception @@ -421,7 +421,7 @@ public void testSimStartAfterFirstDayPlan(){ @Test public void test2PlansSameTimesUncompleteDay(){ final String exceptionMessageOverlapping21 = "Signal plans SignalPlan2 and SignalPlan1 of signal system SignalSystem-3 overlap."; - + try{ (new ScenarioRunner(0.0, 1.0, 0.0, 1.0)).run(); Assert.fail("The simulation has not stopped with an exception although the signal plans overlap."); @@ -430,7 +430,7 @@ public void test2PlansSameTimesUncompleteDay(){ Assert.assertEquals("Wrong exception message.", exceptionMessageOverlapping21, e.getMessage()); } } - + /** * tests: * 1. overlapping signal plans (complete day) result in an exception @@ -439,7 +439,7 @@ public void test2PlansSameTimesUncompleteDay(){ public void test2PlansSameTimesCompleteDay(){ final String exceptionMessageHoleDay = "Signal system SignalSystem-3 has multiple plans but at least one of them covers the hole day. " + "If multiple signal plans are used, they are not allowed to overlap."; - + try{ (new ScenarioRunner(0.0, 0.0, 0.0, 0.0)).run(); // (new ScenarioRunner(1.0, 1.0, 1.0, 1.0)).run(); // alternativ. produces same results @@ -449,11 +449,11 @@ public void test2PlansSameTimesCompleteDay(){ Assert.assertEquals("Wrong exception message.", exceptionMessageHoleDay, e.getMessage()); } } - + @Test public void test2OverlappingPlans(){ final String exceptionMessageOverlapping12 = "Signal plans SignalPlan1 and SignalPlan2 of signal system SignalSystem-3 overlap."; - + try{ (new ScenarioRunner(0.0, 2.0, 1.0, 3.0)).run(); Assert.fail("The simulation has not stopped with an exception although the signal plans overlap."); @@ -462,83 +462,83 @@ public void test2OverlappingPlans(){ Assert.assertEquals("Wrong exception message.", exceptionMessageOverlapping12, e.getMessage()); } } - + @Test public void testNegativeOffset() { //plan1 is valid all day ScenarioRunner sr = new ScenarioRunner(0.0, 0.0, null, null); int offset1 = -3; - - sr.setOffsetPlan1(offset1); + + sr.setOffsetPlan1(offset1); SignalEventAnalyzer signalAnalyzer = sr.run(); // in this case, the first event should be a RED-switch at second 57 - log.info("Offset " + offset1 + " leads to the first signal event at second: " + signalAnalyzer.getFirstSignalEventTime()); + log.info("Offset " + offset1 + " leads to the first signal event at second: " + signalAnalyzer.getFirstSignalEventTime()); Assert.assertEquals("The first signal event should be at the first second after simulation start corresponding to offset, " - + "cycle time and plan start time. Also if the offset is negative!", 60+offset1 , signalAnalyzer.getFirstSignalEventTime() , MatsimTestUtils.EPSILON); + + "cycle time and plan start time. Also if the offset is negative!", 60+offset1 , signalAnalyzer.getFirstSignalEventTime() , MatsimTestUtils.EPSILON); } - + @Test public void testNegativeOffsetEqualCycleTime() { //plan1 is valid all day ScenarioRunner sr = new ScenarioRunner(0.0, 0.0, null, null); int offset1 = -120; - - sr.setOffsetPlan1(offset1); + + sr.setOffsetPlan1(offset1); SignalEventAnalyzer signalAnalyzer = sr.run(); - + // in this case, the first event should be a GREEN-switch at second 0 - log.info("Offset " + offset1 + " leads to the first signal event at second: " + signalAnalyzer.getFirstSignalEventTime()); + log.info("Offset " + offset1 + " leads to the first signal event at second: " + signalAnalyzer.getFirstSignalEventTime()); Assert.assertEquals("The first signal event should be at the first second after simulation start corresponding to offset, " - + "cycle time and plan start time. Also if the offset is negative!", 120+offset1 , signalAnalyzer.getFirstSignalEventTime() , MatsimTestUtils.EPSILON); + + "cycle time and plan start time. Also if the offset is negative!", 120+offset1 , signalAnalyzer.getFirstSignalEventTime() , MatsimTestUtils.EPSILON); } - + @Test public void testTwoPlansWithNegativeOffsets(){ ScenarioRunner sr = new ScenarioRunner(0.0*3600, 1.0*3600, 1.0*3600, 2.*3600 ); - + int offset1 = -3; int offset2 = -5; - + sr.setOffsetPlan1(offset1); sr.setOffsetPlan2(offset2); - + //Simulation starts 1h late int simStart_s = 3600; sr.setSimStart_h(simStart_s/3600); - + SignalEventAnalyzer signalAnalyzer = sr.run(); - + // in this case, the first event should be a RED-switch at second 3625 log.info("Offsets " + offset1 + " and " + offset2 + " with a simulation start at second " + simStart_s + " lead to the first signal event at second: " + signalAnalyzer.getFirstSignalEventTime()); Assert.assertEquals("The first signal event should be at the first second after simulation start corresponding to offset, " - + "cycle time and plan start time. Also if the offset is negative!", simStart_s+30+offset2 , signalAnalyzer.getFirstSignalEventTime() , MatsimTestUtils.EPSILON); + + "cycle time and plan start time. Also if the offset is negative!", simStart_s+30+offset2 , signalAnalyzer.getFirstSignalEventTime() , MatsimTestUtils.EPSILON); } - + @Test public void testTwoPlansWithNegativeOffsetsEqualCycleTime(){ ScenarioRunner sr = new ScenarioRunner(0.0*3600, 1.0*3600, 1.0*3600, 2.*3600 ); - + int offset1 = -3; int offset2 = -60; - + sr.setOffsetPlan1(offset1); sr.setOffsetPlan2(offset2); - + //Simulation starts 1h late int simStart_s = 3600; sr.setSimStart_h(simStart_s/3600); - + SignalEventAnalyzer signalAnalyzer = sr.run(); - + // in this case, the first event should be a GREEN-switch at second 3600 log.info("Offsets " + offset1 + " and " + offset2 + " with a simulation start at second " + simStart_s + " lead to the first signal event at second: " + signalAnalyzer.getFirstSignalEventTime()); Assert.assertEquals("The first signal event should be at the first second after simulation start corresponding to offset, " - + "cycle time and plan start time. Also if the offset is negative!", simStart_s+60+offset2 , signalAnalyzer.getFirstSignalEventTime() , MatsimTestUtils.EPSILON); + + "cycle time and plan start time. Also if the offset is negative!", simStart_s+60+offset2 , signalAnalyzer.getFirstSignalEventTime() , MatsimTestUtils.EPSILON); } - + private class ScenarioRunner{ - + private Double plan1StartTime; private Double plan1EndTime; private Double plan2StartTime; @@ -547,11 +547,11 @@ private class ScenarioRunner{ private int simStart_h= 0; private int offsetPlan1 = 0; private int offsetPlan2 = 0; - + private Scenario scenario; - + /** - * Create a scenario with two signal plans with given start end end times. + * Create a scenario with two signal plans with given start end end times. * If start and end times of second signal plan are null, only one signal plan is created. */ /* package */ ScenarioRunner(Double plan1StartTime, Double plan1EndTime, Double plan2StartTime, Double plan2EndTime) { @@ -560,78 +560,78 @@ private class ScenarioRunner{ this.plan2StartTime = plan2StartTime; this.plan2EndTime = plan2EndTime; } - + /* package */ void setNoSimHours(int hours) { this.noSimHours = hours; } - + /* package */ void setSimStart_h(int simStart_h) { this.simStart_h = simStart_h; } - + /* package */ void setOffsetPlan1(int offset) { this.offsetPlan1 = offset; } - + /* package */ void setOffsetPlan2(int offset) { this.offsetPlan2 = offset; } - + /* package */ SignalEventAnalyzer run() { Config config = defineConfig(); - - scenario = ScenarioUtils.loadScenario(config); + + scenario = ScenarioUtils.loadScenario(config); // add missing scenario elements scenario.addScenarioElement(SignalsData.ELEMENT_NAME, new SignalsDataLoader(config).loadSignalsData()); - + createScenarioElements(scenario); - + Controler controler = new Controler(scenario); // add missing modules // controler.addOverridingModule(new SignalsModule()); Signals.configure(controler); - + // add signal analysis tool final SignalEventAnalyzer signalAnalyzer = new SignalEventAnalyzer(); - controler.addOverridingModule(new AbstractModule() { + controler.addOverridingModule(new AbstractModule() { @Override public void install() { this.addEventHandlerBinding().toInstance(signalAnalyzer); } }); - + controler.run(); return signalAnalyzer; } - + private void createScenarioElements(Scenario scenario) { createNetwork(); createPopulation(); createSignals(); } - + /** * Creates a network like this: - * + * * 1 ----> 2 ----> 3 ----> 4 ----> 5 */ private void createNetwork() { Network net = scenario.getNetwork(); NetworkFactory fac = net.getFactory(); - + net.addNode(fac.createNode(Id.createNodeId(1), new Coord(-2000, 0))); net.addNode(fac.createNode(Id.createNodeId(2), new Coord(-1000, 0))); net.addNode(fac.createNode(Id.createNodeId(3), new Coord(0, 0))); net.addNode(fac.createNode(Id.createNodeId(4), new Coord(1000, 0))); net.addNode(fac.createNode(Id.createNodeId(5), new Coord(2000, 0))); - + String[] links = {"1_2", "2_3", "3_4", "4_5"}; - + for (String linkId : links){ String fromNodeId = linkId.split("_")[0]; String toNodeId = linkId.split("_")[1]; - Link link = fac.createLink(Id.createLinkId(linkId), - net.getNodes().get(Id.createNodeId(fromNodeId)), + Link link = fac.createLink(Id.createLinkId(linkId), + net.getNodes().get(Id.createNodeId(fromNodeId)), net.getNodes().get(Id.createNodeId(toNodeId))); link.setCapacity(7200); link.setLength(1000); @@ -641,12 +641,12 @@ private void createNetwork() { } /** - * Creates a dummy population going from left to right + * Creates a dummy population going from left to right * with one agent starting every second. */ private void createPopulation() { Population pop = scenario.getPopulation(); - + // one person every half an hour for (int i = simStart_h*3600; i <= simStart_h*3600 + noSimHours*3600; i+=1800) { // create a person @@ -677,35 +677,35 @@ private void createSignals() { SignalGroupsData signalGroups = signalsData.getSignalGroupsData(); SignalControlData signalControl = signalsData.getSignalControlData(); SignalControlDataFactory conFac = new SignalControlDataFactoryImpl(); - + // create signal system at node 3 Id signalSystemId = Id.create("SignalSystem-3", SignalSystem.class); SignalSystemData signalSystem = sysFac.createSignalSystemData(signalSystemId); signalSystems.addSignalSystemData(signalSystem); - + // create a signal for inLink 2_3 SignalData signal = sysFac.createSignalData(Id.create("Signal-2_3", Signal.class)); signalSystem.addSignalData(signal); signal.setLinkId(Id.createLinkId("2_3")); - + // create an one element group for the signal Id signalGroupId1 = Id.create("SignalGroup-2_3", SignalGroup.class); SignalGroupData signalGroup1 = signalGroups.getFactory().createSignalGroupData(signalSystemId, signalGroupId1); signalGroup1.addSignalId(Id.create("Signal-2_3", Signal.class)); signalGroups.addSignalGroupData(signalGroup1); - + // create the signal control SignalSystemControllerData signalSystemControl = conFac.createSignalSystemControllerData(signalSystemId); signalSystemControl.setControllerIdentifier(DefaultPlanbasedSignalSystemController.IDENTIFIER); signalControl.addSignalSystemControllerData(signalSystemControl); - + // create a first plan for the signal system (with cycle time 120) SignalPlanData signalPlan1 = SignalUtils.createSignalPlan(conFac, 120, offsetPlan1, Id.create("SignalPlan1", SignalPlan.class)); if (plan1StartTime != null) signalPlan1.setStartTime(plan1StartTime); if (plan1EndTime != null) signalPlan1.setEndTime(plan1EndTime); signalSystemControl.addSignalPlanData(signalPlan1); signalPlan1.addSignalGroupSettings(SignalUtils.createSetting4SignalGroup(conFac, signalGroupId1, 0, 60)); - + if (plan2StartTime != null && plan2EndTime != null) { // create a second plan for the signal system (with cycle time 60) if start and end times are not null SignalPlanData signalPlan2 = SignalUtils.createSignalPlan(conFac, 60, offsetPlan2, Id.create("SignalPlan2", SignalPlan.class)); @@ -718,47 +718,47 @@ private void createSignals() { private Config defineConfig() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); - + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + // set number of iterations - config.controler().setLastIteration(0); - + config.controller().setLastIteration(0); + config.qsim().setStartTime(simStart_h*3600); config.qsim().setUsingFastCapacityUpdate(false); - + // able or enable signals and lanes SignalSystemsConfigGroup signalConfigGroup = ConfigUtils.addOrGetModule(config, SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class); signalConfigGroup.setUseSignalSystems( true ); - + // define strategies: { StrategySettings strat = new StrategySettings(); strat.setStrategyName(DefaultSelector.KeepLastSelected.toString()); strat.setWeight(1); - strat.setDisableAfter(config.controler().getLastIteration()); - config.strategy().addStrategySettings(strat); - } + strat.setDisableAfter(config.controller().getLastIteration()); + config.replanning().addStrategySettings(strat); + } config.qsim().setStuckTime( 3600 ); config.qsim().setRemoveStuckVehicles(false); - - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - + + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.vspExperimental().setWritingOutputEvents(false); - config.planCalcScore().setWriteExperiencedPlans(false); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); - config.controler().setWriteEventsInterval(config.controler().getLastIteration()); - config.controler().setWritePlansInterval(config.controler().getLastIteration()); - + config.scoring().setWriteExperiencedPlans(false); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); + config.controller().setWriteEventsInterval(config.controller().getLastIteration()); + config.controller().setWritePlansInterval(config.controller().getLastIteration()); + // define activity types { ActivityParams dummyAct = new ActivityParams("dummy"); dummyAct.setTypicalDuration(12 * 3600); - config.planCalcScore().addActivityParams(dummyAct); + config.scoring().addActivityParams(dummyAct); } return config; } - + } private class SignalEventAnalyzer implements SignalGroupStateChangedEventHandler{ @@ -770,9 +770,9 @@ private class SignalEventAnalyzer implements SignalGroupStateChangedEventHandler Double firstSignalEventTime = null; double[] cycleTimesOfFirstCyclePerHour = new double[30]; int[] noSignalEventsPerHour = new int[30]; - + Double lastGreenSwitchOfThisCycle = null; - + @Override public void reset(int iteration) { } @@ -784,23 +784,23 @@ public double getCycleTimeOfFirstCycleInHour(int hourOfDay) { public Double getFirstSignalEventTime() { return firstSignalEventTime; } - + public Double getLastSignalOffEventTime() { return lastSignalOffEventTime; } - + public int getNumberOfSignalEventsInHour(int hourOfDay){ return noSignalEventsPerHour[hourOfDay]; } - + public int getNumberOfOffEvents() { return noOffEvents; } - + public Double getLastPlanStartEventTime() { return lastPlanStartEventTime; } - + public int getNumberOfPlanStartEvents() { return noPlanStartEvents; } @@ -810,11 +810,11 @@ public void handleEvent(SignalGroupStateChangedEvent event) { int hourOfDay = (int) (event.getTime() / 3600); // count number of signal events per hour noSignalEventsPerHour[hourOfDay]++; - + if (firstSignalEventTime == null){ firstSignalEventTime = event.getTime(); } - + if (event.getNewState().equals(SignalGroupState.OFF)){ lastSignalOffEventTime = event.getTime(); noOffEvents++; @@ -824,7 +824,7 @@ public void handleEvent(SignalGroupStateChangedEvent event) { noPlanStartEvents++; return; } - + // fill cycle time array if (cycleTimesOfFirstCyclePerHour[hourOfDay] == 0.0){ // first cycle time of this hour not yet determined @@ -840,7 +840,7 @@ public void handleEvent(SignalGroupStateChangedEvent event) { } } } - + } - + } diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/laemmerFix/LaemmerIT.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/laemmerFix/LaemmerIT.java index 2dde98241f7..d5e9aaf88ca 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/laemmerFix/LaemmerIT.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/laemmerFix/LaemmerIT.java @@ -46,7 +46,7 @@ import org.matsim.contrib.signals.model.SignalSystem; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -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.replanning.strategies.DefaultPlanStrategiesModule.DefaultSelector; @@ -66,14 +66,14 @@ public class LaemmerIT { @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); - + private static final int maxCycleTime = 90; private static final int cycleIntergreenTime = 10; private final Id signalGroupId1 = Id.create("SignalGroup1", SignalGroup.class); private final Id signalGroupId1l = Id.create("SignalGroup1l", SignalGroup.class); private final Id signalGroupId2 = Id.create("SignalGroup2", SignalGroup.class); private final Id signalSystemId = Id.create("SignalSystem1", SignalSystem.class); - + /** * single intersection with demand (equals flow capacity) only in NS-direction. signals should show green only for the NS-direction. */ @@ -89,19 +89,19 @@ public void testSingleCrossingScenarioDemandNS() { Map, Double> avgDelayPerLink = generalAnalyzer.getAvgDelayPerLink(); Double avgDelayWE = avgDelayPerLink.get(Id.createLinkId("2_3")); Double avgDelayNS = avgDelayPerLink.get(Id.createLinkId("7_3")); - + log.info("total signal green times: " + totalSignalGreenTimes.get(signalGroupId1) + ", " + totalSignalGreenTimes.get(signalGroupId2)); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycle.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycle.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystem.get(signalSystemId)); log.info("avg delay per link: " + avgDelayWE + ", " + avgDelayNS); - + Assert.assertNull("signal group 1 should show no green", avgSignalGreenTimePerCycle.get(signalGroupId1)); Assert.assertNotNull("signal group 2 should show green", avgSignalGreenTimePerCycle.get(signalGroupId2)); Assert.assertEquals("avg delay at NS-direction should be zero", 0.0, avgDelayNS, MatsimTestUtils.EPSILON); } - + /** * Test minimum green time: * single intersection with high demand in WE-direction, very low demand in NS-direction but minimum green time. I.e. the NS-signal should show green for exactly this 5 seconds per cycle. @@ -111,30 +111,30 @@ public void testSingleCrossingScenarioLowVsHighDemandWithMinG(){ Fixture fixture = new Fixture(90, 1800, 5.0, Regime.COMBINED); SignalAnalysisTool signalAnalyzer = new SignalAnalysisTool(); DelayAnalysisTool generalAnalyzer = fixture.run(signalAnalyzer); - - Map, Double> totalSignalGreenTimes = signalAnalyzer.getTotalSignalGreenTime(); - Map, Double> avgSignalGreenTimePerCycle = signalAnalyzer.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystem = signalAnalyzer.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> totalSignalGreenTimes = signalAnalyzer.getTotalSignalGreenTime(); + Map, Double> avgSignalGreenTimePerCycle = signalAnalyzer.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystem = signalAnalyzer.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLink = generalAnalyzer.getAvgDelayPerLink(); Double avgDelayWE = avgDelayPerLink.get(Id.createLinkId("2_3")); Double avgDelayNS = avgDelayPerLink.get(Id.createLinkId("7_3")); - + log.info("total signal green times: " + totalSignalGreenTimes.get(signalGroupId1) + ", " + totalSignalGreenTimes.get(signalGroupId2)); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycle.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycle.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystem.get(signalSystemId)); log.info("avg delay per link: " + avgDelayWE + ", " + avgDelayNS); - - Assert.assertTrue("total signal green time of WE-direction should be higher than NS-direction", + + Assert.assertTrue("total signal green time of WE-direction should be higher than NS-direction", totalSignalGreenTimes.get(signalGroupId1)-totalSignalGreenTimes.get(signalGroupId2) > 0); - Assert.assertTrue("avg signal green time per cycle of WE-direction should be higher than NS-direction", + Assert.assertTrue("avg signal green time per cycle of WE-direction should be higher than NS-direction", avgSignalGreenTimePerCycle.get(signalGroupId1)-avgSignalGreenTimePerCycle.get(signalGroupId2) > 0); - Assert.assertEquals("avg signal green time per cycle of NS-direction should be the minimum green time of 5 seconds", + Assert.assertEquals("avg signal green time per cycle of NS-direction should be the minimum green time of 5 seconds", 5.0, avgSignalGreenTimePerCycle.get(signalGroupId2), MatsimTestUtils.EPSILON); Assert.assertTrue("cycle time should stay below 90 seconds", avgCycleTimePerSystem.get(signalSystemId) <= 90); Assert.assertTrue("avg delay per vehicle on WS-direction should be less than on NS-direction", avgDelayWE, Double> totalSignalGreenTimes = signalAnalyzer.getTotalSignalGreenTime(); - Map, Double> avgSignalGreenTimePerCycle = signalAnalyzer.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystem = signalAnalyzer.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> totalSignalGreenTimes = signalAnalyzer.getTotalSignalGreenTime(); + Map, Double> avgSignalGreenTimePerCycle = signalAnalyzer.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystem = signalAnalyzer.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLink = generalAnalyzer.getAvgDelayPerLink(); Double avgDelayWE = avgDelayPerLink.get(Id.createLinkId("2_3")); Double avgDelayNS = avgDelayPerLink.get(Id.createLinkId("7_3")); - + log.info("total signal green times: " + totalSignalGreenTimes.get(signalGroupId1) + ", " + totalSignalGreenTimes.get(signalGroupId2)); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycle.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycle.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystem.get(signalSystemId)); log.info("avg delay per link: " + avgDelayWE + ", " + avgDelayNS); - - Assert.assertTrue("total signal green time of WE-direction should be higher than NS-direction", + + Assert.assertTrue("total signal green time of WE-direction should be higher than NS-direction", totalSignalGreenTimes.get(signalGroupId1)-totalSignalGreenTimes.get(signalGroupId2) > 0); - Assert.assertTrue("avg signal green time per cycle of WE-direction should be higher than NS-direction", + Assert.assertTrue("avg signal green time per cycle of WE-direction should be higher than NS-direction", avgSignalGreenTimePerCycle.get(signalGroupId1)-avgSignalGreenTimePerCycle.get(signalGroupId2) > 0); Assert.assertTrue("avg signal green time per cycle of NS-direction should be less than 5 seconds", avgSignalGreenTimePerCycle.get(signalGroupId2) < 5.0); Assert.assertTrue("cycle time should stay below 90 seconds", avgCycleTimePerSystem.get(signalSystemId) <= 90); Assert.assertTrue("avg delay per vehicle on WS-direction should be less than on NS-direction", avgDelayWE, Double> totalSignalGreenTimes = signalAnalyzer.getTotalSignalGreenTime(); - Map, Double> avgSignalGreenTimePerCycle = signalAnalyzer.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystem = signalAnalyzer.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> totalSignalGreenTimes = signalAnalyzer.getTotalSignalGreenTime(); + Map, Double> avgSignalGreenTimePerCycle = signalAnalyzer.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystem = signalAnalyzer.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLink = generalAnalyzer.getAvgDelayPerLink(); Double avgDelayWE = avgDelayPerLink.get(Id.createLinkId("2_3")); Double avgDelayNS = avgDelayPerLink.get(Id.createLinkId("7_3")); - + log.info("total signal green times: " + totalSignalGreenTimes.get(signalGroupId1) + ", " + totalSignalGreenTimes.get(signalGroupId2)); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycle.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycle.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystem.get(signalSystemId)); log.info("avg delay per link: " + avgDelayWE + ", " + avgDelayNS); - - Assert.assertEquals("total signal green times should not differ more than 1%", 1, + + Assert.assertEquals("total signal green times should not differ more than 1%", 1, totalSignalGreenTimes.get(signalGroupId1)/totalSignalGreenTimes.get(signalGroupId2), 0.01); - Assert.assertEquals("avg signal green times per cycle should not differ more than 1%", + Assert.assertEquals("avg signal green times per cycle should not differ more than 1%", 1, avgSignalGreenTimePerCycle.get(signalGroupId1)/avgSignalGreenTimePerCycle.get(signalGroupId2), 0.01); // Assert.assertEquals("avg delay per vehicle per link should not differ more than 5%", 1, avgDelayWE/avgDelayNS, 0.05); /* I commented the last line out because the delay strongly depends on the stabilizing regime, namely the arrival rates that are used. @@ -218,40 +218,40 @@ public void testSingleCrossingScenarioStabilizingVsOptimizingRegimeLowDemand(){ Fixture fixtureComb = new Fixture(360, 1440, 0.0, Regime.COMBINED); SignalAnalysisTool signalAnalyzerComb = new SignalAnalysisTool(); DelayAnalysisTool generalAnalyzerComb = fixtureComb.run(signalAnalyzerComb); - - Map, Double> avgSignalGreenTimePerCycleStab = signalAnalyzerStab.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystemStab = signalAnalyzerStab.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> avgSignalGreenTimePerCycleStab = signalAnalyzerStab.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystemStab = signalAnalyzerStab.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLinkStab = generalAnalyzerStab.getAvgDelayPerLink(); - + log.info("demand 360,1440 (i.e. 0.5) -- results for the stabilizing regime:"); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycleStab.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycleStab.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystemStab.get(signalSystemId)); log.info("avg delay per link: " + avgDelayPerLinkStab.get(Id.createLinkId("2_3")) + ", " + avgDelayPerLinkStab.get(Id.createLinkId("7_3"))); log.info("Total delay: " + generalAnalyzerStab.getTotalDelay()); - - Map, Double> avgSignalGreenTimePerCycleOpt = signalAnalyzerOpt.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystemOpt = signalAnalyzerOpt.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> avgSignalGreenTimePerCycleOpt = signalAnalyzerOpt.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystemOpt = signalAnalyzerOpt.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLinkOpt = generalAnalyzerOpt.getAvgDelayPerLink(); - + log.info("demand 360,1440 (i.e. 0.5) -- results for the optimizing regime:"); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycleOpt.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycleOpt.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystemOpt.get(signalSystemId)); log.info("avg delay per link: " + avgDelayPerLinkOpt.get(Id.createLinkId("2_3")) + ", " + avgDelayPerLinkOpt.get(Id.createLinkId("7_3"))); log.info("Total delay: " + generalAnalyzerOpt.getTotalDelay()); - - Map, Double> avgSignalGreenTimePerCycleComb = signalAnalyzerComb.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystemComb = signalAnalyzerComb.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> avgSignalGreenTimePerCycleComb = signalAnalyzerComb.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystemComb = signalAnalyzerComb.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLinkComb = generalAnalyzerComb.getAvgDelayPerLink(); - + log.info("demand 360,1440 (i.e. 0.5) -- results for the combined regime:"); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycleComb.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycleComb.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystemComb.get(signalSystemId)); log.info("avg delay per link: " + avgDelayPerLinkComb.get(Id.createLinkId("2_3")) + ", " + avgDelayPerLinkComb.get(Id.createLinkId("7_3"))); log.info("Total delay: " + generalAnalyzerComb.getTotalDelay()); - + // Test Stabilizing Regime: for (Id linkId : avgDelayPerLinkStab.keySet()) { Assert.assertTrue("stab: avg delay per link should be below a threshold (i.e. still stable)", avgDelayPerLinkStab.get(linkId) < maxCycleTime); @@ -260,36 +260,36 @@ public void testSingleCrossingScenarioStabilizingVsOptimizingRegimeLowDemand(){ Assert.assertTrue("stab: total delay should be higher than for the other regimes", generalAnalyzerStab.getTotalDelay() > generalAnalyzerComb.getTotalDelay()); Assert.assertTrue("the stabilizing regime should satisfy the maximum cycle time", avgCycleTimePerSystemStab.get(signalSystemId) < maxCycleTime); // stabilizing regime only shows green when number of vehicles beyond a critical number, i.e. some of the cycle time is given away (all signals show red) - Assert.assertTrue("stab: sum of green times per cycle plus 10 seconds intergreen time should be more than 10 seconds less than the avg cycle time", - avgSignalGreenTimePerCycleStab.get(signalGroupId1) + avgSignalGreenTimePerCycleStab.get(signalGroupId2) + cycleIntergreenTime + Assert.assertTrue("stab: sum of green times per cycle plus 10 seconds intergreen time should be more than 10 seconds less than the avg cycle time", + avgSignalGreenTimePerCycleStab.get(signalGroupId1) + avgSignalGreenTimePerCycleStab.get(signalGroupId2) + cycleIntergreenTime < avgCycleTimePerSystemStab.get(signalSystemId) - 10); - + // Test Optimizing Regime: for (Id linkId : avgDelayPerLinkOpt.keySet()) { Assert.assertTrue("opt: avg delay per link should be below a threshold (i.e. still stable)", avgDelayPerLinkOpt.get(linkId) < maxCycleTime); } - Assert.assertEquals("sum of green times per cycle plus 10 seconds intergreen time should be more or less equal to the avg cycle time", - avgCycleTimePerSystemOpt.get(signalSystemId), - avgSignalGreenTimePerCycleOpt.get(signalGroupId1) + avgSignalGreenTimePerCycleOpt.get(signalGroupId2) + cycleIntergreenTime, + Assert.assertEquals("sum of green times per cycle plus 10 seconds intergreen time should be more or less equal to the avg cycle time", + avgCycleTimePerSystemOpt.get(signalSystemId), + avgSignalGreenTimePerCycleOpt.get(signalGroupId1) + avgSignalGreenTimePerCycleOpt.get(signalGroupId2) + cycleIntergreenTime, 2); - Assert.assertTrue("for this demand, the cycle time of the optimizing regime should be still reasonable, i.e. below a threshold", + Assert.assertTrue("for this demand, the cycle time of the optimizing regime should be still reasonable, i.e. below a threshold", avgCycleTimePerSystemOpt.get(signalSystemId) < maxCycleTime); - + // Test Combined Regime: for (Id linkId : avgDelayPerLinkComb.keySet()) { Assert.assertTrue("avg delay per link should be below a threshold (i.e. still stable)", avgDelayPerLinkComb.get(linkId) < maxCycleTime); } - Assert.assertEquals("comb: sum of green times per cycle plus 10 seconds intergreen time should be more or less equal to the avg cycle time", - avgCycleTimePerSystemComb.get(signalSystemId), - avgSignalGreenTimePerCycleComb.get(signalGroupId1) + avgSignalGreenTimePerCycleComb.get(signalGroupId2) + cycleIntergreenTime, + Assert.assertEquals("comb: sum of green times per cycle plus 10 seconds intergreen time should be more or less equal to the avg cycle time", + avgCycleTimePerSystemComb.get(signalSystemId), + avgSignalGreenTimePerCycleComb.get(signalGroupId1) + avgSignalGreenTimePerCycleComb.get(signalGroupId2) + cycleIntergreenTime, 2); Assert.assertTrue("the combined regime should satisfy the maximum cycle time", avgCycleTimePerSystemComb.get(signalSystemId) < maxCycleTime); Assert.assertTrue("total delay with the combined regime should be the lowest", generalAnalyzerOpt.getTotalDelay() > generalAnalyzerComb.getTotalDelay()); } - + /** * compare different regimes for laemmer: stabilizing, optimizing and combination of both (combined) - * for high demand, i.e. an occupancy rate of 0.6 in the example of nico kuehnel's master thesis, the optimizing regime should no longer be stable (high delays, high travel time, + * for high demand, i.e. an occupancy rate of 0.6 in the example of nico kuehnel's master thesis, the optimizing regime should no longer be stable (high delays, high travel time, * no standard cycle pattern). The stabilizing regime should still be stable, the combined regime should be the best. */ @Test @@ -305,63 +305,63 @@ public void testSingleCrossingScenarioStabilizingVsOptimizingRegimeHighDemand(){ Fixture fixtureComb = new Fixture(360, 1800, 0.0, Regime.COMBINED); SignalAnalysisTool signalAnalyzerComb = new SignalAnalysisTool(); DelayAnalysisTool generalAnalyzerComb = fixtureComb.run(signalAnalyzerComb); - - Map, Double> avgSignalGreenTimePerCycleStab = signalAnalyzerStab.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystemStab = signalAnalyzerStab.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> avgSignalGreenTimePerCycleStab = signalAnalyzerStab.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystemStab = signalAnalyzerStab.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLinkStab = generalAnalyzerStab.getAvgDelayPerLink(); - + log.info("demand 360,1800 (i.e. 0.6) -- results for the stabilizing regime:"); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycleStab.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycleStab.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystemStab.get(signalSystemId)); log.info("avg delay per link: " + avgDelayPerLinkStab.get(Id.createLinkId("2_3")) + ", " + avgDelayPerLinkStab.get(Id.createLinkId("7_3"))); log.info("Total delay: " + generalAnalyzerStab.getTotalDelay()); - - Map, Double> avgSignalGreenTimePerCycleOpt = signalAnalyzerOpt.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystemOpt = signalAnalyzerOpt.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> avgSignalGreenTimePerCycleOpt = signalAnalyzerOpt.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystemOpt = signalAnalyzerOpt.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLinkOpt = generalAnalyzerOpt.getAvgDelayPerLink(); - + log.info("demand 360,1800 (i.e. 0.6) -- results for the optimizing regime:"); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycleOpt.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycleOpt.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystemOpt.get(signalSystemId)); log.info("avg delay per link: " + avgDelayPerLinkOpt.get(Id.createLinkId("2_3")) + ", " + avgDelayPerLinkOpt.get(Id.createLinkId("7_3"))); log.info("Total delay: " + generalAnalyzerOpt.getTotalDelay()); - - Map, Double> avgSignalGreenTimePerCycleComb = signalAnalyzerComb.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystemComb = signalAnalyzerComb.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> avgSignalGreenTimePerCycleComb = signalAnalyzerComb.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystemComb = signalAnalyzerComb.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLinkComb = generalAnalyzerComb.getAvgDelayPerLink(); - + log.info("demand 360,1800 (i.e. 0.6) -- results for the combined regime:"); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycleComb.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycleComb.get(signalGroupId2)); log.info("avg cycle time per system: " + avgCycleTimePerSystemComb.get(signalSystemId)); log.info("avg delay per link: " + avgDelayPerLinkComb.get(Id.createLinkId("2_3")) + ", " + avgDelayPerLinkComb.get(Id.createLinkId("7_3"))); log.info("Total delay: " + generalAnalyzerComb.getTotalDelay()); - + // Test Stabilizing Regime: for (Id linkId : avgDelayPerLinkStab.keySet()) { Assert.assertTrue("stab: avg delay per link should be below a threshold (i.e. still stable)", avgDelayPerLinkStab.get(linkId) < maxCycleTime); } Assert.assertTrue("the stabilizing regime should satisfy the maximum cycle time", avgCycleTimePerSystemStab.get(signalSystemId) < maxCycleTime); // stabilizing regime only shows green when number of vehicles beyond a critical number, i.e. some of the cycle time is given away (all signals show red) - Assert.assertTrue("stab: sum of green times per cycle plus 10 seconds intergreen time should be more than 9 seconds less than the avg cycle time", - avgSignalGreenTimePerCycleStab.get(signalGroupId1) + avgSignalGreenTimePerCycleStab.get(signalGroupId2) + cycleIntergreenTime + Assert.assertTrue("stab: sum of green times per cycle plus 10 seconds intergreen time should be more than 9 seconds less than the avg cycle time", + avgSignalGreenTimePerCycleStab.get(signalGroupId1) + avgSignalGreenTimePerCycleStab.get(signalGroupId2) + cycleIntergreenTime < avgCycleTimePerSystemStab.get(signalSystemId) - 9); - + // Test Optimizing Regime: Assert.assertTrue("avg delay for NS-direction should be very high for the optimizing regime with high demand", avgDelayPerLinkOpt.get(Id.createLinkId("7_3")) > maxCycleTime); Assert.assertTrue("total delay of optimizing regime should be the highest", generalAnalyzerStab.getTotalDelay() < generalAnalyzerOpt.getTotalDelay()); - Assert.assertTrue("for this demand, the cycle time of the optimizing regime should be very high, i.e. not stable anymore", + Assert.assertTrue("for this demand, the cycle time of the optimizing regime should be very high, i.e. not stable anymore", avgCycleTimePerSystemOpt.get(signalSystemId) > 10*maxCycleTime); - + // Test Combined Regime: for (Id linkId : avgDelayPerLinkComb.keySet()) { Assert.assertTrue("avg delay per link should be below a threshold (i.e. still stable)", avgDelayPerLinkComb.get(linkId) < maxCycleTime); } - Assert.assertEquals("comb: sum of green times per cycle plus 10 seconds intergreen time should be more or less equal to the avg cycle time", - avgCycleTimePerSystemComb.get(signalSystemId), - avgSignalGreenTimePerCycleComb.get(signalGroupId1) + avgSignalGreenTimePerCycleComb.get(signalGroupId2) + cycleIntergreenTime, + Assert.assertEquals("comb: sum of green times per cycle plus 10 seconds intergreen time should be more or less equal to the avg cycle time", + avgCycleTimePerSystemComb.get(signalSystemId), + avgSignalGreenTimePerCycleComb.get(signalGroupId1) + avgSignalGreenTimePerCycleComb.get(signalGroupId2) + cycleIntergreenTime, 2); Assert.assertTrue("the combined regime should satisfy the maximum cycle time", avgCycleTimePerSystemComb.get(signalSystemId) < maxCycleTime); Assert.assertTrue("total delay with the combined regime should be the lowest", generalAnalyzerOpt.getTotalDelay() > generalAnalyzerComb.getTotalDelay()); @@ -378,17 +378,17 @@ public void testSingleCrossingScenarioWithDifferentFlowCapacityFactors(){ Fixture fixtureFlowCap1 = new Fixture(360, 1800, 0.0, Regime.COMBINED); SignalAnalysisTool signalAnalyzerFlowCap1 = new SignalAnalysisTool(); DelayAnalysisTool generalAnalyzerFlowCap1 = fixtureFlowCap1.run(signalAnalyzerFlowCap1); - + Fixture fixtureFlowCap2 = new Fixture(360, 1800, 0.0, Regime.COMBINED); fixtureFlowCap2.doublePopulation(); SignalAnalysisTool signalAnalyzerFlowCap2 = new SignalAnalysisTool(); DelayAnalysisTool generalAnalyzerFlowCap2 = fixtureFlowCap2.run(signalAnalyzerFlowCap2); - - Map, Double> totalSignalGreenTimesFlowCap2 = signalAnalyzerFlowCap2.getTotalSignalGreenTime(); - Map, Double> avgSignalGreenTimePerCycleFlowCap2 = signalAnalyzerFlowCap2.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystemFlowCap2 = signalAnalyzerFlowCap2.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> totalSignalGreenTimesFlowCap2 = signalAnalyzerFlowCap2.getTotalSignalGreenTime(); + Map, Double> avgSignalGreenTimePerCycleFlowCap2 = signalAnalyzerFlowCap2.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystemFlowCap2 = signalAnalyzerFlowCap2.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLinkFlowCap2 = generalAnalyzerFlowCap2.getAvgDelayPerLink(); - + log.info("*** flow capacity 2.0 ***"); log.info("total signal green times: " + totalSignalGreenTimesFlowCap2.get(signalGroupId1) + ", " + totalSignalGreenTimesFlowCap2.get(signalGroupId2)); log.info("avg signal green times per cycle: " + avgSignalGreenTimePerCycleFlowCap2.get(signalGroupId1) + ", " @@ -396,10 +396,10 @@ public void testSingleCrossingScenarioWithDifferentFlowCapacityFactors(){ log.info("avg cycle time per system: " + avgCycleTimePerSystemFlowCap2.get(signalSystemId)); log.info("avg delay per link: " + avgDelayPerLinkFlowCap2.get(Id.createLinkId("2_3")) + ", " + avgDelayPerLinkFlowCap2.get(Id.createLinkId("7_3"))); log.info("Total delay: " + generalAnalyzerFlowCap2.getTotalDelay()); - - Map, Double> totalSignalGreenTimesFlowCap1 = signalAnalyzerFlowCap1.getTotalSignalGreenTime(); - Map, Double> avgSignalGreenTimePerCycleFlowCap1 = signalAnalyzerFlowCap1.calculateAvgSignalGreenTimePerFlexibleCycle(); - Map, Double> avgCycleTimePerSystemFlowCap1 = signalAnalyzerFlowCap1.calculateAvgFlexibleCycleTimePerSignalSystem(); + + Map, Double> totalSignalGreenTimesFlowCap1 = signalAnalyzerFlowCap1.getTotalSignalGreenTime(); + Map, Double> avgSignalGreenTimePerCycleFlowCap1 = signalAnalyzerFlowCap1.calculateAvgSignalGreenTimePerFlexibleCycle(); + Map, Double> avgCycleTimePerSystemFlowCap1 = signalAnalyzerFlowCap1.calculateAvgFlexibleCycleTimePerSignalSystem(); Map, Double> avgDelayPerLinkFlowCap1 = generalAnalyzerFlowCap1.getAvgDelayPerLink(); log.info("*** flow capacity 1.0 ***"); @@ -409,24 +409,24 @@ public void testSingleCrossingScenarioWithDifferentFlowCapacityFactors(){ log.info("avg cycle time per system: " + avgCycleTimePerSystemFlowCap1.get(signalSystemId)); log.info("avg delay per link: " + avgDelayPerLinkFlowCap1.get(Id.createLinkId("2_3")) + ", " + avgDelayPerLinkFlowCap1.get(Id.createLinkId("7_3"))); log.info("Total delay: " + generalAnalyzerFlowCap1.getTotalDelay()); - - Assert.assertEquals("total signal green times should not differ", 1, + + Assert.assertEquals("total signal green times should not differ", 1, totalSignalGreenTimesFlowCap1.get(signalGroupId1)/totalSignalGreenTimesFlowCap2.get(signalGroupId1), 0.01); - Assert.assertEquals("total signal green times should not differ", 1, + Assert.assertEquals("total signal green times should not differ", 1, totalSignalGreenTimesFlowCap1.get(signalGroupId2)/totalSignalGreenTimesFlowCap2.get(signalGroupId2), 0.01); - Assert.assertEquals("avg signal green times per cycle should not differ", avgSignalGreenTimePerCycleFlowCap1.get(signalGroupId1), + Assert.assertEquals("avg signal green times per cycle should not differ", avgSignalGreenTimePerCycleFlowCap1.get(signalGroupId1), avgSignalGreenTimePerCycleFlowCap2.get(signalGroupId1), 0.1); - Assert.assertEquals("avg signal green times per cycle should not differ", avgSignalGreenTimePerCycleFlowCap1.get(signalGroupId2), + Assert.assertEquals("avg signal green times per cycle should not differ", avgSignalGreenTimePerCycleFlowCap1.get(signalGroupId2), avgSignalGreenTimePerCycleFlowCap2.get(signalGroupId2), 0.1); Assert.assertEquals("avg cycle time should not differ", avgCycleTimePerSystemFlowCap1.get(signalSystemId), avgCycleTimePerSystemFlowCap2.get(signalSystemId), 0.1); - Assert.assertEquals("avg delay per vehicle per link should not differ", + Assert.assertEquals("avg delay per vehicle per link should not differ", avgDelayPerLinkFlowCap1.get(Id.createLinkId("2_3")), avgDelayPerLinkFlowCap2.get(Id.createLinkId("2_3")), 0.1); - Assert.assertEquals("avg delay per vehicle per link should not differ", + Assert.assertEquals("avg delay per vehicle per link should not differ", avgDelayPerLinkFlowCap1.get(Id.createLinkId("7_3")), avgDelayPerLinkFlowCap2.get(Id.createLinkId("7_3")), 2); Assert.assertEquals("total delay for doubled demand should be doubled", 2, generalAnalyzerFlowCap2.getTotalDelay()/generalAnalyzerFlowCap1.getTotalDelay(), 0.1); } - + /** * Test Laemmer with multiple iterations (some variables have to be reset after iterations). */ @@ -444,7 +444,7 @@ public void testMultipleIterations() { Map, Double> avgDelayPerLink0It = generalAnalyzer0It.getAvgDelayPerLink(); Double avgDelayWE0It = avgDelayPerLink0It.get(Id.createLinkId("2_3")); Double avgDelayNS0It = avgDelayPerLink0It.get(Id.createLinkId("7_3")); - + log.info("total signal green times in iteration 0: " + totalSignalGreenTimes0It.get(signalGroupId1) + ", " + totalSignalGreenTimes0It.get(signalGroupId1l) + ", " + totalSignalGreenTimes0It.get(signalGroupId2)); log.info("avg signal green times per cycle in itertion 0: " + avgSignalGreenTimePerCycle0It.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycle0It.get(signalGroupId1l) + ", " @@ -452,7 +452,7 @@ public void testMultipleIterations() { log.info("avg cycle time per system in itertion 0: " + avgCycleTimePerSystem0It.get(signalSystemId)); log.info("avg delay per link in itertion 0: " + avgDelayWE0It + ", " + avgDelayNS0It); - + Fixture fixture1It = new Fixture(500, 2000, 5.0, Regime.COMBINED); int lastIt = 1; fixture1It.setLastIteration(lastIt); @@ -466,7 +466,7 @@ public void testMultipleIterations() { Map, Double> avgDelayPerLink1It = generalAnalyzer1It.getAvgDelayPerLink(); Double avgDelayWE1It = avgDelayPerLink1It.get(Id.createLinkId("2_3")); Double avgDelayNS1It = avgDelayPerLink1It.get(Id.createLinkId("7_3")); - + log.info("total signal green times in itertion 1: " + totalSignalGreenTimes1It.get(signalGroupId1) + ", " + totalSignalGreenTimes1It.get(signalGroupId1l) + ", " + totalSignalGreenTimes1It.get(signalGroupId2)); log.info("avg signal green times per cycle in itertion 1: " + avgSignalGreenTimePerCycle1It.get(signalGroupId1) + ", " + avgSignalGreenTimePerCycle1It.get(signalGroupId1l) + ", " @@ -474,7 +474,7 @@ public void testMultipleIterations() { log.info("avg cycle time per system in itertion 1: " + avgCycleTimePerSystem1It.get(signalSystemId)); log.info("avg delay per link in itertion 1: " + avgDelayWE1It + ", " + avgDelayNS1It); - + Assert.assertEquals("total green time of signal group 1 should be the same as in the first iteration", totalSignalGreenTimes0It.get(signalGroupId1), totalSignalGreenTimes1It.get(signalGroupId1), MatsimTestUtils.EPSILON); Assert.assertEquals("total green time of signal group 1l should be the same as in the first iteration", totalSignalGreenTimes0It.get(signalGroupId1l), totalSignalGreenTimes1It.get(signalGroupId1l), MatsimTestUtils.EPSILON); Assert.assertEquals("total green time of signal group 2 should be the same as in the first iteration", totalSignalGreenTimes0It.get(signalGroupId2), totalSignalGreenTimes1It.get(signalGroupId2), MatsimTestUtils.EPSILON); @@ -489,29 +489,29 @@ public void testMultipleIterations() { long checksum_itLast = CRCChecksum.getCRCFromFile(testUtils.getOutputDirectory() + "ITERS/it."+lastIt+"/signalEvents2Via.csv"); Assert.assertEquals("Signal events are different", checksum_it0, checksum_itLast); } - + // TODO test stochasticity (laemmer better than fixed-time; different than for constant demand) // TODO test temporarily overcrowded situations (no exeption; signal is able to resolve congestion; like fixed-time schedule; cycle times get longer when overload continues) // TODO test liveArrivalRate (with/without time buckets) vs. exact data (the second results in more precise green times?!; liveArrivalRates are determined correctly) // TODO test grouping // TODO test lanes // ... - + private class Fixture { - + private Scenario scenario; private double flowNS; private double flowWE; - + Fixture(double flowNS, double flowWE, double minG, Regime regime) { this.flowWE = flowWE; this.flowNS = flowNS; - + // create Config Config config = ConfigUtils.loadConfig("./examples/tutorial/singleCrossingScenario/config.xml"); config.plans().setInputFile(null); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); - + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + LaemmerConfigGroup laemmerConfigGroup = ConfigUtils.addOrGetModule(config, LaemmerConfigGroup.GROUP_NAME, LaemmerConfigGroup.class); laemmerConfigGroup.setMinGreenTime(minG); @@ -534,33 +534,33 @@ private class Fixture { lanesOfLink43.getLanes().get(Id.create("4_3.r", Lane.class)).setCapacityVehiclesPerHour(0); lanesOfLink43.getLanes().get(Id.create("4_3.s", Lane.class)).setCapacityVehiclesPerHour(3600); } - + void doublePopulation() { scenario.getConfig().qsim().setFlowCapFactor(2.0); createSimplePopulationWithoutLeftTurns(scenario.getPopulation(), flowNS, flowWE, "-2"); } - + void addLeftTurnTraffic() { String[] linksWEleft = {"1_2-6_7", "5_4-8_9"}; createPopulationForRelation(0.1 * flowWE, scenario.getPopulation(), linksWEleft, "-left"); } - + void setLastIteration(int lastIteration) { - scenario.getConfig().controler().setLastIteration(lastIteration); + scenario.getConfig().controller().setLastIteration(lastIteration); // add replanning strategy StrategySettings strat = new StrategySettings(); strat.setStrategyName(DefaultSelector.KeepLastSelected.toString()); strat.setWeight(1.); - scenario.getConfig().strategy().addStrategySettings(strat); + scenario.getConfig().replanning().addStrategySettings(strat); } - + DelayAnalysisTool run(SignalAnalysisTool signalAnalyzer) { Controler controler = new Controler( scenario ); - + // add the signals module // controler.addOverridingModule(new SignalsModule()); Signals.configure( controler ); - + // add signal analysis tool controler.addOverridingModule(new AbstractModule() { @Override @@ -577,13 +577,13 @@ public void install() { this.addEventHandlerBinding().toInstance(delayAnalysis); } }); - + // run the simulation controler.run(); - + return delayAnalysis; } - + private void createSimplePopulationWithoutLeftTurns(Population pop, double flowNS, double flowWE, String idPostFix) { String[] linksNS = {"6_7-8_9", "9_8-7_6"}; String[] linksWE = {"5_4-2_1", "1_2-4_5"}; @@ -591,7 +591,7 @@ private void createSimplePopulationWithoutLeftTurns(Population pop, double flowN createPopulationForRelation(flowNS, pop, linksNS, idPostFix); createPopulationForRelation(flowWE, pop, linksWE, idPostFix); } - + private void createPopulationForRelation(double flow, Population population, String[] links, String idPostFix) { if (flow == 0) { return; @@ -631,7 +631,7 @@ private void createPerson(Population population, String fromLinkId, String toLin Id.createLinkId(toLinkId)); plan.addActivity(drainAct); } - + } } diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/sylvia/SylviaIT.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/sylvia/SylviaIT.java index 4ec520760c8..3954235366d 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/sylvia/SylviaIT.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/controller/sylvia/SylviaIT.java @@ -60,8 +60,8 @@ import org.matsim.contrib.signals.utils.SignalUtils; 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.StrategyConfigGroup.StrategySettings; +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.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -74,10 +74,10 @@ /** * Test sylvia logic at an intersection with four incoming links and one signal each. * No lanes are used. - * + * * It is tested whether sylvia expands signal phases correctly when more vehicles want to pass * and whether cycle times are kept. - * + * * @author tthunig * */ @@ -94,7 +94,7 @@ public class SylviaIT { * used. The two approaches have equal demand but different priority in the * Sylvia signal algorithm. The priority is given by the order in the signal * plan. In this test, signal group 1 has priority over 2. - * + * * note: signal settings of the fixed time plan are unbalanced with 5 seconds * for signal group 1 vs. 45 seconds for signal group 2. but signal settings of * the sylvia plan are balanced, because each setting is shortend to 5 seconds @@ -123,16 +123,16 @@ public void testDemandABPrioA() { Assert.assertEquals("avg green time per cycle of signal group 1 is wrong", 30, avgSignalGreenTimePerCycle.get(signalGroupId1), 1); Assert.assertEquals("avg green time per cycle of signal group 2 is wrong", 20, avgSignalGreenTimePerCycle.get(signalGroupId2), 1); // can differ from the fixed cycle length because the analysis is quit after the last activity start event - Assert.assertEquals("avg cycle time of the system is wrong", 60, avgCycleTimePerSystem.get(signalSystemId), 1); + Assert.assertEquals("avg cycle time of the system is wrong", 60, avgCycleTimePerSystem.get(signalSystemId), 1); } - + /** * Test sylvia with two conflicting streams at a single intersection. A fixed * cycle time (of 60 seconds) and no maximal extension time per setting are * used. The two approaches have equal demand but different priority in the * Sylvia signal algorithm. The priority is given by the order in the signal * plan. In this test, signal group 2 has priority over 1. - * + * * note: signal settings of the fixed time plan are unbalanced with 5 seconds * for signal group 1 vs. 45 seconds for signal group 2. but signal settings of * the sylvia plan are balanced, because each setting is shortend to 5 seconds @@ -162,7 +162,7 @@ public void testDemandABPrioB() { Assert.assertEquals("avg green time per cycle of signal group 2 is wrong", 30, avgSignalGreenTimePerCycle.get(signalGroupId2), 1); Assert.assertEquals("avg green time per cycle of signal group 1 is wrong", 20, avgSignalGreenTimePerCycle.get(signalGroupId1), 1); // can differ from the fixed cycle length because the analysis is quit after the last activity start event - Assert.assertEquals("avg cycle time of the system is wrong", 60, avgCycleTimePerSystem.get(signalSystemId), 1); + Assert.assertEquals("avg cycle time of the system is wrong", 60, avgCycleTimePerSystem.get(signalSystemId), 1); } /** @@ -228,7 +228,7 @@ private void createScenarioElements(Scenario scenario, double[] noPersons, int o /** * creates a network like this: - * + * * 6 * ^ * | @@ -245,8 +245,8 @@ private void createScenarioElements(Scenario scenario, double[] noPersons, int o * ^ * | * v - * 9 - * + * 9 + * * @param net * the object where the network should be stored */ @@ -365,10 +365,10 @@ private void createSignals(Scenario scenario, int offset) { private Config defineConfig() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); // set number of iterations - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); // able or enable signals and lanes SignalSystemsConfigGroup signalConfigGroup = ConfigUtils.addOrGetModule(config, SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class); @@ -389,8 +389,8 @@ private Config defineConfig() { StrategySettings strat = new StrategySettings(); strat.setStrategyName(DefaultSelector.KeepLastSelected.toString()); strat.setWeight(0.9); - strat.setDisableAfter(config.controler().getLastIteration()); - config.strategy().addStrategySettings(strat); + strat.setDisableAfter(config.controller().getLastIteration()); + config.replanning().addStrategySettings(strat); } // choose maximal number of plans per agent. 0 means unlimited @@ -403,21 +403,21 @@ private Config defineConfig() { config.qsim().setEndTime(3 * 3600); config.qsim().setUsingFastCapacityUpdate(false); - - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); config.vspExperimental().setWritingOutputEvents(false); - config.planCalcScore().setWriteExperiencedPlans(false); - config.controler().setCreateGraphs(false); + config.scoring().setWriteExperiencedPlans(false); + config.controller().setCreateGraphs(false); - config.controler().setWriteEventsInterval(config.controler().getLastIteration()); - config.controler().setWritePlansInterval(config.controler().getLastIteration()); + config.controller().setWriteEventsInterval(config.controller().getLastIteration()); + config.controller().setWritePlansInterval(config.controller().getLastIteration()); // define activity types { ActivityParams dummyAct = new ActivityParams("dummy"); dummyAct.setTypicalDuration(12 * 3600); - config.planCalcScore().addActivityParams(dummyAct); + config.scoring().addActivityParams(dummyAct); } return config; diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/data/conflicts/UnprotectedLeftTurnLogicTest.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/data/conflicts/UnprotectedLeftTurnLogicTest.java index 29b171fbdf6..e33fed5dc46 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/data/conflicts/UnprotectedLeftTurnLogicTest.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/data/conflicts/UnprotectedLeftTurnLogicTest.java @@ -43,14 +43,14 @@ public class UnprotectedLeftTurnLogicTest { @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); - + @Test public void testSingleIntersectionScenarioWithLeftTurns() { // run scenarios from files AnalyzeSingleIntersectionLeftTurnDelays restrictedLeftTurns = runSimulation(IntersectionLogic.CONFLICTING_DIRECTIONS_AND_TURN_RESTRICTIONS); AnalyzeSingleIntersectionLeftTurnDelays unrestrictedLeftTurns = runSimulation(IntersectionLogic.CONFLICTING_DIRECTIONS_NO_TURN_RESTRICTIONS); AnalyzeSingleIntersectionLeftTurnDelays noLogic = runSimulation(IntersectionLogic.NONE); - + double leftTurnDelayWTurnRestriction = restrictedLeftTurns.getLeftTurnDelay(); double leftTurnDelayWoTurnRestriction = unrestrictedLeftTurns.getLeftTurnDelay(); double leftTurnDelayWithoutLogic = noLogic.getLeftTurnDelay(); @@ -69,30 +69,30 @@ private AnalyzeSingleIntersectionLeftTurnDelays runSimulation(IntersectionLogic SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class); signalsConfigGroup.setSignalControlFile("signalControlFixedTime.xml"); signalsConfigGroup.setIntersectionLogic(intersectionLogic); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + intersectionLogic + "/"); - + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + intersectionLogic + "/"); + Scenario scenario = ScenarioUtils.loadScenario( config ) ; scenario.addScenarioElement(SignalsData.ELEMENT_NAME, new SignalsDataLoader(config).loadSignalsData()); - + Controler controler = new Controler( scenario ); - + // add the signals module // controler.addOverridingModule(new SignalsModule()); Signals.configure(controler); - + // add analysis tools AnalyzeSingleIntersectionLeftTurnDelays handler = new AnalyzeSingleIntersectionLeftTurnDelays(); - controler.addOverridingModule(new AbstractModule() { + controler.addOverridingModule(new AbstractModule() { @Override public void install() { this.addEventHandlerBinding().toInstance(handler); } }); - + // run the simulation controler.run(); - + return handler; } - + } diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/integration/SignalSystemsIT.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/integration/SignalSystemsIT.java index e8eabb57027..96b73fa8a3d 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/integration/SignalSystemsIT.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/integration/SignalSystemsIT.java @@ -45,64 +45,64 @@ * */ public class SignalSystemsIT { - + private final static String CONFIG_FILE_NAME = "signalSystemsIntegrationConfig.xml"; - + @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); - + @Test public void testSignalSystems() { Config config = testUtils.loadConfig(testUtils.getClassInputDirectory() + CONFIG_FILE_NAME); config.plans().setActivityDurationInterpretation(PlansConfigGroup.ActivityDurationInterpretation.minOfDurationAndEndTime); String controlerOutputDir = testUtils.getOutputDirectory() + "controlerOutput/"; - + config.network().setLaneDefinitionsFile("testLaneDefinitions_v2.0.xml"); - config.controler().setWriteEventsInterval(10); - config.controler().setWritePlansInterval(10); - - config.controler().setOutputDirectory(controlerOutputDir); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); - + config.controller().setWriteEventsInterval(10); + config.controller().setWritePlansInterval(10); + + config.controller().setOutputDirectory(controlerOutputDir); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); + config.qsim().setStartTime(1.5*3600); config.qsim().setEndTime(5.5*3600); config.qsim().setUsingFastCapacityUpdate(false); - - config.controler().setLastIteration(10); - + + config.controller().setLastIteration(10); + // --- - + Scenario scenario = ScenarioUtils.loadScenario(config) ; scenario.addScenarioElement(SignalsData.ELEMENT_NAME, new SignalsDataLoader(config).loadSignalsData()); - + // --- - + Controler c = new Controler(scenario); Signals.configure(c); - + c.run(); - + String inputDirectory = testUtils.getInputDirectory(); { - //iteration 0 + //iteration 0 String iterationOutput = controlerOutputDir + "ITERS/it.0/"; - + Assert.assertEquals("different events files after iteration 0 ", EventsFileComparator.Result.FILES_ARE_EQUAL, new EventsFileComparator().setIgnoringCoordinates( true ).runComparison( inputDirectory + "0.events.xml.gz", iterationOutput + "0.events.xml.gz") ); - + Scenario expectedPopulation = ScenarioUtils.createScenario(c.getConfig()); new MatsimNetworkReader(expectedPopulation.getNetwork()).parse(c.getConfig().network().getInputFileURL(c.getConfig().getContext())); new PopulationReader(expectedPopulation).readFile(inputDirectory + "0.plans.xml.gz"); - + Scenario actualPopulation = ScenarioUtils.createScenario(c.getConfig()); new PopulationReader(actualPopulation).readFile(iterationOutput + "0.plans.xml.gz"); - + boolean works = PopulationUtils.equalPopulation(expectedPopulation.getPopulation(), actualPopulation.getPopulation()); - + if (!works){ new org.matsim.api.core.v01.population.PopulationWriter(expectedPopulation.getPopulation()).write(testUtils.getOutputDirectory()+"/expected_plans_it0.xml.gz"); new org.matsim.api.core.v01.population.PopulationWriter(actualPopulation.getPopulation()).write(testUtils.getOutputDirectory()+"/actual_plans_it0.xml.gz"); @@ -110,9 +110,9 @@ public void testSignalSystems() { Assert.assertTrue("different population files after iteration 0 ", works); } { - //iteration 10 + //iteration 10 String iterationOutput = controlerOutputDir + "ITERS/it.10/"; - + Assert.assertEquals("different event files after iteration 10", EventsFileComparator.Result.FILES_ARE_EQUAL, new EventsFileComparator().setIgnoringCoordinates( true ).runComparison( inputDirectory + "10.events.xml.gz", iterationOutput + "10.events.xml.gz" ) @@ -121,12 +121,12 @@ public void testSignalSystems() { Scenario expectedPopulation = ScenarioUtils.createScenario(c.getConfig()); new MatsimNetworkReader(expectedPopulation.getNetwork()).parse(c.getConfig().network().getInputFileURL(c.getConfig().getContext())); new PopulationReader(expectedPopulation).readFile(inputDirectory + "10.plans.xml.gz"); - + Scenario actualPopulation = ScenarioUtils.createScenario(c.getConfig()); new PopulationReader(actualPopulation).readFile(iterationOutput + "10.plans.xml.gz"); - + boolean works = PopulationUtils.equalPopulation(expectedPopulation.getPopulation(), actualPopulation.getPopulation()); - + if (!works){ new org.matsim.api.core.v01.population.PopulationWriter(expectedPopulation.getPopulation()).write(testUtils.getOutputDirectory()+"/expected_plans_it10.xml.gz"); new org.matsim.api.core.v01.population.PopulationWriter(actualPopulation.getPopulation()).write(testUtils.getOutputDirectory()+"/actual_plans_it10.xml.gz"); @@ -144,58 +144,58 @@ public void testSignalSystems() { Assert.assertTrue(file.exists()); file = new File(writer.getIntergreenTimesOutputFilename()); Assert.assertTrue(file.exists()); - + } - + @Test - public void testSignalSystemsWTryEndTimeThenDuration() { + public void testSignalSystemsWTryEndTimeThenDuration() { Config config = testUtils.loadConfig(testUtils.getClassInputDirectory() + CONFIG_FILE_NAME); // tryEndTimeThenDuration currently is the default config.plans().setActivityDurationInterpretation(PlansConfigGroup.ActivityDurationInterpretation.tryEndTimeThenDuration); String controlerOutputDir = testUtils.getOutputDirectory() + "controlerOutput/"; - + config.network().setLaneDefinitionsFile("testLaneDefinitions_v2.0.xml"); - config.controler().setWriteEventsInterval(10); - config.controler().setWritePlansInterval(10); - - config.controler().setOutputDirectory(controlerOutputDir); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); - + config.controller().setWriteEventsInterval(10); + config.controller().setWritePlansInterval(10); + + config.controller().setOutputDirectory(controlerOutputDir); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); + config.qsim().setStartTime(1.5*3600); config.qsim().setEndTime(5*3600); config.qsim().setUsingFastCapacityUpdate(false); - - config.controler().setLastIteration(10); - + + config.controller().setLastIteration(10); + Scenario scenario = ScenarioUtils.loadScenario(config); scenario.addScenarioElement(SignalsData.ELEMENT_NAME, new SignalsDataLoader(config).loadSignalsData()); - + Controler c = new Controler(scenario); Signals.configure( c ); c.run(); - - + + String inputDirectory = testUtils.getInputDirectory(); { - //iteration 0 + //iteration 0 String iterationOutput = controlerOutputDir + "ITERS/it.0/"; - + Assert.assertEquals("different events files after iteration 0 ", EventsFileComparator.Result.FILES_ARE_EQUAL, new EventsFileComparator().setIgnoringCoordinates( true ).runComparison( inputDirectory + "0.events.xml.gz", iterationOutput + "0.events.xml.gz") ); - + Scenario expectedPopulation = ScenarioUtils.createScenario(c.getConfig()); new MatsimNetworkReader(expectedPopulation.getNetwork()).parse(c.getConfig().network().getInputFileURL(c.getConfig().getContext())); new PopulationReader(expectedPopulation).readFile(testUtils.getInputDirectory() + "0.plans.xml.gz"); - + Scenario actualPopulation = ScenarioUtils.createScenario(c.getConfig()); new PopulationReader(actualPopulation).readFile(iterationOutput + "0.plans.xml.gz"); - + boolean works = PopulationUtils.equalPopulation(expectedPopulation.getPopulation(), actualPopulation.getPopulation()); - + if (!works){ new org.matsim.api.core.v01.population.PopulationWriter(expectedPopulation.getPopulation()).write(testUtils.getOutputDirectory()+"/expected_plans_it0.xml.gz"); new org.matsim.api.core.v01.population.PopulationWriter(actualPopulation.getPopulation()).write(testUtils.getOutputDirectory()+"/actual_plans_it0.xml.gz"); @@ -203,24 +203,24 @@ public void testSignalSystemsWTryEndTimeThenDuration() { Assert.assertTrue("different population files after iteration 0 ", works); } { - //iteration 10 + //iteration 10 String iterationOutput = controlerOutputDir + "ITERS/it.10/"; - + Assert.assertEquals("different event files after iteration 10", EventsFileComparator.Result.FILES_ARE_EQUAL, new EventsFileComparator().setIgnoringCoordinates( true ).runComparison( inputDirectory + "10.events.xml.gz", iterationOutput + "10.events.xml.gz") ); - - + + Scenario expectedPopulation = ScenarioUtils.createScenario(c.getConfig()); new MatsimNetworkReader(expectedPopulation.getNetwork()).parse(c.getConfig().network().getInputFileURL(c.getConfig().getContext())); new PopulationReader(expectedPopulation).readFile(inputDirectory + "10.plans.xml.gz"); - + Scenario actualPopulation = ScenarioUtils.createScenario(c.getConfig()); new PopulationReader(actualPopulation).readFile(iterationOutput + "10.plans.xml.gz"); - + boolean works = PopulationUtils.equalPopulation(expectedPopulation.getPopulation(), actualPopulation.getPopulation()); - + if (!works){ new org.matsim.api.core.v01.population.PopulationWriter(expectedPopulation.getPopulation()).write(testUtils.getOutputDirectory()+"/expected_plans_it10.xml.gz"); new org.matsim.api.core.v01.population.PopulationWriter(actualPopulation.getPopulation()).write(testUtils.getOutputDirectory()+"/actual_plans_it10.xml.gz"); @@ -238,8 +238,8 @@ public void testSignalSystemsWTryEndTimeThenDuration() { Assert.assertTrue(file.exists()); file = new File(writer.getIntergreenTimesOutputFilename()); Assert.assertTrue(file.exists()); - + } - - + + } diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/integration/invertednetworks/InvertedNetworksSignalsIT.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/integration/invertednetworks/InvertedNetworksSignalsIT.java index 1f2806e32fe..3515b7fba6e 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/integration/invertednetworks/InvertedNetworksSignalsIT.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/integration/invertednetworks/InvertedNetworksSignalsIT.java @@ -45,16 +45,16 @@ public class InvertedNetworksSignalsIT { @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); - + @Test public final void testSignalsInvertedNetworkRouting() { InvertedNetworkRoutingSignalsFixture f = new InvertedNetworkRoutingSignalsFixture(false, false, true); - f.scenario.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory()); + f.scenario.getConfig().controller().setOutputDirectory(testUtils.getOutputDirectory()); Controler c = new Controler(f.scenario); // c.addOverridingModule(new SignalsModule()); Signals.configure(c); - c.getConfig().controler().setDumpDataAtEnd(false); - c.getConfig().controler().setCreateGraphs(false); + c.getConfig().controller().setDumpDataAtEnd(false); + c.getConfig().controller().setCreateGraphs(false); final InvertedNetworkRoutingTestEventHandler testHandler = new InvertedNetworkRoutingTestEventHandler(); c.addControlerListener(new StartupListener(){ @Override @@ -65,12 +65,12 @@ public void notifyStartup(StartupEvent event) { c.run(); Assert.assertTrue("No traffic on link", testHandler.hadTrafficOnLink25); } - + @Test public final void testSignalsInvertedNetworkRoutingIterations() { InvertedNetworkRoutingSignalsFixture f = new InvertedNetworkRoutingSignalsFixture(false, false, true); - f.scenario.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory()); - f.scenario.getConfig().controler().setLastIteration(1); + f.scenario.getConfig().controller().setOutputDirectory(testUtils.getOutputDirectory()); + f.scenario.getConfig().controller().setLastIteration(1); SignalsData signalsData = (SignalsData) f.scenario.getScenarioElement(SignalsData.ELEMENT_NAME); SignalPlanData signalPlan = signalsData.getSignalControlData().getSignalSystemControllerDataBySystemId().get(Id.create(2, SignalSystem.class)).getSignalPlanData().get(Id.create(1, SignalPlan.class)); signalPlan.setCycleTime(500); @@ -81,8 +81,8 @@ public final void testSignalsInvertedNetworkRoutingIterations() { Controler c = new Controler(f.scenario); // c.addOverridingModule(new SignalsModule()); Signals.configure( c ); - c.getConfig().controler().setDumpDataAtEnd(false); - c.getConfig().controler().setCreateGraphs(false); + c.getConfig().controller().setDumpDataAtEnd(false); + c.getConfig().controller().setCreateGraphs(false); final InvertedNetworkRoutingTestEventHandler testHandler = new InvertedNetworkRoutingTestEventHandler(); c.addControlerListener(new StartupListener(){ @Override @@ -93,7 +93,7 @@ public void notifyStartup(StartupEvent event) { c.run(); Assert.assertTrue("No traffic on link", testHandler.hadTrafficOnLink25); } - + diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/network/SignalsAndLanesOsmNetworkReaderTest.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/network/SignalsAndLanesOsmNetworkReaderTest.java index be54f468859..7a8db642e1c 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/network/SignalsAndLanesOsmNetworkReaderTest.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/network/SignalsAndLanesOsmNetworkReaderTest.java @@ -426,8 +426,8 @@ public void berlinSnippet(){ //Try-Mini Example to ensure basic usability scenario.getConfig().plans().setInputFile(inputfile+"plans_berlinSnippet.xml"); Controler controler = new Controler( scenario ); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(1); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(1); controler.run(); int noSignalGroups = 0; diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/oneagent/ControlerTest.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/oneagent/ControlerTest.java index 65aaff468ce..6b981e6ba59 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/oneagent/ControlerTest.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/oneagent/ControlerTest.java @@ -32,7 +32,6 @@ import org.matsim.contrib.signals.events.SignalGroupStateChangedEventHandler; import org.matsim.core.controler.Controler; import org.matsim.core.controler.events.AfterMobsimEvent; -import org.matsim.core.controler.events.IterationStartsEvent; import org.matsim.core.controler.listener.AfterMobsimListener; import org.matsim.core.controler.listener.IterationStartsListener; import org.matsim.core.mobsim.qsim.interfaces.SignalGroupState; @@ -50,10 +49,10 @@ * */ public class ControlerTest { - + @Rule public MatsimTestUtils testUtils = new MatsimTestUtils(); - + /** * Tests the setup with a traffic light that shows all the time green in the 0th iteration. * After the mobsim is run the signal settings are changed thus in the 1st iteration @@ -64,13 +63,13 @@ public void testModifySignalControlDataOnsetOffset() { //configure and load standard scenario Fixture fixture = new Fixture(); Scenario scenario = fixture.createAndLoadTestScenarioOneSignal(false); - scenario.getConfig().controler().setFirstIteration(0); - scenario.getConfig().controler().setLastIteration(1); - scenario.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory()); - scenario.getConfig().controler().setWriteEventsInterval(1); - + scenario.getConfig().controller().setFirstIteration(0); + scenario.getConfig().controller().setLastIteration(1); + scenario.getConfig().controller().setOutputDirectory(testUtils.getOutputDirectory()); + scenario.getConfig().controller().setWriteEventsInterval(1); + Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setCreateGraphs(false); controler.addControlerListener(new AfterMobsimListener() { @Override @@ -82,7 +81,7 @@ public void notifyAfterMobsim(AfterMobsimEvent event) { ((SignalsData) scenario .getScenarioElement(SignalsData.ELEMENT_NAME)).getSignalControlData() .getSignalSystemControllerDataBySystemId().values()) { - + for (SignalPlanData plan : intersectionSignal.getSignalPlanData().values()) { plan.setCycleTime(2000); for (SignalGroupSettingsData data : plan.getSignalGroupSettingsDataByGroupId().values()) { @@ -93,7 +92,7 @@ public void notifyAfterMobsim(AfterMobsimEvent event) { } } }); - + controler.addControlerListener((IterationStartsListener)event -> { event.getServices().getEvents().addHandler(new EventsLogger()); @@ -108,11 +107,11 @@ public void notifyAfterMobsim(AfterMobsimEvent event) { event.getServices().getEvents().addHandler(signalsHandler0); } }); - + controler.run(); } - - + + private static final class TestSignalGroupStateChangedHandler implements SignalGroupStateChangedEventHandler { @@ -143,5 +142,5 @@ public void handleEvent(LinkEnterEvent e){ } } } - + } diff --git a/contribs/signals/src/test/java/org/matsim/contrib/signals/oneagent/Fixture.java b/contribs/signals/src/test/java/org/matsim/contrib/signals/oneagent/Fixture.java index d01b6d7881b..2aeba8355a5 100644 --- a/contribs/signals/src/test/java/org/matsim/contrib/signals/oneagent/Fixture.java +++ b/contribs/signals/src/test/java/org/matsim/contrib/signals/oneagent/Fixture.java @@ -45,8 +45,8 @@ import org.matsim.contrib.signals.model.SignalSystem; 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.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.lanes.Lane; @@ -65,18 +65,18 @@ public class Fixture { final Id signalPlanId2 = Id.create(2, SignalPlan.class); final Id signalSystemId2 = Id.create(2, SignalSystem.class); final Id signalGroupId100 = Id.create(100, SignalGroup.class); - + // only available if 'TwoSignals'-Method is used final Id signalGroupId200 = Id.create(200, SignalGroup.class); final Id linkId6 = Id.create(6, Link.class); final Id nodeId6 = Id.create(6, Node.class); - + public Scenario createAndLoadTestScenarioOneSignal(Boolean useIntergreens){ Config conf = createConfigOneSignal(useIntergreens); Scenario scenario = ScenarioUtils.loadScenario(conf); scenario.addScenarioElement(SignalsData.ELEMENT_NAME, new SignalsDataLoader(conf).loadSignalsData()); - + return scenario; } @@ -89,15 +89,15 @@ private Config createConfigOneSignal(Boolean useIntergreens) { e.printStackTrace(); } Config conf = ConfigUtils.createConfig(testUtils.classInputResourcePath()); - conf.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + conf.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); ActivityParams params = new ActivityParams("h"); params.setTypicalDuration(24.0 * 3600.0); - conf.planCalcScore().addActivityParams(params); + conf.scoring().addActivityParams(params); StrategySettings settings = new StrategySettings(Id.create("1", StrategySettings.class)); settings.setStrategyName("ChangeExpBeta"); settings.setWeight(1.0); - conf.strategy().addStrategySettings(settings); + conf.replanning().addStrategySettings(settings); conf.network().setInputFile("network.xml.gz"); conf.network().setLaneDefinitionsFile("testLaneDefinitions_v2.0.xml"); conf.plans().setInputFile("plans1Agent.xml"); @@ -107,17 +107,17 @@ private Config createConfigOneSignal(Boolean useIntergreens) { conf.qsim().setUsingFastCapacityUpdate(false); SignalSystemsConfigGroup signalsConfig = ConfigUtils.addOrGetModule(conf, SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class); signalsConfig.setUseSignalSystems(true); - + if (useIntergreens) { signalsConfig.setIntergreenTimesFile("testIntergreenTimes_v1.0.xml"); signalsConfig.setUseIntergreenTimes(true); signalsConfig.setActionOnIntergreenViolation(SignalSystemsConfigGroup.ActionOnSignalSpecsViolation.EXCEPTION); - } + } this.setSignalSystemConfigValues(signalsConfig, testUtils); return conf; } - + private void setSignalSystemConfigValues(SignalSystemsConfigGroup signalsConfig, MatsimTestUtils testUtils){ signalsConfig.setSignalSystemFile("testSignalSystems_v2.0.xml"); signalsConfig.setSignalGroupsFile("testSignalGroups_v2.0.xml"); @@ -130,10 +130,10 @@ public Scenario createAndLoadTestScenarioTwoSignals(boolean useConflictData) { SignalSystemsConfigGroup signalsConfig = ConfigUtils.addOrGetModule(config, SignalSystemsConfigGroup.GROUP_NAME, SignalSystemsConfigGroup.class); signalsConfig.setIntersectionLogic(IntersectionLogic.CONFLICTING_DIRECTIONS_NO_TURN_RESTRICTIONS); signalsConfig.setActionOnConflictingDirectionViolation(ActionOnSignalSpecsViolation.EXCEPTION); - + Scenario scenario = ScenarioUtils.loadScenario(config); scenario.addScenarioElement(SignalsData.ELEMENT_NAME, new SignalsDataLoader(config).loadSignalsData()); - + // modify scenario Network net = scenario.getNetwork(); net.addNode(net.getFactory().createNode(nodeId6, new Coord(0, 100))); @@ -168,9 +168,9 @@ public Scenario createAndLoadTestScenarioTwoSignals(boolean useConflictData) { conflictsNode2.addDirection(direction1); conflictsNode2.addDirection(direction2); signalsData.getConflictingDirectionsData().addConflictingDirectionsForIntersection(signalSystemId2, nodeId2, conflictsNode2); - + return scenario; } - + } diff --git a/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystems/10.events.xml.gz b/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystems/10.events.xml.gz index c7ef25fe7c6..3493cb13c84 100644 Binary files a/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystems/10.events.xml.gz and b/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystems/10.events.xml.gz differ diff --git a/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystems/10.plans.xml.gz b/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystems/10.plans.xml.gz index 9b71cf15cb5..2b90066faf5 100644 Binary files a/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystems/10.plans.xml.gz and b/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystems/10.plans.xml.gz differ diff --git a/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystemsWTryEndTimeThenDuration/10.events.xml.gz b/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystemsWTryEndTimeThenDuration/10.events.xml.gz index e2ea8e8111c..3493cb13c84 100644 Binary files a/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystemsWTryEndTimeThenDuration/10.events.xml.gz and b/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystemsWTryEndTimeThenDuration/10.events.xml.gz differ diff --git a/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystemsWTryEndTimeThenDuration/10.plans.xml.gz b/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystemsWTryEndTimeThenDuration/10.plans.xml.gz index d66ff6e80af..d8733aca4db 100644 Binary files a/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystemsWTryEndTimeThenDuration/10.plans.xml.gz and b/contribs/signals/src/test/resources/test/input/org/matsim/contrib/signals/integration/SignalSystemsIT/testSignalSystemsWTryEndTimeThenDuration/10.plans.xml.gz differ diff --git a/contribs/simulatedannealing/src/main/java/org/matsim/contrib/simulatedannealing/SimulatedAnnealingAnalysis.java b/contribs/simulatedannealing/src/main/java/org/matsim/contrib/simulatedannealing/SimulatedAnnealingAnalysis.java index 519351d1390..c6e2c23ea99 100644 --- a/contribs/simulatedannealing/src/main/java/org/matsim/contrib/simulatedannealing/SimulatedAnnealingAnalysis.java +++ b/contribs/simulatedannealing/src/main/java/org/matsim/contrib/simulatedannealing/SimulatedAnnealingAnalysis.java @@ -39,7 +39,7 @@ public final class SimulatedAnnealingAnalysis implements IterationStartsListe public SimulatedAnnealingAnalysis(Config config, MatsimServices matsimServices, SimulatedAnnealing simulatedAnnealing) { this.matsimServices = matsimServices; - this.runId = Optional.ofNullable(config.controler().getRunId()).orElse(notAvailableString); + this.runId = Optional.ofNullable(config.controller().getRunId()).orElse(notAvailableString); this.simulatedAnnealing = simulatedAnnealing; this.delimiter = config.global().getDefaultDelimiter(); diff --git a/contribs/simulatedannealing/src/test/java/org/matsim/contrib/simulatedannealing/SimulatedAnnealingIT.java b/contribs/simulatedannealing/src/test/java/org/matsim/contrib/simulatedannealing/SimulatedAnnealingIT.java index 361e99b08cc..a8622e6ba36 100644 --- a/contribs/simulatedannealing/src/test/java/org/matsim/contrib/simulatedannealing/SimulatedAnnealingIT.java +++ b/contribs/simulatedannealing/src/test/java/org/matsim/contrib/simulatedannealing/SimulatedAnnealingIT.java @@ -41,12 +41,12 @@ public void testIntegratedAnnealingInQSim() { final Controler controler = new Controler(config); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setWriteEventsInterval(0); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(0); SimulatedAnnealingConfigGroup simAnCfg = new SimulatedAnnealingConfigGroup(); - config.controler().setLastIteration(10); + config.controller().setLastIteration(10); controler.addOverridingModule(new AbstractModule() { @Override diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperListener.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperListener.java index d672a774df6..2b056c444c3 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperListener.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperListener.java @@ -109,7 +109,7 @@ private List loadProvider(ImmutableSet c List result = new ArrayList<>(); for (ClassPath.ClassInfo info : classes) { Class clazz = info.load(); - if (clazz.isAssignableFrom(DashboardProvider.class)) { + if (DashboardProvider.class.isAssignableFrom(clazz)) { try { Constructor c = clazz.getDeclaredConstructor(); DashboardProvider o = (DashboardProvider) c.newInstance(); diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperRunner.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperRunner.java index a13b02dc168..d276e4528f7 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperRunner.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperRunner.java @@ -30,6 +30,10 @@ public class SimWrapperRunner implements MATSimAppCommand { @CommandLine.Option(names = "--exclude", split = ",", description = "Exclusion that will be added to the config.") private Set exclude; + public static void main(String[] args) { + new SimWrapperRunner().execute(args); + } + @Override public Integer call() throws Exception { for (Path input : inputPaths) { diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/OverviewDashboard.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/OverviewDashboard.java index b24ae180cc9..68b02d22fde 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/OverviewDashboard.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/OverviewDashboard.java @@ -65,8 +65,8 @@ public void configure(Header header, Layout layout) { }).el(PieChart.class, (viz, data) -> { viz.title = "Mode Share"; viz.description = "at final Iteration"; - viz.dataset = data.output("*.modestats.txt"); - viz.ignoreColumns = List.of("Iteration"); + viz.dataset = data.output("*.modestats.csv"); + viz.ignoreColumns = List.of("iteration"); viz.useLastRow = true; }); @@ -74,10 +74,10 @@ public void configure(Header header, Layout layout) { layout.row("second").el(Line.class, (viz, data) -> { viz.title = "Score"; - viz.dataset = data.output("*.scorestats.txt"); + viz.dataset = data.output("*.scorestats.csv"); viz.description = "per Iteration"; viz.x = "ITERATION"; - viz.columns = List.of("avg. EXECUTED", "avg. WORST", "avg. BEST"); + viz.columns = List.of("avg_executed", "avg_worst", "avg_best"); viz.xAxisName = "Iteration"; viz.yAxisName = "Score"; @@ -87,7 +87,7 @@ public void configure(Header header, Layout layout) { .el(Area.class, (viz, data) -> { viz.title = "Mode Share Progression"; viz.description = "per Iteration"; - viz.dataset = data.output("*.modestats.txt"); + viz.dataset = data.output("*.modestats.csv"); viz.x = "Iteration"; viz.xAxisName = "Iteration"; viz.yAxisName = "Share"; diff --git a/contribs/simwrapper/src/test/java/org/matsim/simwrapper/SimWrapperModuleTest.java b/contribs/simwrapper/src/test/java/org/matsim/simwrapper/SimWrapperModuleTest.java index ec6e7ca7075..0e781bb830d 100644 --- a/contribs/simwrapper/src/test/java/org/matsim/simwrapper/SimWrapperModuleTest.java +++ b/contribs/simwrapper/src/test/java/org/matsim/simwrapper/SimWrapperModuleTest.java @@ -2,14 +2,11 @@ import org.junit.Rule; import org.junit.Test; -import org.matsim.application.analysis.traffic.LinkStats; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.Controler; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; -import org.matsim.simwrapper.viz.PieChart; -import org.matsim.simwrapper.viz.TextBlock; import org.matsim.testcases.MatsimTestUtils; import java.net.URL; @@ -26,8 +23,8 @@ public void runScenario() { Config config = ConfigUtils.loadConfig(equil); - config.controler().setLastIteration(5); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(5); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Controler controler = new Controler(config); controler.addOverridingModule(new SimWrapperModule()); diff --git a/contribs/simwrapper/src/test/java/org/matsim/simwrapper/TestScenario.java b/contribs/simwrapper/src/test/java/org/matsim/simwrapper/TestScenario.java index 039e7acad58..a58095cc3e1 100644 --- a/contribs/simwrapper/src/test/java/org/matsim/simwrapper/TestScenario.java +++ b/contribs/simwrapper/src/test/java/org/matsim/simwrapper/TestScenario.java @@ -4,7 +4,6 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.application.MATSimApplication; -import org.matsim.contrib.emissions.HbefaVehicleCategory; import org.matsim.contrib.vsp.scenario.SnzActivities; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; @@ -13,9 +12,6 @@ import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; -import org.matsim.vehicles.EngineInformation; -import org.matsim.vehicles.VehicleType; -import org.matsim.vehicles.VehicleUtils; import java.net.URL; import java.util.HashSet; @@ -36,10 +32,10 @@ public static Config loadConfig(MatsimTestUtils utils) { URL context = ExamplesUtils.getTestScenarioURL("kelheim"); Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(context, "config.xml")); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); - config.controler().setWriteEventsInterval(1); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); + config.controller().setWriteEventsInterval(1); return config; } diff --git a/contribs/simwrapper/src/test/java/org/matsim/simwrapper/dashboard/DashboardTests.java b/contribs/simwrapper/src/test/java/org/matsim/simwrapper/dashboard/DashboardTests.java index d3bd0e20124..394797cdea9 100644 --- a/contribs/simwrapper/src/test/java/org/matsim/simwrapper/dashboard/DashboardTests.java +++ b/contribs/simwrapper/src/test/java/org/matsim/simwrapper/dashboard/DashboardTests.java @@ -4,7 +4,6 @@ import org.junit.Rule; import org.junit.Test; import org.matsim.application.MATSimApplication; -import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.Controler; @@ -23,7 +22,7 @@ public class DashboardTests { private void run(Dashboard... dashboards) { Config config = TestScenario.loadConfig(utils); - config.controler().setLastIteration(2); + config.controller().setLastIteration(2); SimWrapperConfigGroup group = ConfigUtils.addOrGetModule(config, SimWrapperConfigGroup.class); group.defaultParams().sampleSize = 0.001; diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/controller/listeners/JointPlansDumping.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/controller/listeners/JointPlansDumping.java index d0268d9daad..1f624bbc98d 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/controller/listeners/JointPlansDumping.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/controller/listeners/JointPlansDumping.java @@ -52,8 +52,8 @@ public JointPlansDumping( final OutputDirectoryHierarchy controlerIO ) { this.sc = sc ; this.jointPlans = (JointPlans) sc.getScenarioElement( JointPlans.ELEMENT_NAME ); - this.firstIteration = sc.getConfig().controler().getFirstIteration(); - this.writePlansInterval = sc.getConfig().controler().getWritePlansInterval() ; + this.firstIteration = sc.getConfig().controller().getFirstIteration(); + this.writePlansInterval = sc.getConfig().controller().getWritePlansInterval() ; this.controlerIO = controlerIO ; } diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/population/PlanWithCachedJointPlan.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/population/PlanWithCachedJointPlan.java index c1def957531..5d5990a7237 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/population/PlanWithCachedJointPlan.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/population/PlanWithCachedJointPlan.java @@ -23,6 +23,7 @@ import java.util.List; import java.util.Map; +import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; @@ -172,6 +173,24 @@ public String getType() { public void setType(String type) { this.delegate.setType(type); } + + @Override + public Id getId() { return null; } + + @Override + public void setPlanId(Id planId) { /* nothing to do here */ } + + @Override + public int getIterationCreated() { return -1; } + + @Override + public void setIterationCreated(int iteration) { /* nothing to do here */ } + + @Override + public String getPlanMutator() { return null; } + + @Override + public void setPlanMutator(String planMutator) { /* nothing to do here */ } @Override public Person getPerson() { diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/CoalitionExpBetaFactory.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/CoalitionExpBetaFactory.java index 3d4d089511e..174687017ea 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/CoalitionExpBetaFactory.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/CoalitionExpBetaFactory.java @@ -49,7 +49,7 @@ public GroupLevelPlanSelector createSelector() { return new CoalitionSelector( new LogitWeight( MatsimRandom.getLocalInstance(), - sc.getConfig().planCalcScore().getBrainExpBeta()), + sc.getConfig().scoring().getBrainExpBeta()), conflictSolver); } } diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/GroupSelectExpBetaFactory.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/GroupSelectExpBetaFactory.java index 96a9ef30475..047404f6e16 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/GroupSelectExpBetaFactory.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/GroupSelectExpBetaFactory.java @@ -48,7 +48,7 @@ public GroupLevelPlanSelector createSelector() { return new LogitSumSelector( MatsimRandom.getLocalInstance(), incompatiblePlansIdentifierFactory, - sc.getConfig().planCalcScore().getBrainExpBeta()); + sc.getConfig().scoring().getBrainExpBeta()); } } diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/GroupWhoIsTheBossSelectExpBetaFactory.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/GroupWhoIsTheBossSelectExpBetaFactory.java index 91648c35c9f..120cd6e7658 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/GroupWhoIsTheBossSelectExpBetaFactory.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/framework/replanning/strategies/GroupWhoIsTheBossSelectExpBetaFactory.java @@ -53,7 +53,7 @@ public GroupLevelPlanSelector createSelector() { incompatiblePlansIdentifierFactory , new LogitWeight( MatsimRandom.getLocalInstance(), - sc.getConfig().planCalcScore().getBrainExpBeta()) ); + sc.getConfig().scoring().getBrainExpBeta()) ); } } diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/jointactivities/scoring/FireMoneyEventsForUtilityOfBeingTogether.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/jointactivities/scoring/FireMoneyEventsForUtilityOfBeingTogether.java index 50dfd2d5988..019ca148c9b 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/jointactivities/scoring/FireMoneyEventsForUtilityOfBeingTogether.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/jointactivities/scoring/FireMoneyEventsForUtilityOfBeingTogether.java @@ -47,7 +47,7 @@ import org.matsim.contrib.socnetsim.run.ScoringFunctionConfigGroup; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.api.core.v01.events.HasPersonId; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.events.AfterMobsimEvent; import org.matsim.core.controler.listener.AfterMobsimListener; import org.matsim.core.utils.collections.MapUtils; @@ -94,7 +94,7 @@ public FireMoneyEventsForUtilityOfBeingTogether( module.getActTypeFilterForJointScoring(), module.getModeFilterForJointScoring(), getPersonOverlapScorerFactory( sc ), - sc.getConfig().planCalcScore().getMarginalUtilityOfMoney(), + sc.getConfig().scoring().getMarginalUtilityOfMoney(), sc.getActivityFacilities(), (SocialNetwork) sc.getScenarioElement( SocialNetwork.ELEMENT_NAME ) ); @@ -123,7 +123,7 @@ public BeingTogetherScoring.PersonOverlapScorer createScorer(final Id id) { return new BeingTogetherScoring.LinearOverlapScorer( 0 ); } final double typicalDuration = - getTypicalDuration( + getTypicalDuration( scenario, person, scoringFunctionConf.getActivityTypeForContactInDesires() ); @@ -151,14 +151,14 @@ public static double getTypicalDuration( if ( typicalDuration != null ) return typicalDuration; - final ActivityParams params = scenario.getConfig().planCalcScore().getActivityParams( type ); - + final ActivityParams params = scenario.getConfig().scoring().getActivityParams( type ); + if ( params == null ) { //throw new RuntimeException( "could not find typical duration for Person "+person.getId()+" for type "+type ); // not that nice, but needed for agents that might not have a preference. BeingTogetherScoring knows how to handle that return Double.NEGATIVE_INFINITY; } - + return params.getTypicalDuration().seconds(); } diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/jointtrips/scoring/CharyparNagelWithJointModesScoringFunctionFactory.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/jointtrips/scoring/CharyparNagelWithJointModesScoringFunctionFactory.java index 4fe7423b7f3..2f436e9d857 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/jointtrips/scoring/CharyparNagelWithJointModesScoringFunctionFactory.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/jointtrips/scoring/CharyparNagelWithJointModesScoringFunctionFactory.java @@ -66,7 +66,7 @@ public CharyparNagelWithJointModesScoringFunctionFactory( final Set typesNotToScore, final Scenario scenario) { log.warn( "initializing the \"CharyparNagel\" scoring function: this has no special parameters for joint modes!" ); - this.params = new ScoringParameters.Builder(scenario.getConfig().planCalcScore(), scenario.getConfig().planCalcScore().getScoringParameters(null), scenario.getConfig().scenario()).build(); + this.params = new ScoringParameters.Builder(scenario.getConfig().scoring(), scenario.getConfig().scoring().getScoringParameters(null), scenario.getConfig().scenario()).build(); this.scenario = scenario; this.blackList = typesNotToScore; diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/run/ReplanningAllocationDumper.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/run/ReplanningAllocationDumper.java index 3b5fe3725c4..0c41c7bf2be 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/run/ReplanningAllocationDumper.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/run/ReplanningAllocationDumper.java @@ -21,6 +21,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import org.matsim.api.core.v01.population.Person; import org.matsim.core.controler.events.BeforeMobsimEvent; @@ -30,7 +31,6 @@ import org.matsim.core.controler.listener.ShutdownListener; import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.contrib.socnetsim.framework.replanning.GroupPlanStrategy; import org.matsim.contrib.socnetsim.framework.replanning.GroupStrategyManager; @@ -54,7 +54,7 @@ public void notifyStartup(final StartupEvent event) { this.writer = IOUtils.getBufferedWriter( outPath ); try { this.writer.write( "iter\tagentId\tgroup\tstrategy" ); - } + } catch (IOException e) { throw new UncheckedIOException( e ); } @@ -76,7 +76,7 @@ public void notifyAlloc( this.writer.write( strategy.toString() ); } group++; - } + } catch (IOException e) { throw new UncheckedIOException( e ); } @@ -86,7 +86,7 @@ public void notifyAlloc( public void notifyShutdown(ShutdownEvent event) { try { this.writer.close(); - } + } catch (IOException e) { throw new UncheckedIOException( e ); } @@ -96,7 +96,7 @@ public void notifyShutdown(ShutdownEvent event) { public void notifyBeforeMobsim(BeforeMobsimEvent event) { try { this.writer.flush(); - } + } catch (IOException e) { throw new UncheckedIOException( e ); } diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/run/ReplanningStatsDumper.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/run/ReplanningStatsDumper.java index 3c8bf0793b1..c24b3dcf15d 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/run/ReplanningStatsDumper.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/run/ReplanningStatsDumper.java @@ -21,6 +21,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import org.matsim.core.controler.events.BeforeMobsimEvent; import org.matsim.core.controler.events.ShutdownEvent; @@ -29,7 +30,6 @@ import org.matsim.core.controler.listener.ShutdownListener; import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.contrib.socnetsim.framework.replanning.GroupPlanStrategy; import org.matsim.contrib.socnetsim.framework.replanning.GroupStrategyManager; @@ -52,7 +52,7 @@ public void notifyStartup(final StartupEvent event) { this.writer = IOUtils.getBufferedWriter( outPath ); try { this.writer.write( "iter\tgroupSize\tstrategy" ); - } + } catch (IOException e) { throw new UncheckedIOException( e ); } @@ -71,7 +71,7 @@ public void notifyAlloc( this.writer.write( ""+g.getPersons().size() ); this.writer.write( "\t" ); this.writer.write( strategy.toString() ); - } + } catch (IOException e) { throw new UncheckedIOException( e ); } @@ -81,7 +81,7 @@ public void notifyAlloc( public void notifyShutdown(ShutdownEvent event) { try { this.writer.close(); - } + } catch (IOException e) { throw new UncheckedIOException( e ); } @@ -91,7 +91,7 @@ public void notifyShutdown(ShutdownEvent event) { public void notifyBeforeMobsim(BeforeMobsimEvent event) { try { this.writer.flush(); - } + } catch (IOException e) { throw new UncheckedIOException( e ); } diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/CourtesyHistogramListener.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/CourtesyHistogramListener.java index 02c1f50e5e9..c659828ea59 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/CourtesyHistogramListener.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/CourtesyHistogramListener.java @@ -36,12 +36,12 @@ import org.matsim.core.controler.events.IterationStartsEvent; import org.matsim.core.controler.listener.IterationEndsListener; import org.matsim.core.controler.listener.IterationStartsListener; -import org.matsim.core.utils.io.UncheckedIOException; import jakarta.inject.Singleton; import java.awt.*; import java.io.File; import java.io.IOException; +import java.io.UncheckedIOException; /** * @author thibautd @@ -59,7 +59,7 @@ public class CourtesyHistogramListener implements IterationEndsListener, Iterat CourtesyHistogramListener(Config config, CourtesyHistogram histogram, OutputDirectoryHierarchy controlerIO) { this.controlerIO = controlerIO; this.histogram = histogram; - this.outputGraph = config.controler().isCreateGraphs(); + this.outputGraph = config.controller().isCreateGraphs(); } @Override diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/CountNSelectedJointTripsPerAgent.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/CountNSelectedJointTripsPerAgent.java index a14e37a7865..b86e9e905fb 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/CountNSelectedJointTripsPerAgent.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/CountNSelectedJointTripsPerAgent.java @@ -21,6 +21,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.List; import org.matsim.api.core.v01.Scenario; @@ -32,7 +33,6 @@ import org.matsim.core.router.TripStructureUtils.Trip; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.contrib.socnetsim.jointtrips.population.JointActingTypes; diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/DumpSizeOfSelectedJointPlans.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/DumpSizeOfSelectedJointPlans.java index 2fca6b179bc..26a7c17c9e1 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/DumpSizeOfSelectedJointPlans.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/DumpSizeOfSelectedJointPlans.java @@ -21,6 +21,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -33,7 +34,6 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.core.utils.io.IOUtils; import org.matsim.core.utils.io.MatsimXmlParser; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.Counter; import org.xml.sax.Attributes; diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/ExtractDriverBeeflyDetours.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/ExtractDriverBeeflyDetours.java index a951ef14781..da34ee7ed57 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/ExtractDriverBeeflyDetours.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/analysis/scripts/ExtractDriverBeeflyDetours.java @@ -21,13 +21,13 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.Stack; import org.matsim.api.core.v01.Coord; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.core.utils.io.MatsimXmlParser; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.Counter; import org.xml.sax.Attributes; diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupMinLossSelectExpBetaFactory.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupMinLossSelectExpBetaFactory.java index 9f211616cdc..b6f397ca44a 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupMinLossSelectExpBetaFactory.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupMinLossSelectExpBetaFactory.java @@ -40,7 +40,7 @@ public class GroupMinLossSelectExpBetaFactory extends NonInnovativeStrategyFacto private final Scenario sc; private final IncompatiblePlansIdentifierFactory incompatiblePlans; - + @Inject public GroupMinLossSelectExpBetaFactory( Scenario sc , IncompatiblePlansIdentifierFactory incompatiblePlans ) { this.sc = sc; @@ -57,7 +57,7 @@ public GroupLevelPlanSelector createSelector() { new LossWeight(), (JointPlans) sc.getScenarioElement( JointPlans.ELEMENT_NAME ) ), MatsimRandom.getLocalInstance(), - sc.getConfig().planCalcScore().getBrainExpBeta()) ); + sc.getConfig().scoring().getBrainExpBeta()) ); } } diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupMinSelectExpBetaFactory.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupMinSelectExpBetaFactory.java index 9399f0d65c2..60c42842220 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupMinSelectExpBetaFactory.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupMinSelectExpBetaFactory.java @@ -54,7 +54,7 @@ public GroupLevelPlanSelector createSelector() { new LowestScoreOfJointPlanWeight( ((JointPlans) sc.getScenarioElement( JointPlans.ELEMENT_NAME )) ), MatsimRandom.getLocalInstance(), - sc.getConfig().planCalcScore().getBrainExpBeta()) ); + sc.getConfig().scoring().getBrainExpBeta()) ); } } diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupTimeAllocationMutatorFactory.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupTimeAllocationMutatorFactory.java index 032b81787ca..9c27ebe7b89 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupTimeAllocationMutatorFactory.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupTimeAllocationMutatorFactory.java @@ -79,8 +79,8 @@ public GroupPlanStrategy get() { public PlanAlgorithm getPlanAlgoInstance() { final int iteration = getReplanningContext().getIteration(); - final int firstIteration = config.controler().getFirstIteration(); - final double nIters = config.controler().getLastIteration() - firstIteration; + final int firstIteration = config.controller().getFirstIteration(); + final double nIters = config.controller().getLastIteration() - firstIteration; final double minTemp = 1; final double startMin = (2 / 3.) * nIters; final double progress = (iteration - firstIteration) / startMin; diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupWeightedSelectExpBetaFactory.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupWeightedSelectExpBetaFactory.java index 5c3a04b5d64..b3b683627e5 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupWeightedSelectExpBetaFactory.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/GroupWeightedSelectExpBetaFactory.java @@ -54,13 +54,13 @@ public GroupLevelPlanSelector createSelector() { sc.getConfig().getModule( GroupReplanningConfigGroup.GROUP_NAME ); - return + return new HighestWeightSelector( incompatiblePlansIdentifierFactory , new WeightedWeight( new LogitWeight( MatsimRandom.getLocalInstance(), - sc.getConfig().planCalcScore().getBrainExpBeta()), + sc.getConfig().scoring().getBrainExpBeta()), configGroup.getWeightAttributeName(), sc.getPopulation() ) ); diff --git a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/ParetoExpBetaFactory.java b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/ParetoExpBetaFactory.java index e42ae240f1f..e616e55e645 100644 --- a/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/ParetoExpBetaFactory.java +++ b/contribs/socnetsim/src/main/java/org/matsim/contrib/socnetsim/usage/replanning/strategies/ParetoExpBetaFactory.java @@ -48,13 +48,13 @@ public ParetoExpBetaFactory( IncompatiblePlansIdentifierFactory incompatiblePlan @Override public GroupLevelPlanSelector createSelector() { - return + return new HighestWeightSelector( incompatiblePlansIdentifierFactory, new ParetoWeight( new LogitWeight( MatsimRandom.getLocalInstance(), - sc.getConfig().planCalcScore().getBrainExpBeta())) ); + sc.getConfig().scoring().getBrainExpBeta())) ); } } diff --git a/contribs/socnetsim/test/input/org/matsim/contrib/socnetsim/config.xml b/contribs/socnetsim/test/input/org/matsim/contrib/socnetsim/config.xml index cc618ea1dcc..511d050ca86 100644 --- a/contribs/socnetsim/test/input/org/matsim/contrib/socnetsim/config.xml +++ b/contribs/socnetsim/test/input/org/matsim/contrib/socnetsim/config.xml @@ -32,11 +32,10 @@ - - + diff --git a/contribs/taxi/src/main/java/org/matsim/contrib/etaxi/run/RunETaxiBenchmark.java b/contribs/taxi/src/main/java/org/matsim/contrib/etaxi/run/RunETaxiBenchmark.java index 0236fe6a5ee..5e67a5e2105 100644 --- a/contribs/taxi/src/main/java/org/matsim/contrib/etaxi/run/RunETaxiBenchmark.java +++ b/contribs/taxi/src/main/java/org/matsim/contrib/etaxi/run/RunETaxiBenchmark.java @@ -72,16 +72,16 @@ public static void run(String [] configUrl, int nIterations) { Config config = ConfigUtils.loadConfig(configUrl, new MultiModeTaxiConfigGroup(ETaxiConfigGroups::createWithCustomETaxiOptimizerParams), new DvrpConfigGroup(), new EvConfigGroup()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); createControler(config, nIterations).run(); } public static Controler createControler(Config config, int runs) { - config.controler().setLastIteration(runs - 1); - config.controler().setDumpDataAtEnd(false); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); - config.controler().setCreateGraphs(false); + config.controller().setLastIteration(runs - 1); + config.controller().setDumpDataAtEnd(false); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); + config.controller().setCreateGraphs(false); DvrpBenchmarks.adjustConfig(config); Scenario scenario = createScenarioWithDrtRouteFactory(config); diff --git a/contribs/taxi/src/main/java/org/matsim/contrib/etaxi/run/RunETaxiScenario.java b/contribs/taxi/src/main/java/org/matsim/contrib/etaxi/run/RunETaxiScenario.java index 1d67f8be01e..f5598174103 100644 --- a/contribs/taxi/src/main/java/org/matsim/contrib/etaxi/run/RunETaxiScenario.java +++ b/contribs/taxi/src/main/java/org/matsim/contrib/etaxi/run/RunETaxiScenario.java @@ -58,7 +58,7 @@ public static void run(String [] args, boolean otfvis) { new MultiModeTaxiConfigGroup(ETaxiConfigGroups::createWithCustomETaxiOptimizerParams), new DvrpConfigGroup(), new OTFVisConfigGroup(), new EvConfigGroup()); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); createControler(config, otfvis).run(); } diff --git a/contribs/taxi/src/main/java/org/matsim/contrib/taxi/benchmark/RunTaxiBenchmark.java b/contribs/taxi/src/main/java/org/matsim/contrib/taxi/benchmark/RunTaxiBenchmark.java index 989ea7e4062..b87e10a3413 100644 --- a/contribs/taxi/src/main/java/org/matsim/contrib/taxi/benchmark/RunTaxiBenchmark.java +++ b/contribs/taxi/src/main/java/org/matsim/contrib/taxi/benchmark/RunTaxiBenchmark.java @@ -56,11 +56,11 @@ public static void run(URL configUrl, int runs) { } public static Controler createControler(Config config, int runs) { - config.controler().setLastIteration(runs - 1); - config.controler().setDumpDataAtEnd(false); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); - config.controler().setCreateGraphs(false); + config.controller().setLastIteration(runs - 1); + config.controller().setDumpDataAtEnd(false); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); + config.controller().setCreateGraphs(false); DvrpBenchmarks.adjustConfig(config); Scenario scenario = createScenarioWithDrtRouteFactory(config); diff --git a/contribs/taxi/src/main/java/org/matsim/contrib/taxi/run/examples/RunMultiModeTaxiExample.java b/contribs/taxi/src/main/java/org/matsim/contrib/taxi/run/examples/RunMultiModeTaxiExample.java index 2fd5bc00fdd..81d05a94c33 100644 --- a/contribs/taxi/src/main/java/org/matsim/contrib/taxi/run/examples/RunMultiModeTaxiExample.java +++ b/contribs/taxi/src/main/java/org/matsim/contrib/taxi/run/examples/RunMultiModeTaxiExample.java @@ -34,7 +34,7 @@ public static void run(URL configUrl, boolean otfvis, int lastIteration) { // load config Config config = ConfigUtils.loadConfig(configUrl, new MultiModeTaxiConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); TaxiControlerCreator.createControler(config, otfvis).run(); } diff --git a/contribs/taxi/src/main/java/org/matsim/contrib/taxi/run/examples/RunTaxiExample.java b/contribs/taxi/src/main/java/org/matsim/contrib/taxi/run/examples/RunTaxiExample.java index 7b4a44842c3..e3bc4048497 100644 --- a/contribs/taxi/src/main/java/org/matsim/contrib/taxi/run/examples/RunTaxiExample.java +++ b/contribs/taxi/src/main/java/org/matsim/contrib/taxi/run/examples/RunTaxiExample.java @@ -33,7 +33,7 @@ public static void run(URL configUrl, boolean otfvis, int lastIteration) { // load config Config config = ConfigUtils.loadConfig(configUrl, new MultiModeTaxiConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup()); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); TaxiControlerCreator.createControler(config, otfvis).run(); } } diff --git a/contribs/taxi/src/test/java/org/matsim/contrib/taxi/optimizer/TaxiOptimizerTests.java b/contribs/taxi/src/test/java/org/matsim/contrib/taxi/optimizer/TaxiOptimizerTests.java index 57b3ac811ca..f92b30ee28a 100644 --- a/contribs/taxi/src/test/java/org/matsim/contrib/taxi/optimizer/TaxiOptimizerTests.java +++ b/contribs/taxi/src/test/java/org/matsim/contrib/taxi/optimizer/TaxiOptimizerTests.java @@ -43,7 +43,7 @@ public static void runBenchmark(boolean vehicleDiversion, AbstractTaxiOptimizerP // mielec taxi mini benchmark contains only the morning peak (6:00 - 12:00) that is shifted by -6 hours (i.e. 0:00 - 6:00). URL configUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("mielec"), "mielec_taxi_mini_benchmark_config.xml"); var config = ConfigUtils.loadConfig(configUrl, new MultiModeTaxiConfigGroup(), new DvrpConfigGroup()); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); TaxiConfigGroup taxiCfg = TaxiConfigGroup.getSingleModeTaxiConfig(config); Optional.ofNullable(taxiCfg.getTaxiOptimizerParams()).ifPresent(taxiCfg::removeParameterSet); @@ -52,8 +52,8 @@ public static void runBenchmark(boolean vehicleDiversion, AbstractTaxiOptimizerP var controler = RunTaxiBenchmark.createControler(config, 1); // RunTaxiBenchmark.createControler() overrides some config params, this is a moment to adjust them - config.controler().setWriteEventsInterval(1); - config.controler().setDumpDataAtEnd(true); + config.controller().setWriteEventsInterval(1); + config.controller().setDumpDataAtEnd(true); controler.run(); diff --git a/contribs/taxi/src/test/java/org/matsim/contrib/taxi/run/RunTaxiScenarioTestIT.java b/contribs/taxi/src/test/java/org/matsim/contrib/taxi/run/RunTaxiScenarioTestIT.java index ee1f6728ea3..7e991fdfebe 100644 --- a/contribs/taxi/src/test/java/org/matsim/contrib/taxi/run/RunTaxiScenarioTestIT.java +++ b/contribs/taxi/src/test/java/org/matsim/contrib/taxi/run/RunTaxiScenarioTestIT.java @@ -51,8 +51,8 @@ private void runMielec(String plansFile, String taxisFile) { new OTFVisConfigGroup()); config.plans().setInputFile(plansFile); TaxiConfigGroup.getSingleModeTaxiConfig(config).taxisFile = taxisFile; - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setDumpDataAtEnd(false); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setDumpDataAtEnd(false); TaxiControlerCreator.createControler(config, false).run(); } } diff --git a/contribs/taxi/src/test/java/org/matsim/contrib/taxi/util/TaxiEventsReadersTest.java b/contribs/taxi/src/test/java/org/matsim/contrib/taxi/util/TaxiEventsReadersTest.java index 71db340ef1b..eba9e7a1c4b 100644 --- a/contribs/taxi/src/test/java/org/matsim/contrib/taxi/util/TaxiEventsReadersTest.java +++ b/contribs/taxi/src/test/java/org/matsim/contrib/taxi/util/TaxiEventsReadersTest.java @@ -46,7 +46,7 @@ import org.matsim.contrib.taxi.schedule.TaxiStayTask; import org.matsim.contrib.taxi.schedule.TaxiTaskType; 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(); TaxiEventsReaders.createEventsReader(eventsManager) .readStream(new ByteArrayInputStream(outputStream.toByteArray()), - ControlerConfigGroup.EventsFileFormat.xml); + ControllerConfigGroup.EventsFileFormat.xml); eventsManager.finishProcessing(); assertThat(handler.handledEvents).usingRecursiveFieldByFieldElementComparator() diff --git a/contribs/vsp/pom.xml b/contribs/vsp/pom.xml index 3db82269372..99614d63e78 100644 --- a/contribs/vsp/pom.xml +++ b/contribs/vsp/pom.xml @@ -140,7 +140,7 @@ org.apache.poi poi-ooxml - 5.2.3 + 5.2.4 @@ -174,12 +174,12 @@ org.openjfx javafx-graphics - 20.0.2 + 21.0.1 com.graphhopper graphhopper-core - 6.2 + 8.0 diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/vsp/scenario/SnzActivities.java b/contribs/vsp/src/main/java/org/matsim/contrib/vsp/scenario/SnzActivities.java index 8700bc0d86b..5687f8b2116 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/vsp/scenario/SnzActivities.java +++ b/contribs/vsp/src/main/java/org/matsim/contrib/vsp/scenario/SnzActivities.java @@ -1,7 +1,7 @@ package org.matsim.contrib.vsp.scenario; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; /** * Defines available activities and open- and closing times in Snz scenarios at vsp. @@ -54,7 +54,7 @@ public enum SnzActivities { /** * Apply start and end time to params. */ - public PlanCalcScoreConfigGroup.ActivityParams apply(PlanCalcScoreConfigGroup.ActivityParams params) { + public ScoringConfigGroup.ActivityParams apply(ScoringConfigGroup.ActivityParams params) { if (start >= 0) params = params.setOpeningTime(start * 3600.); if (end >= 0) @@ -70,18 +70,18 @@ public static void addScoringParams(Config config) { for (SnzActivities value : SnzActivities.values()) { for (long ii = 600; ii <= 97200; ii += 600) { - config.planCalcScore().addActivityParams(value.apply(new PlanCalcScoreConfigGroup.ActivityParams(value.name() + "_" + ii).setTypicalDuration(ii))); + config.scoring().addActivityParams(value.apply(new ScoringConfigGroup.ActivityParams(value.name() + "_" + ii).setTypicalDuration(ii))); } } - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("car interaction").setTypicalDuration(60)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("ride interaction").setTypicalDuration(60)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("bike interaction").setTypicalDuration(60)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("car interaction").setTypicalDuration(60)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("ride interaction").setTypicalDuration(60)); + config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("bike interaction").setTypicalDuration(60)); - config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("other").setTypicalDuration(600 * 3)); + 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)); } } diff --git a/contribs/vsp/src/main/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributes.java b/contribs/vsp/src/main/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributes.java index afa71b067aa..861a51c33c4 100644 --- a/contribs/vsp/src/main/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributes.java +++ b/contribs/vsp/src/main/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributes.java @@ -25,7 +25,7 @@ import org.matsim.api.core.v01.IdMap; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.ScenarioConfigGroup; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; @@ -60,7 +60,7 @@ public class PersonScoringParametersFromPersonAttributes implements ScoringParametersForPerson { Logger log = LogManager.getLogger(PersonScoringParametersFromPersonAttributes.class); - private final PlanCalcScoreConfigGroup config; + private final ScoringConfigGroup config; private final ScenarioConfigGroup scConfig; private final TransitConfigGroup transitConfigGroup; private final Map, ScoringParameters> params = new IdMap<>(Person.class); @@ -68,8 +68,8 @@ public class PersonScoringParametersFromPersonAttributes implements ScoringParam private final Map> activityParamsPerSubpopulation = new ConcurrentHashMap<>(); @Inject - PersonScoringParametersFromPersonAttributes(Population population, PlanCalcScoreConfigGroup planCalcScoreConfigGroup, ScenarioConfigGroup scenarioConfigGroup, TransitConfigGroup transitConfigGroup) { - this.config = planCalcScoreConfigGroup; + PersonScoringParametersFromPersonAttributes(Population population, ScoringConfigGroup scoringConfigGroup, ScenarioConfigGroup scenarioConfigGroup, TransitConfigGroup transitConfigGroup) { + this.config = scoringConfigGroup; this.scConfig = scenarioConfigGroup; this.transitConfigGroup = transitConfigGroup; this.globalAvgIncome = computeAvgIncome(population); @@ -114,13 +114,13 @@ public ScoringParameters getScoringParameters(Person person) { * point of view than giving each ScoringFunction its own copy of the params. */ - PlanCalcScoreConfigGroup.ScoringParameterSet subpopulationScoringParams = this.config.getScoringParameters(subpopulation); + ScoringConfigGroup.ScoringParameterSet subpopulationScoringParams = this.config.getScoringParameters(subpopulation); // (we can set scoring params per subpopulation, so retrieve them as starting point. kai, apr'22) // save the activityParams of the subpopulation so we need to build them only once. this.activityParamsPerSubpopulation.computeIfAbsent(subpopulation, k -> { Map activityParams = new TreeMap<>(); - for (PlanCalcScoreConfigGroup.ActivityParams params : subpopulationScoringParams.getActivityParams()) { + for (ScoringConfigGroup.ActivityParams params : subpopulationScoringParams.getActivityParams()) { ActivityUtilityParameters.Builder factory = new ActivityUtilityParameters.Builder(params); activityParams.put(params.getActivityType(), factory.build()); } @@ -134,7 +134,7 @@ public ScoringParameters getScoringParameters(Person person) { if (transitConfigGroup.isUseTransit()) { // this is the PT stage activity: - PlanCalcScoreConfigGroup.ActivityParams transitActivityParams = new PlanCalcScoreConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); + ScoringConfigGroup.ActivityParams transitActivityParams = new ScoringConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); transitActivityParams.setTypicalDuration(120.0); transitActivityParams.setOpeningTime(0.); transitActivityParams.setClosingTime(0.); @@ -170,7 +170,7 @@ public ScoringParameters getScoringParameters(Person person) { } // copy other params from subpopulation config - PlanCalcScoreConfigGroup.ModeParams subpopulationModeParams = subpopulationScoringParams.getModes().get(entry.getKey()); + ScoringConfigGroup.ModeParams subpopulationModeParams = subpopulationScoringParams.getModes().get(entry.getKey()); modeUtilityParamsBuilder.setMarginalUtilityOfTraveling_s(subpopulationModeParams.getMarginalUtilityOfTraveling()); modeUtilityParamsBuilder.setMarginalUtilityOfDistance_m(subpopulationModeParams.getMarginalUtilityOfDistance()); modeUtilityParamsBuilder.setMonetaryDistanceRate(subpopulationModeParams.getMonetaryDistanceRate()); diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/CarrierLoadAnalysis.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/CarrierLoadAnalysis.java similarity index 65% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/CarrierLoadAnalysis.java rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/CarrierLoadAnalysis.java index 7a4d89cdfb3..7e858ee725d 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/CarrierLoadAnalysis.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/CarrierLoadAnalysis.java @@ -1,13 +1,34 @@ -package org.matsim.contrib.freight.analysis; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.analysis; 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.Event; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.events.CarrierShipmentDeliveryStartEvent; -import org.matsim.contrib.freight.events.CarrierShipmentPickupStartEvent; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.events.CarrierShipmentDeliveryStartEvent; +import org.matsim.freight.carriers.events.CarrierShipmentPickupStartEvent; import org.matsim.core.events.handler.BasicEventHandler; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; @@ -21,7 +42,7 @@ import java.util.LinkedList; import java.util.Map; -import static org.matsim.contrib.freight.events.CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND; +import static org.matsim.freight.carriers.events.CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND; /** * @author Kai Martins-Turner (kturner) diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/CarrierPlanAnalysis.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/CarrierPlanAnalysis.java similarity index 50% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/CarrierPlanAnalysis.java rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/CarrierPlanAnalysis.java index 5892430bf81..e8f0439af85 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/CarrierPlanAnalysis.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/CarrierPlanAnalysis.java @@ -1,10 +1,31 @@ -package org.matsim.contrib.freight.analysis; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.analysis; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; 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 java.io.BufferedWriter; import java.io.FileWriter; @@ -40,7 +61,7 @@ public void runAnalysisAndWriteStats(String analysisOutputDirectory) throws IOEx BufferedWriter bw1 = new BufferedWriter(new FileWriter(fileName)); //Write headline: - bw1.write("carrierId \t scoreOfSelectedPlan \t nuOfTours \t nuOfShipments(input) \t nuOfServices(input) "); + bw1.write("carrierId \t MATSimScoreSelectedPlan \t jSpritScoreSelectedPlan \t nuOfTours \t nuOfShipments(input) \t nuOfServices(input) "); bw1.newLine(); final TreeMap, Carrier> sortedCarrierMap = new TreeMap<>(carriers.getCarriers()); @@ -48,6 +69,7 @@ public void runAnalysisAndWriteStats(String analysisOutputDirectory) throws IOEx for (Carrier carrier : sortedCarrierMap.values()) { bw1.write(carrier.getId().toString()); bw1.write("\t" + carrier.getSelectedPlan().getScore()); + bw1.write("\t" + carrier.getSelectedPlan().getJspritScore()); bw1.write("\t" + carrier.getSelectedPlan().getScheduledTours().size()); bw1.write("\t" + carrier.getShipments().size()); bw1.write("\t" + carrier.getServices().size()); diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisEventHandler.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventHandler.java similarity index 94% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisEventHandler.java rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventHandler.java index 15a0dd00702..2f322e8640f 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisEventHandler.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventHandler.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2021 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.analysis; +package org.matsim.freight.carriers.analysis; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -28,26 +28,26 @@ import org.matsim.api.core.v01.events.handler.*; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -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.Carriers; -import org.matsim.contrib.freight.events.CarrierServiceEndEvent; -import org.matsim.contrib.freight.events.CarrierServiceStartEvent; -import org.matsim.contrib.freight.events.CarrierShipmentDeliveryEndEvent; -import org.matsim.contrib.freight.events.CarrierShipmentPickupEndEvent; -import org.matsim.contrib.freight.events.eventhandler.FreightServiceEndEventHandler; -import org.matsim.contrib.freight.events.eventhandler.FreightServiceStartEventHandler; -import org.matsim.contrib.freight.events.eventhandler.FreightShipmentDeliveryEventHandler; -import org.matsim.contrib.freight.events.eventhandler.FreightShipmentPickupEventHandler; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierService; +import org.matsim.freight.carriers.CarrierShipment; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.events.CarrierServiceEndEvent; +import org.matsim.freight.carriers.events.CarrierServiceStartEvent; +import org.matsim.freight.carriers.events.CarrierShipmentDeliveryEndEvent; +import org.matsim.freight.carriers.events.CarrierShipmentPickupEndEvent; +import org.matsim.freight.carriers.events.eventhandler.CarrierServiceEndEventHandler; +import org.matsim.freight.carriers.events.eventhandler.CarrierServiceStartEventHandler; +import org.matsim.freight.carriers.events.eventhandler.CarrierShipmentDeliveryEndEventHandler; +import org.matsim.freight.carriers.events.eventhandler.CarrierShipmentPickupEndEventHandler; import org.matsim.core.network.NetworkUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.Vehicles; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -59,7 +59,7 @@ * */ @Deprecated(since = "apr23") -class FreightAnalysisEventHandler implements ActivityStartEventHandler, LinkEnterEventHandler, LinkLeaveEventHandler, PersonEntersVehicleEventHandler, PersonLeavesVehicleEventHandler, FreightShipmentPickupEventHandler, FreightShipmentDeliveryEventHandler, FreightServiceStartEventHandler, FreightServiceEndEventHandler { +class FreightAnalysisEventHandler implements ActivityStartEventHandler, LinkEnterEventHandler, LinkLeaveEventHandler, PersonEntersVehicleEventHandler, PersonLeavesVehicleEventHandler, CarrierShipmentPickupEndEventHandler, CarrierShipmentDeliveryEndEventHandler, CarrierServiceStartEventHandler, CarrierServiceEndEventHandler { private final static Logger log = LogManager.getLogger(FreightAnalysisEventHandler.class); private final Vehicles vehicles; diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisServiceTracking.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisServiceTracking.java similarity index 96% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisServiceTracking.java rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisServiceTracking.java index 1c0edb4d814..88ee09b7b5c 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisServiceTracking.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisServiceTracking.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2021 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,13 +19,13 @@ * */ -package org.matsim.contrib.freight.analysis; +package org.matsim.freight.carriers.analysis; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityStartEvent; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.*; -import org.matsim.contrib.freight.events.CarrierServiceEndEvent; -import org.matsim.contrib.freight.events.CarrierServiceStartEvent; +import org.matsim.freight.carriers.*; +import org.matsim.freight.carriers.events.CarrierServiceEndEvent; +import org.matsim.freight.carriers.events.CarrierServiceStartEvent; import java.util.LinkedHashMap; diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisShipmentTracking.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisShipmentTracking.java similarity index 93% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisShipmentTracking.java rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisShipmentTracking.java index beb8d66f846..e7126cca05e 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisShipmentTracking.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisShipmentTracking.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2021 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,15 +19,15 @@ * */ -package org.matsim.contrib.freight.analysis; +package org.matsim.freight.carriers.analysis; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityStartEvent; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierShipment; -import org.matsim.contrib.freight.events.CarrierShipmentDeliveryEndEvent; -import org.matsim.contrib.freight.events.CarrierShipmentPickupEndEvent; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierShipment; +import org.matsim.freight.carriers.events.CarrierShipmentDeliveryEndEvent; +import org.matsim.freight.carriers.events.CarrierShipmentPickupEndEvent; import java.util.LinkedHashMap; import java.util.LinkedHashSet; diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisVehicleTracking.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisVehicleTracking.java similarity index 97% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisVehicleTracking.java rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisVehicleTracking.java index 8130eaa4ffb..5bc4e6a690a 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightAnalysisVehicleTracking.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisVehicleTracking.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2021 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,7 +19,7 @@ * */ -package org.matsim.contrib.freight.analysis; +package org.matsim.freight.carriers.analysis; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -28,7 +28,7 @@ import org.matsim.api.core.v01.events.LinkLeaveEvent; import org.matsim.api.core.v01.events.PersonLeavesVehicleEvent; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.Carrier; +import org.matsim.freight.carriers.Carrier; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightTimeAndDistanceAnalysisEventsHandler.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightTimeAndDistanceAnalysisEventsHandler.java similarity index 82% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightTimeAndDistanceAnalysisEventsHandler.java rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightTimeAndDistanceAnalysisEventsHandler.java index bfd229df7ed..42c95fb70ad 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/FreightTimeAndDistanceAnalysisEventsHandler.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightTimeAndDistanceAnalysisEventsHandler.java @@ -1,4 +1,25 @@ -package org.matsim.contrib.freight.analysis; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.analysis; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -6,11 +27,11 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.events.LinkEnterEvent; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.Tour; -import org.matsim.contrib.freight.controler.FreightUtils; -import org.matsim.contrib.freight.events.CarrierTourEndEvent; -import org.matsim.contrib.freight.events.CarrierTourStartEvent; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.Tour; +import org.matsim.freight.carriers.events.CarrierTourEndEvent; +import org.matsim.freight.carriers.events.CarrierTourStartEvent; import org.matsim.core.events.handler.BasicEventHandler; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; @@ -141,7 +162,7 @@ void writeTravelTimeAndDistancePerVehicleType(String analysisOutputDirectory, Sc //----- All VehicleTypes in CarriervehicleTypes container. Used so that even unused vehTypes appear in the output - TreeMap, VehicleType> vehicleTypesMap = new TreeMap<>(FreightUtils.getCarrierVehicleTypes(scenario).getVehicleTypes()); + TreeMap, VehicleType> vehicleTypesMap = new TreeMap<>(CarriersUtils.getCarrierVehicleTypes(scenario).getVehicleTypes()); //For the case that there are additional vehicle types found in the events. for (VehicleType vehicleType : vehicleId2VehicleType.values()) { vehicleTypesMap.putIfAbsent(vehicleType.getId(), vehicleType); diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/Readme.md b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/Readme.md similarity index 100% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/Readme.md rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/Readme.md diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/RunFreightAnalysis.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysis.java similarity index 92% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/RunFreightAnalysis.java rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysis.java index 709511ad323..30758ffb516 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/RunFreightAnalysis.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysis.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2021 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,12 +19,12 @@ * */ -package org.matsim.contrib.freight.analysis; +package org.matsim.freight.carriers.analysis; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.CarrierPlanXmlReader; -import org.matsim.contrib.freight.carrier.CarrierVehicleTypes; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.CarrierPlanXmlReader; +import org.matsim.freight.carriers.CarrierVehicleTypes; +import org.matsim.freight.carriers.Carriers; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; diff --git a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/RunFreightAnalysisEventbased.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java similarity index 82% rename from contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/RunFreightAnalysisEventbased.java rename to contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java index bcc3753f621..1a60ed8b6a3 100644 --- a/contribs/vsp/src/main/java/org/matsim/contrib/freight/analysis/RunFreightAnalysisEventbased.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2021 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,14 +19,14 @@ * */ -package org.matsim.contrib.freight.analysis; +package org.matsim.freight.carriers.analysis; 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.contrib.freight.events.CarrierEventsReaders; +import org.matsim.freight.carriers.FreightCarriersConfigGroup; +import org.matsim.freight.carriers.CarriersUtils; +import org.matsim.freight.carriers.events.CarrierEventsReaders; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; @@ -48,9 +48,9 @@ * * @author kturner (Kai Martins-Turner) */ -public class RunFreightAnalysisEventbased { +public class RunFreightAnalysisEventBased { - private static final Logger log = LogManager.getLogger(RunFreightAnalysisEventbased.class); + private static final Logger log = LogManager.getLogger(RunFreightAnalysisEventBased.class); //Were is your simulation output, that should be analysed? private final String SIM_OUTPUT_PATH ; @@ -62,7 +62,7 @@ public class RunFreightAnalysisEventbased { * @param analysisOutputPath The directory where the result of the analysis should go to * @param globalCrs */ - public RunFreightAnalysisEventbased(String simOutputPath, String analysisOutputPath, String globalCrs) { + public RunFreightAnalysisEventBased(String simOutputPath, String analysisOutputPath, String globalCrs) { this.SIM_OUTPUT_PATH = simOutputPath; this.ANALYSIS_OUTPUT_PATH = analysisOutputPath; this.GLOBAL_CRS = globalCrs; @@ -75,13 +75,13 @@ public void runAnalysis() throws IOException { config.network().setInputFile(SIM_OUTPUT_PATH + "output_network.xml.gz"); config.global().setCoordinateSystem(GLOBAL_CRS); config.plans().setInputFile(null); - config.parallelEventHandling().setNumberOfThreads(null); - config.parallelEventHandling().setEstimatedNumberOfEvents(null); + config.eventsManager().setNumberOfThreads(null); + config.eventsManager().setEstimatedNumberOfEvents(null); config.global().setNumberOfThreads(1); //freight settings - FreightConfigGroup freightConfigGroup = ConfigUtils.addOrGetModule( config, FreightConfigGroup.class ) ; - freightConfigGroup.setCarriersFile( SIM_OUTPUT_PATH + "output_carriers.xml.gz"); - freightConfigGroup.setCarriersVehicleTypesFile(SIM_OUTPUT_PATH + "output_carriersVehicleTypes.xml.gz"); + FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule( config, FreightCarriersConfigGroup.class ) ; + freightCarriersConfigGroup.setCarriersFile( SIM_OUTPUT_PATH + "output_carriers.xml.gz"); + freightCarriersConfigGroup.setCarriersVehicleTypesFile(SIM_OUTPUT_PATH + "output_allVehicles.xml.gz"); //Were to store the analysis output? String analysisOutputDirectory = ANALYSIS_OUTPUT_PATH; @@ -96,11 +96,11 @@ public void runAnalysis() throws IOException { Scenario scenario = ScenarioUtils.loadScenario(config); //load carriers according to freight config - FreightUtils.loadCarriersAccordingToFreightConfig( scenario ); + CarriersUtils.loadCarriersAccordingToFreightConfig( scenario ); // CarrierPlanAnalysis - CarrierPlanAnalysis carrierPlanAnalysis = new CarrierPlanAnalysis(FreightUtils.getCarriers(scenario)); + CarrierPlanAnalysis carrierPlanAnalysis = new CarrierPlanAnalysis(CarriersUtils.getCarriers(scenario)); carrierPlanAnalysis.runAnalysisAndWriteStats(analysisOutputDirectory); // Prepare eventsManager - start of event based Analysis; @@ -109,7 +109,7 @@ public void runAnalysis() throws IOException { FreightTimeAndDistanceAnalysisEventsHandler freightTimeAndDistanceAnalysisEventsHandler = new FreightTimeAndDistanceAnalysisEventsHandler(scenario); eventsManager.addHandler(freightTimeAndDistanceAnalysisEventsHandler); - CarrierLoadAnalysis carrierLoadAnalysis = new CarrierLoadAnalysis(FreightUtils.getCarriers(scenario)); + CarrierLoadAnalysis carrierLoadAnalysis = new CarrierLoadAnalysis(CarriersUtils.getCarriers(scenario)); eventsManager.addHandler(carrierLoadAnalysis); eventsManager.initProcessing(); diff --git a/contribs/vsp/src/main/java/playground/vsp/airPollution/exposure/EmissionResponsibilityTravelDisutilityCalculatorFactory.java b/contribs/vsp/src/main/java/playground/vsp/airPollution/exposure/EmissionResponsibilityTravelDisutilityCalculatorFactory.java index 8ae1e6eabb7..e0c3d929689 100644 --- a/contribs/vsp/src/main/java/playground/vsp/airPollution/exposure/EmissionResponsibilityTravelDisutilityCalculatorFactory.java +++ b/contribs/vsp/src/main/java/playground/vsp/airPollution/exposure/EmissionResponsibilityTravelDisutilityCalculatorFactory.java @@ -24,7 +24,7 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.EmissionModule; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.costcalculators.RandomizingTimeDistanceTravelDisutilityFactory; import org.matsim.core.router.costcalculators.TravelDisutilityFactory; import org.matsim.core.router.util.TravelDisutility; @@ -41,7 +41,7 @@ public class EmissionResponsibilityTravelDisutilityCalculatorFactory implements private RandomizingTimeDistanceTravelDisutilityFactory randomizedTimeDistanceTravelDisutilityFactory; @Inject private EmissionModule emissionModule; @Inject private EmissionResponsibilityCostModule emissionCostModule; - @Inject private PlanCalcScoreConfigGroup cnScoringGroup; + @Inject private ScoringConfigGroup cnScoringGroup; private Set> hotspotLinks = null; @Inject private Vehicles vehicles; diff --git a/contribs/vsp/src/main/java/playground/vsp/airPollution/flatEmissions/EmissionTravelDisutilityCalculatorFactory.java b/contribs/vsp/src/main/java/playground/vsp/airPollution/flatEmissions/EmissionTravelDisutilityCalculatorFactory.java index 3158ac1e854..1b6814f1388 100644 --- a/contribs/vsp/src/main/java/playground/vsp/airPollution/flatEmissions/EmissionTravelDisutilityCalculatorFactory.java +++ b/contribs/vsp/src/main/java/playground/vsp/airPollution/flatEmissions/EmissionTravelDisutilityCalculatorFactory.java @@ -24,7 +24,7 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.EmissionModule; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.costcalculators.RandomizingTimeDistanceTravelDisutilityFactory; import org.matsim.core.router.costcalculators.TravelDisutilityFactory; import org.matsim.core.router.util.TravelDisutility; @@ -41,7 +41,7 @@ public class EmissionTravelDisutilityCalculatorFactory implements TravelDisutili private final RandomizingTimeDistanceTravelDisutilityFactory randomizedTimeDistanceTravelDisutilityFactory; @Inject private EmissionModule emissionModule; @Inject private EmissionCostModule emissionCostModule; - @Inject private PlanCalcScoreConfigGroup cnScoringGroup; + @Inject private ScoringConfigGroup cnScoringGroup; private Set> hotspotLinks = null; @Inject private Vehicles vehicles; diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/DefaultAnalysis_ik.java b/contribs/vsp/src/main/java/playground/vsp/analysis/DefaultAnalysis_ik.java index 7fcaa40fb41..59e04000322 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/DefaultAnalysis_ik.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/DefaultAnalysis_ik.java @@ -20,38 +20,35 @@ package playground.vsp.analysis; import java.io.File; +import java.io.UncheckedIOException; import java.util.LinkedList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.api.core.v01.population.Person; import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.config.groups.VspExperimentalConfigGroup; import org.matsim.core.events.EventsReaderXMLv1; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.handler.EventHandler; import org.matsim.core.gbl.Gbl; import org.matsim.core.scenario.MutableScenario; -import org.matsim.core.utils.io.UncheckedIOException; import playground.vsp.analysis.modules.AbstractAnalysisModule; import playground.vsp.analysis.modules.waitingTimes.WaitingTimesAnalyzer; -import playground.vsp.analysis.modules.welfareAnalyzer.WelfareAnalyzer; /** - * + * * @author ikaddoura, aneumann * */ public class DefaultAnalysis_ik { - + private final static Logger log = LogManager.getLogger(DefaultAnalysis_ik.class); - + private final String outputDir; private final String eventsFile; private final MutableScenario scenario; - + private final List anaModules = new LinkedList(); public DefaultAnalysis_ik(MutableScenario scenario, String iterationOutputDir, String eventsFile) { @@ -62,7 +59,7 @@ public DefaultAnalysis_ik(MutableScenario scenario, String iterationOutputDir, S public void init(String aasRunnerConfigFile){ log.info("Configuration through config file is currently not implemented. Initializing all modules with defaults..."); - + // END of configuration file // EmissionEventsWriter emiWriter = new EmissionEventsWriter(ptDriverPrefix, this.outputDir); @@ -85,35 +82,35 @@ public void init(String aasRunnerConfigFile){ // vcg.setDetailedColdEmissionFactorsFile(detailedColdEmissionFactorsFile); // emiWriter.init(scenario); // this.anaModules.add(emiWriter); -// +// // // emission events file required for this analysis module: // String emissionsEventsFile = "/Users/Ihab/Documents/workspace/shared-svn/studies/ihab/test/output/test_fakePt/ITERS/it.0/analysis/EmissionEventsWriter/emission.events.xml"; // EmissionsAnalyzer emiAna = new EmissionsAnalyzer(ptDriverPrefix, emissionsEventsFile); // emiAna.init(scenario); // this.anaModules.add(emiAna); -// +// // // number of detailed slots required for this analysis module // int numberOfDetailedSlots = 5; // VehDelayAtStopHistogramAnalyzer delayHistogramAna = new VehDelayAtStopHistogramAnalyzer(ptDriverPrefix, numberOfDetailedSlots); // delayHistogramAna.init(scenario); // this.anaModules.add(delayHistogramAna); - + // WelfareAnalyzer welfareAna = new WelfareAnalyzer(); // welfareAna.init(scenario); // this.anaModules.add(welfareAna); - + WaitingTimesAnalyzer waitingTimeAna = new WaitingTimesAnalyzer(); waitingTimeAna.init(scenario); this.anaModules.add(waitingTimeAna); // END ugly code - Initialization needs to be configurable - + // for (Person person : this.scenario.getPopulation().getPersons().values()) { // if (person.getId().toString().startsWith(ptDriverPrefix)){ // throw new RuntimeException("Person " + person.getId() + " has the same prefix as the pt Driver: " + ptDriverPrefix + ". Aborting..."); // } // } - + log.info("Initializing all modules with defaults... done."); } @@ -124,7 +121,7 @@ public void preProcess(){ } log.info("Preprocessing all modules... done."); } - + public void run(){ EventsManager eventsManager = EventsUtils.createEventsManager(); for (AbstractAnalysisModule module : this.anaModules) { @@ -140,7 +137,7 @@ public void run(){ log.warn("Failed parsing " + this.eventsFile + ". Skipping events handling..."); } } - + public void postProcess(){ log.info("Postprocessing all modules..."); for (AbstractAnalysisModule module : this.anaModules) { @@ -148,12 +145,12 @@ public void postProcess(){ } log.info("Postprocessing all modules... done."); } - + public void writeResults(){ log.info("Writing results for all modules..."); log.info("Generating output directory " + this.outputDir); new File(this.outputDir).mkdir(); - + for (AbstractAnalysisModule module : this.anaModules) { String moduleOutputDir = this.outputDir + module.getName() + "/"; log.info("Writing results of module " + module.getName() + " to " + moduleOutputDir + "..."); diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/modalAnalyses/modalShare/ModalShareControlerListener.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/modalAnalyses/modalShare/ModalShareControlerListener.java index 758bd5814d0..829f58ac57f 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/modalAnalyses/modalShare/ModalShareControlerListener.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/modalAnalyses/modalShare/ModalShareControlerListener.java @@ -51,13 +51,13 @@ public class ModalShareControlerListener implements StartupListener, IterationEn @Override public void notifyStartup(StartupEvent event) { - this.firstIteration = event.getServices().getConfig().controler().getFirstIteration(); + this.firstIteration = event.getServices().getConfig().controller().getFirstIteration(); this.events.addHandler(this.modalShareHandler); } @Override public void notifyIterationEnds(IterationEndsEvent event) { - String outputDir = event.getServices().getConfig().controler().getOutputDirectory(); + String outputDir = event.getServices().getConfig().controller().getOutputDirectory(); SortedMap mode2legs = this.modalShareHandler.getMode2numberOflegs(); modeHistory.addAll(mode2legs.keySet()); diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/modalAnalyses/modalTripTime/ModalTravelTimeControlerListener.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/modalAnalyses/modalTripTime/ModalTravelTimeControlerListener.java index e8bae833ad3..604fa8a1f0f 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/modalAnalyses/modalTripTime/ModalTravelTimeControlerListener.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/modalAnalyses/modalTripTime/ModalTravelTimeControlerListener.java @@ -55,14 +55,14 @@ public class ModalTravelTimeControlerListener implements StartupListener, Iterat @Override public void notifyStartup(StartupEvent event) { - this.firstIteration = event.getServices().getConfig().controler().getFirstIteration(); + this.firstIteration = event.getServices().getConfig().controller().getFirstIteration(); this.events.addHandler(this.travelTimeHandler); } @Override public void notifyIterationEnds(IterationEndsEvent event) { - String outputDir = event.getServices().getConfig().controler().getOutputDirectory(); + String outputDir = event.getServices().getConfig().controller().getOutputDirectory(); SortedMap mode2AvgTripTime = modalAvgTime(); modeHistory.addAll(mode2AvgTripTime.keySet()); diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/simpleTripAnalyzer/SimpleTripAnalyzer.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/simpleTripAnalyzer/SimpleTripAnalyzer.java index 01555386963..877f39c9eab 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/simpleTripAnalyzer/SimpleTripAnalyzer.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/simpleTripAnalyzer/SimpleTripAnalyzer.java @@ -55,17 +55,17 @@ import org.matsim.core.utils.io.IOUtils; /** - * A simple analysis-class for a very basic MATSim-Scenario, i.e it should be used + * A simple analysis-class for a very basic MATSim-Scenario, i.e it should be used * with physical simulation of car-trips only. All other modes must be teleported. Thus, - * this class will throw a runtime-exception when {@link ScenarioConfigGroup#isUseTransit()} is true. - * + * this class will throw a runtime-exception when {@link ScenarioConfigGroup#isUseTransit()} is true. + * * @author droeder * */ -public final class SimpleTripAnalyzer extends AbstractPersonAlgorithm +public final class SimpleTripAnalyzer extends AbstractPersonAlgorithm implements LinkLeaveEventHandler, PersonArrivalEventHandler, - PersonDepartureEventHandler, + PersonDepartureEventHandler, PersonStuckEventHandler, VehicleEntersTrafficEventHandler, VehicleLeavesTrafficEventHandler { @SuppressWarnings("unused") @@ -74,15 +74,15 @@ public final class SimpleTripAnalyzer extends AbstractPersonAlgorithm private Network net; private Set> pIds; private Map distFactors; - + private Vehicle2DriverEventHandler delegate = new Vehicle2DriverEventHandler(); - + public SimpleTripAnalyzer(Config c, Network net, Set> pIds) throws RuntimeException{ if(c.transit().isUseTransit() ){ throw new RuntimeException("This analysis is structured very simple. " + "Thus, it does not allow physically simulated transit!"); } - this.distFactors = c.plansCalcRoute().getBeelineDistanceFactors() ; + this.distFactors = c.routing().getBeelineDistanceFactors() ; this.net = net; this.pIds = pIds; } @@ -106,9 +106,9 @@ public void handleEvent(PersonDepartureEvent event) { mode = (mode == TransportMode.transit_walk) ? TransportMode.walk : mode; // cars start at the end of a link, thus we subtract the link-length for car-trips. //the distance for other modes is Double.NaN as they are teleported. - t.startTrip(event.getTime(), mode, + t.startTrip(event.getTime(), mode, (mode == TransportMode.car) ? (-calcLinkDistance(event.getLinkId())) : Double.NaN); - + } @Override @@ -120,7 +120,7 @@ public void handleEvent(LinkLeaveEvent event) { t.passLink(calcLinkDistance(event.getLinkId())); } - + @Override public void handleEvent(PersonArrivalEvent event) { Traveller t = this.traveller.get(event.getPersonId()); @@ -129,7 +129,7 @@ public void handleEvent(PersonArrivalEvent event) { } t.endTrip(event.getTime(), calcLinkDistance(event.getLinkId())); } - + @Override public void handleEvent(PersonStuckEvent event) { Traveller t = this.traveller.get(event.getPersonId()); @@ -138,7 +138,7 @@ public void handleEvent(PersonStuckEvent event) { } t.setStuck(); } - + @Override public void handleEvent(VehicleEntersTrafficEvent event) { delegate.handleEvent(event); @@ -169,7 +169,7 @@ public void run(Person person) { trip.beeline = calcBeelineDistance(trip.from, trip.to); // dist for non-car-modes is calculated with a factor if(!trip.mode.equals(TransportMode.car)){ - trip.dist = this.distFactors.get( trip.mode ) * trip.beeline; + trip.dist = this.distFactors.get( trip.mode ) * trip.beeline; } // there will be no more trips if(trip.stuck) return; @@ -177,7 +177,7 @@ public void run(Person person) { } // ##################helper methods ####################### - + /** * @param linkId * @return @@ -200,7 +200,7 @@ private Double calcBeelineDistance(Coord from, Coord to) { * @param outputPath */ public void dumpData(String outputPath, String fileprefix) { - BufferedWriter w = IOUtils.getBufferedWriter(outputPath + System.getProperty("file.separator") + + BufferedWriter w = IOUtils.getBufferedWriter(outputPath + System.getProperty("file.separator") + ((fileprefix == null) ? "" : (fileprefix.endsWith(".") ? fileprefix : (fileprefix + "."))) + "trips.csv.gz"); try { w.write(Traveller.HEADER + "\n"); @@ -216,10 +216,10 @@ public void dumpData(String outputPath, String fileprefix) { } //##################getter/setter############################### - + public final Map, Traveller> getTraveller(){ return traveller; } - + } diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/transitVehicleVolume/TransitVehicleVolumeAnalyzer.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/transitVehicleVolume/TransitVehicleVolumeAnalyzer.java index db215077acb..0063fd989f6 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/transitVehicleVolume/TransitVehicleVolumeAnalyzer.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/transitVehicleVolume/TransitVehicleVolumeAnalyzer.java @@ -18,6 +18,7 @@ * *********************************************************************** */ package playground.vsp.analysis.modules.transitVehicleVolume; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -40,7 +41,6 @@ import org.matsim.core.events.handler.EventHandler; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.gis.ShapeFileWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.counts.Count; import org.matsim.counts.Counts; import org.matsim.counts.Volume; @@ -90,13 +90,13 @@ public void preProcessData() { public void postProcessData() { this.createTotals(); } - + private void createTotals() { // count totals this.mode2Link2Total = new HashMap>(); Double total; for(Entry> e: this.handler.getMode2Counts().entrySet()){ - Map temp = new HashMap(); + Map temp = new HashMap(); for(Count c: e.getValue().getCounts().values()){ total = new Double(0.); for(Volume v: c.getVolumes().values()){ @@ -114,7 +114,7 @@ public void writeResults(String outputFolder) { writeModeShape(e.getKey(), e.getValue(), this.mode2Link2Total.get(e.getKey()), outputFolder + e.getKey() + ".shp", this.targetCoordinateSystem); } } - + private void writeModeShape(String name, Counts counts, Map mode2Total, String file, String targetCoordinateSystem){ SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.setCRS(MGC.getCRS(targetCoordinateSystem)); @@ -126,9 +126,9 @@ private void writeModeShape(String name, Counts counts, Map mo b.add(String.valueOf(i), Double.class); } SimpleFeatureBuilder builder = new SimpleFeatureBuilder(b.buildFeatureType()); - + Collection features = new ArrayList(); - + Object[] featureAttribs; for(Count c: counts.getCounts().values()){ featureAttribs = new Object[2 + this.handler.getMaxTimeSlice() + 1]; diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/userBenefits/UserBenefitsCalculator.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/userBenefits/UserBenefitsCalculator.java index 57ade159f57..f67b7f0fc98 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/userBenefits/UserBenefitsCalculator.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/userBenefits/UserBenefitsCalculator.java @@ -30,7 +30,7 @@ import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.gbl.Gbl; /** @@ -54,26 +54,26 @@ public class UserBenefitsCalculator { private final Set> stuckingAgents; public UserBenefitsCalculator(Config config, WelfareMeasure wm, boolean considerAllPlans) { - PlanCalcScoreConfigGroup pcs = config.planCalcScore(); + ScoringConfigGroup pcs = config.scoring(); this.betaLogit = pcs.getBrainExpBeta(); this.marginalUtlOfMoney = pcs.getMarginalUtilityOfMoney(); this.welfareMeasure = wm; this.considerAllPlans = considerAllPlans; - + logger.warn("There is no list of person IDs provided to be excluded from the user benefit calculation."); this.stuckingAgents = null; - + if (considerAllPlans) { logger.warn("All plans are considered for the calculation of user benefits. For an economic interpretation invalid plans (score <= 0.0 or score == null) should not be considered."); } else { logger.warn("Invalid plans that will not be considered for the calculation of user benefits are defined to have either a null score or a negative score."); } } - + public UserBenefitsCalculator(Config config, Set> stuckingAgents) { logger.info("Providing the IDs of agents that are stucking in the final iteration (selected plans)."); - PlanCalcScoreConfigGroup pcs = config.planCalcScore(); + ScoringConfigGroup pcs = config.scoring(); this.betaLogit = pcs.getBrainExpBeta(); this.marginalUtlOfMoney = pcs.getMarginalUtilityOfMoney(); this.stuckingAgents = stuckingAgents; @@ -81,7 +81,7 @@ public UserBenefitsCalculator(Config config, Set> stuckingAgents) { logger.info("A list of person IDs of stucking agents is provided. These persons will be excluded from the user benefit calculation." + "All other plans will be considered."); this.considerAllPlans = false; - + logger.info("The welfare measure is set to " + WelfareMeasure.SELECTED.toString() + "."); this.welfareMeasure = WelfareMeasure.SELECTED; } @@ -105,7 +105,7 @@ public double calculateUtility_utils(Population pop){ logger.info("Finished user benefits calculation..."); return sumOfUtility_utils; } - + public double calculateUtility_money(Population pop) { double sumOfUtility_money = 0.0; logger.info("Starting user benefits calculation..."); @@ -126,7 +126,7 @@ public double calculateUtilityOfPerson_utils(Person person) { double utilityOfPerson_utils = 0.0; double sumOfExpScore = 0.0; double bestScore = Double.NEGATIVE_INFINITY; - + if(this.welfareMeasure.equals(WelfareMeasure.LOGSUM)){ for(Plan plan : person.getPlans()){ boolean shouldBeConsidered; @@ -141,7 +141,7 @@ public double calculateUtilityOfPerson_utils(Person person) { /* Kais version: */ bestScore = getBestScore(person); double expScoreOfPlan = Math.exp(betaLogit * (plan.getScore() - bestScore)); - + sumOfExpScore += expScoreOfPlan; } else { // plan is not considered @@ -188,7 +188,7 @@ private boolean testScore(Plan plan, Id personId) { if(plan.getScore() == null){ nullScore++; if(nullScore <= maxWarnCnt) { - logger.warn("Score for person " + personId + " is " + plan.getScore() + logger.warn("Score for person " + personId + " is " + plan.getScore() + ". A null score cannot be used for utility calculation."); if(nullScore == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED + "\n"); } @@ -196,7 +196,7 @@ private boolean testScore(Plan plan, Id personId) { } else if(plan.getScore() <= 0.0){ minusScore++; if(minusScore <= maxWarnCnt) { - logger.warn("Score for person " + personId + " is " + plan.getScore() + logger.warn("Score for person " + personId + " is " + plan.getScore() + ". A score <= 0.0 cannot be used for utility calculation."); if(minusScore == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED + "\n"); } @@ -204,7 +204,7 @@ private boolean testScore(Plan plan, Id personId) { } else return true; } else { if (plan.getScore() == null){ - throw new RuntimeException("Score for person " + personId + " is " + plan.getScore() + throw new RuntimeException("Score for person " + personId + " is " + plan.getScore() + ". A null score cannot be used for utility calculation. This person has to be excluded."); } else { if (this.stuckingAgents.contains(personId)) { @@ -243,7 +243,7 @@ public int getPersonsWithoutValidPlanCnt() { return personsWithoutValidPlanScore; } } - + public int getInvalidPlans() { if (this.considerAllPlans) { logger.warn("All plans are forced to be considered. Asking for the number of invalid plans doesn't make sense."); @@ -253,11 +253,11 @@ public int getInvalidPlans() { return invalidPlans; } } - + public Map, Double> getPersonId2Utility() { return personId2Utility; } - + public Map, Double> getPersonId2MonetizedUtility() { return personId2MonetizedUtility; } diff --git a/contribs/vsp/src/main/java/playground/vsp/andreas/mzilske/bvg09/DataPrepare.java b/contribs/vsp/src/main/java/playground/vsp/andreas/mzilske/bvg09/DataPrepare.java index d380efe7262..37df0aa0811 100644 --- a/contribs/vsp/src/main/java/playground/vsp/andreas/mzilske/bvg09/DataPrepare.java +++ b/contribs/vsp/src/main/java/playground/vsp/andreas/mzilske/bvg09/DataPrepare.java @@ -53,7 +53,6 @@ import org.matsim.pt.UmlaufInterpolator; import org.matsim.pt.config.TransitConfigGroup; import org.matsim.pt.router.TransitRouterConfig; -import org.matsim.pt.router.TransitRouterImpl; import org.matsim.pt.transitSchedule.TransitScheduleWriterV1; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitScheduleWriter; @@ -156,11 +155,11 @@ protected void routePopulation() { new PopulationReader(this.scenario).readFile(InInputPlansFileWithXY2Links); DijkstraFactory dijkstraFactory = new DijkstraFactory(); - FreespeedTravelTimeAndDisutility timeCostCalculator = new FreespeedTravelTimeAndDisutility(this.scenario.getConfig().planCalcScore()); + FreespeedTravelTimeAndDisutility timeCostCalculator = new FreespeedTravelTimeAndDisutility(this.scenario.getConfig().scoring()); TransitConfigGroup transitConfig = new TransitConfigGroup(); - TransitRouterConfig transitRouterConfig = new TransitRouterConfig(this.scenario.getConfig().planCalcScore() - , this.scenario.getConfig().plansCalcRoute(), this.scenario.getConfig().transitRouter(), + TransitRouterConfig transitRouterConfig = new TransitRouterConfig(this.scenario.getConfig().scoring() + , this.scenario.getConfig().routing(), this.scenario.getConfig().transitRouter(), this.scenario.getConfig().vspExperimental()); log.warn( "please chack that this still does what you want. td, oct 2013"); @@ -184,44 +183,48 @@ protected void routePopulation() { } protected void visualizeRouterNetwork() { - - TransitRouterConfig transitRouterConfig = new TransitRouterConfig(this.scenario.getConfig().planCalcScore() - , this.scenario.getConfig().plansCalcRoute(), this.scenario.getConfig().transitRouter(), - this.scenario.getConfig().vspExperimental()); - - TransitRouterImpl router = new TransitRouterImpl(transitRouterConfig, this.scenario.getTransitSchedule() ); - Network routerNet = router.getTransitRouterNetwork(); - - log.info("create vis network"); - MutableScenario visScenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); - Network visNet = visScenario.getNetwork(); - - for (Node node : routerNet.getNodes().values()) { - visNet.getFactory().createNode(node.getId(), node.getCoord()); - visNet.addNode(node); - } - for (Link link : routerNet.getLinks().values()) { - Link l = visNet.getFactory().createLink(link.getId(), visNet.getNodes().get(link.getFromNode().getId()), visNet.getNodes().get(link.getToNode().getId())); - l.setLength(link.getLength()); - l.setFreespeed(link.getFreespeed()); - l.setCapacity(link.getCapacity()); - l.setNumberOfLanes(link.getNumberOfLanes()); - } - - log.info("write routerNet.xml"); - new NetworkWriter(visNet).write("visNet.xml"); - - log.info("start visualizer"); - EventsManager events = EventsUtils.createEventsManager(); - QSim otfVisQSim = new QSimBuilder(visScenario.getConfig()).useDefaults().build(visScenario, events); - OnTheFlyServer server = OTFVis.startServerAndRegisterWithQSim(visScenario.getConfig(), visScenario, events, otfVisQSim); - OTFClientLive.run(visScenario.getConfig(), server); - otfVisQSim.run(); + throw new RuntimeException("this works no longer, sorry."); + + /* I commented this code out, as it directly refers to the old and inefficient TransitRouterImpl + which got removed at the Code Sprint 2023 in Berlin. // mrieser, 2023oct09 + */ + +// TransitRouterConfig transitRouterConfig = new TransitRouterConfig(this.scenario.getConfig().planCalcScore() +// , this.scenario.getConfig().plansCalcRoute(), this.scenario.getConfig().transitRouter(), +// this.scenario.getConfig().vspExperimental()); +// TransitRouterImpl router = new TransitRouterImpl(transitRouterConfig, this.scenario.getTransitSchedule() ); +// Network routerNet = router.getTransitRouterNetwork(); +// +// log.info("create vis network"); +// MutableScenario visScenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); +// Network visNet = visScenario.getNetwork(); +// +// for (Node node : routerNet.getNodes().values()) { +// visNet.getFactory().createNode(node.getId(), node.getCoord()); +// visNet.addNode(node); +// } +// for (Link link : routerNet.getLinks().values()) { +// Link l = visNet.getFactory().createLink(link.getId(), visNet.getNodes().get(link.getFromNode().getId()), visNet.getNodes().get(link.getToNode().getId())); +// l.setLength(link.getLength()); +// l.setFreespeed(link.getFreespeed()); +// l.setCapacity(link.getCapacity()); +// l.setNumberOfLanes(link.getNumberOfLanes()); +// } +// +// log.info("write routerNet.xml"); +// new NetworkWriter(visNet).write("visNet.xml"); +// +// log.info("start visualizer"); +// EventsManager events = EventsUtils.createEventsManager(); +// QSim otfVisQSim = new QSimBuilder(visScenario.getConfig()).useDefaults().build(visScenario, events); +// OnTheFlyServer server = OTFVis.startServerAndRegisterWithQSim(visScenario.getConfig(), visScenario, events, otfVisQSim); +// OTFClientLive.run(visScenario.getConfig(), server); +// otfVisQSim.run(); } private void buildUmlaeufe() { Collection transitLines = this.scenario.getTransitSchedule().getTransitLines().values(); - GreedyUmlaufBuilderImpl greedyUmlaufBuilder = new GreedyUmlaufBuilderImpl(new UmlaufInterpolator(this.scenario.getNetwork(), this.scenario.getConfig().planCalcScore()), transitLines); + GreedyUmlaufBuilderImpl greedyUmlaufBuilder = new GreedyUmlaufBuilderImpl(new UmlaufInterpolator(this.scenario.getNetwork(), this.scenario.getConfig().scoring()), transitLines); Collection umlaeufe = greedyUmlaufBuilder.build(); VehiclesFactory vb = this.scenario.getTransitVehicles().getFactory(); diff --git a/contribs/vsp/src/main/java/playground/vsp/andreas/mzilske/pt/queuesim/GreedyUmlaufBuilderImpl.java b/contribs/vsp/src/main/java/playground/vsp/andreas/mzilske/pt/queuesim/GreedyUmlaufBuilderImpl.java index ed41e96f525..8302957adf5 100644 --- a/contribs/vsp/src/main/java/playground/vsp/andreas/mzilske/pt/queuesim/GreedyUmlaufBuilderImpl.java +++ b/contribs/vsp/src/main/java/playground/vsp/andreas/mzilske/pt/queuesim/GreedyUmlaufBuilderImpl.java @@ -30,12 +30,12 @@ public final class GreedyUmlaufBuilderImpl implements UmlaufBuilder { private static final Logger log = LogManager.getLogger( GreedyUmlaufBuilderImpl.class ); public class UmlaufKey { - + private final Id lineId; private final Id stopFacilityId; private final double lastArrivalTime; private final Id umlaufId; - + Id getUmlaufId() { return umlaufId; @@ -52,7 +52,7 @@ Id getUmlaufId() { public Id getLineId() { return lineId; } - + public Id getStopFacility() { return stopFacilityId; } @@ -60,12 +60,12 @@ public Id getStopFacility() { double getLastArrivalTime() { return lastArrivalTime; } - + @Override public String toString() { return stopFacilityId + " at " + lastArrivalTime + "(" + getLineId() + ")"; } - + } @@ -75,7 +75,7 @@ public String toString() { public int compare(UmlaufStueck o1, UmlaufStueck o2) { return Double.compare(o1.getDeparture().getDepartureTime(), o2.getDeparture().getDepartureTime()); } - + }; private static final Comparator umlaufKeyComparator = new Comparator() { @@ -86,7 +86,7 @@ public int compare(UmlaufKey o1, UmlaufKey o2) { if (c != 0) { return c; } else { - int cc = o1.getLineId().compareTo(o2.getLineId()); + int cc = o1.getLineId().compareTo(o2.getLineId()); if (cc != 0) { return cc; } else { @@ -99,9 +99,9 @@ public int compare(UmlaufKey o1, UmlaufKey o2) { } } } - + }; - + private final Collection transitLines; private final SortedMap umlaeufe = new TreeMap(umlaufKeyComparator); private ArrayList umlaufStuecke; @@ -115,14 +115,14 @@ public GreedyUmlaufBuilderImpl(UmlaufInterpolator interpolator, Collection build() { if (!canBuild()) { @@ -142,12 +142,12 @@ public Collection build() { } return umlaeufe.values(); } - + private static double getLastArrivalTime( Umlauf umlauf ) { TransitRouteStop previousStop = getLastStop(umlauf); double previousDepartureTime = getLastDeparture(umlauf).getDepartureTime(); double arrivalOffset = previousStop.getArrivalOffset().seconds(); - double previousArrivalTime = previousDepartureTime + arrivalOffset; + double previousArrivalTime = previousDepartureTime + arrivalOffset; return previousArrivalTime; } @@ -210,7 +210,7 @@ private void createUmlaufStuecke() { Collections.sort(this.umlaufStuecke, departureTimeComparator); } - - + + } diff --git a/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/BuildingEnergyAnalyzerMain.java b/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/BuildingEnergyAnalyzerMain.java index d53a3a33238..1731b3f5d68 100644 --- a/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/BuildingEnergyAnalyzerMain.java +++ b/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/BuildingEnergyAnalyzerMain.java @@ -24,7 +24,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryLogging; import org.matsim.core.gbl.Gbl; @@ -36,12 +36,12 @@ /** * @author droeder - * + * */ class BuildingEnergyAnalyzerMain { private static final Logger log = LogManager.getLogger(BuildingEnergyAnalyzerMain.class); - + private static final String[] ARGS = new String[]{ "E:\\VSP\\svn\\shared-svn\\studies\\droeder\\buildingEnergy\\runs\\", "E:\\VSP\\svn\\shared-svn\\studies\\droeder\\buildingEnergy\\runs\\outputCaseStudies\\", @@ -64,8 +64,8 @@ private BuildingEnergyAnalyzerMain() { } /** - * - * + * + * * @param args */ public static void main(String[] args) { @@ -100,7 +100,7 @@ public static void main(String[] args) { OutputDirectoryLogging.initLogging( new OutputDirectoryHierarchy(outputPath, BuildingEnergyAnalyzer.class.getSimpleName(), OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles, - ControlerConfigGroup.CompressionType.none)); + ControllerConfigGroup.CompressionType.none)); OutputDirectoryLogging.catchLogEntries(); // dump input-parameters to log log.info("running class: " + System.getProperty("sun.java.command")); @@ -135,16 +135,16 @@ public static void main(String[] args) { Gbl.printElapsedTime(); log.info("finished."); } - + private static class OfficeEnergyConsumptionRuleImpl implements BuildingEnergyConsumptionRule{ - + private double additional; private double baseLoad; private double td; private double someCoefficient; /** - * + * * @param td, duration timeslice [s] * @param baseLoadPerPerson [kW] * @param additionalLoadPerPerson [kW] @@ -155,7 +155,7 @@ private static class OfficeEnergyConsumptionRuleImpl implements BuildingEnergyCo this.additional = additionalLoadPerPerson; this.someCoefficient = someCoefficient; } - + @Override public double getEnergyConsumption_kWh(double maxSize, double currentOccupancy) { if(currentOccupancy > maxSize) throw new RuntimeException("more persons on the link than expected"); @@ -164,17 +164,17 @@ public double getEnergyConsumption_kWh(double maxSize, double currentOccupancy) double additionalLoad = this.additional * maxSize; return (td / 3600. * (baseload + additionalLoad * (1 - Math.exp(-1.0 * currentOccupancy / maxSize * someCoefficient)))); } - + } - + private static class HomeEnergyConsumptionRuleImpl implements BuildingEnergyConsumptionRule{ - + private double td; private double baseLoad; private double additional; /** - * + * * @param td * @param baseLoadPerPerson * @param additionalLoadPerPerson @@ -189,7 +189,7 @@ private static class HomeEnergyConsumptionRuleImpl implements BuildingEnergyCons public double getEnergyConsumption_kWh(double maxSize, double currentOccupancy) { return (td/3600. * (maxSize * baseLoad + currentOccupancy * additional)); } - + } } diff --git a/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/BuildingEnergyRunnerMain.java b/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/BuildingEnergyRunnerMain.java index 28d2b93ecd0..982a441a790 100644 --- a/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/BuildingEnergyRunnerMain.java +++ b/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/BuildingEnergyRunnerMain.java @@ -57,7 +57,7 @@ public abstract class BuildingEnergyRunnerMain { private static final int LENGTH = 2; /** - * + * * @param args {configfile agents2exclude.csv} */ public static void main(String[] args) { @@ -72,7 +72,7 @@ public static void main(String[] args) { System.exit(-1); } OutputDirectoryLogging.catchLogEntries(); - + log.info("running " + BuildingEnergyRunnerMain.class.getName() ); String configFilename = args[0]; String agents2exclude = args[1]; @@ -84,14 +84,14 @@ public static void main(String[] args) { Scenario sc = loadScenario(c, agents2exclude); // run Controler controler = new Controler(sc); - controler.getConfig().controler().setOverwriteFileSetting( + controler.getConfig().controller().setOverwriteFileSetting( overwrite ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists ); controler.addControlerListener(new MyControlerListener(c, sc.getNetwork())); controler.run(); } - + /** * @param configFilename * @param agents2exclude @@ -139,33 +139,33 @@ private static Set> getAgents2Exclude(String agents2exclude) { // static class which plug the analysis to the services and generates some more output (distance- & tt-shares) private static class MyControlerListener implements IterationStartsListener, IterationEndsListener{ - + private SimpleTripAnalyzer analyzer; - + MyControlerListener(Config c, Network net){ analyzer = new SimpleTripAnalyzer(c, net, null); } - + @Override public void notifyIterationStarts(IterationStartsEvent event) { - if(event.getIteration() == event.getServices().getConfig().controler().getLastIteration()){ + if(event.getIteration() == event.getServices().getConfig().controller().getLastIteration()){ analyzer.reset(event.getIteration()); event.getServices().getEvents().addHandler(analyzer); } } - + @Override public void notifyIterationEnds(IterationEndsEvent event) { - if(event.getIteration() == event.getServices().getConfig().controler().getLastIteration()){ + if(event.getIteration() == event.getServices().getConfig().controller().getLastIteration()){ analyzer.run(event.getServices().getScenario().getPopulation()); String path = event.getServices().getControlerIO().getOutputPath() + System.getProperty("file.separator"); - String prefix = event.getServices().getConfig().controler().getRunId() + "."; + String prefix = event.getServices().getConfig().controller().getRunId() + "."; analyzer.dumpData(path, prefix); calcWriteDistanceDistribution(analyzer.getTraveller(), path + prefix + "distanceShare.csv.gz"); calcAndWriteTTDistribution(analyzer.getTraveller(), path + prefix + "ttShare.csv.gz"); } } - + /** * @param traveller */ @@ -194,7 +194,7 @@ private void calcAndWriteTTDistribution(Map, Traveller> traveller, St } dumpData(map, file); } - + /** * @param traveller */ @@ -223,7 +223,7 @@ private void calcWriteDistanceDistribution(Map, Traveller> traveller, } dumpData(map, file); } - + /** * @param map * @param file @@ -249,7 +249,7 @@ private void dumpData(Map> map, String file) { e.printStackTrace(); } } - + /** * @param temp * @param dist @@ -262,9 +262,9 @@ private void increase(Map temp, Double value) { } } } - - - + + + private Map getColumn(Map> map, List distribution, String mode){ if(map.containsKey(mode)) return map.get(mode); Map temp = new LinkedHashMap(); @@ -274,9 +274,9 @@ private Map getColumn(Map> map, L map.put(mode, temp); return temp; } - + } - + } diff --git a/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/linkOccupancy/LinkActivityCalculationFromEventsMain.java b/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/linkOccupancy/LinkActivityCalculationFromEventsMain.java index f6aa672471a..cb70d46affb 100644 --- a/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/linkOccupancy/LinkActivityCalculationFromEventsMain.java +++ b/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/linkOccupancy/LinkActivityCalculationFromEventsMain.java @@ -38,7 +38,7 @@ import org.matsim.api.core.v01.population.Population; 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.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryLogging; import org.matsim.core.events.EventsUtils; @@ -54,7 +54,7 @@ /** - * Simple main-routine that parse an eventsfile, using {@link LinkActivityOccupancyCounter}. + * Simple main-routine that parse an eventsfile, using {@link LinkActivityOccupancyCounter}. * The generated data is written to csv-tables. * @author droeder * @@ -68,7 +68,7 @@ private LinkActivityCalculationFromEventsMain() { private static final String DIR = "E:\\VSP\\svn\\shared-svn\\studies\\droeder\\buildingEnergy\\runs\\"; private static final String RUN = "2kW.15"; - + private static String[] ARGS = new String[]{ DIR + RUN + "\\" + RUN + ".output_network.xml.gz", DIR + RUN + "\\ITERS\\it.1000\\" + RUN + ".1000.plans.xml.gz", @@ -78,15 +78,15 @@ private LinkActivityCalculationFromEventsMain() { "86400", RUN }; - + private static Counter he= new Counter("home events # "); private static Counter we = new Counter("work events # "); private static Counter hp= new Counter("home plans # "); private static Counter wp = new Counter("work plans # "); - + private static final String PREFIX = "activityCountOnLinks"; - - + + /** * @param args */ @@ -105,7 +105,7 @@ public static void main(String[] args) { //catch logEntries OutputDirectoryLogging.initLogging(new OutputDirectoryHierarchy(outputPath, runId + "." + PREFIX, OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles, - ControlerConfigGroup.CompressionType.none)); + ControllerConfigGroup.CompressionType.none)); OutputDirectoryLogging.catchLogEntries(); Gbl.enableThreadCpuTimeMeasurement(); // dump input-parameters @@ -139,10 +139,10 @@ public static void main(String[] args) { } /** - * @param eventsFile - * @param work - * @param home - * + * @param eventsFile + * @param work + * @param home + * */ private static void parseEvents(Map home, Map work, String eventsFile) { log.info("parsing events."); @@ -153,14 +153,14 @@ private static void parseEvents(Map home, for(LinkActivityOccupancyCounter v: work.values()){ manager.addHandler(v); } - + manager.addHandler(new ActivityStartEventHandler() { - + @Override public void reset(int iteration) { - + } - + @Override public void handleEvent(ActivityStartEvent event) { if(event.getActType().equals("home")) he.incCounter(); @@ -168,7 +168,7 @@ public void handleEvent(ActivityStartEvent event) { } }); new MatsimEventsReader(manager).readFile(eventsFile); - log.info("finished (parsing events)."); + log.info("finished (parsing events)."); } /** @@ -199,7 +199,7 @@ private static Scenario prepareScenario(String plansFile, String networkFile) { // final Population population = (Population) sc.getPopulation(); StreamingPopulationReader reader = new StreamingPopulationReader( sc ) ; reader.addAlgorithm(new PersonAlgorithm() { - + @Override public void run(Person person) { for(int i = 1; i < person.getSelectedPlan().getPlanElements().size(); i++){ diff --git a/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/linkOccupancy/RunEquil.java b/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/linkOccupancy/RunEquil.java index 18a2268e3d1..965ae44b56b 100644 --- a/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/linkOccupancy/RunEquil.java +++ b/contribs/vsp/src/main/java/playground/vsp/buildingEnergy/linkOccupancy/RunEquil.java @@ -14,7 +14,7 @@ public class RunEquil { public static void main(String[] args) { String configFile = "examples/equil/config.xml"; Config config = ConfigUtils.loadConfig(configFile); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); Scenario scenario = ScenarioUtils.loadScenario(config); Controler controler = new Controler(scenario); @@ -31,7 +31,7 @@ public static void main(String[] args) { // People work only 30 minutes in Equil, so the interval for work-time is 6:01 to 6:30 final LinkActivityOccupancyCounter atWork = new LinkActivityOccupancyCounter(scenario.getPopulation(), 6*60*60 + 1, 6*60*60 + 30 * 60); controler.getEvents().addHandler(atWork); - + // This one briefly listens in when everyone is already at home again final LinkActivityOccupancyCounter nextNight = new LinkActivityOccupancyCounter(scenario.getPopulation(), 13*60*60 + 45 * 60, 13*60*60 + 47 * 60); controler.getEvents().addHandler(nextNight); @@ -39,7 +39,7 @@ public static void main(String[] args) { // During this window, most people are already home, a few are still working, and one person is actually seen both at work and at home. final LinkActivityOccupancyCounter middle = new LinkActivityOccupancyCounter(scenario.getPopulation(), 27810, 31440); controler.getEvents().addHandler(middle); - + // This one listens all day final LinkActivityOccupancyCounter allDay = new LinkActivityOccupancyCounter(scenario.getPopulation()); controler.getEvents().addHandler(allDay); @@ -69,7 +69,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { System.out.println("---"); } }); - controler.getConfig().controler().setOverwriteFileSetting( + controler.getConfig().controller().setOverwriteFileSetting( true ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists ); diff --git a/contribs/vsp/src/main/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsBuilder.java b/contribs/vsp/src/main/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsBuilder.java index 8ddbcd6641d..513423ed0c6 100644 --- a/contribs/vsp/src/main/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsBuilder.java +++ b/contribs/vsp/src/main/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsBuilder.java @@ -40,7 +40,7 @@ AnalyticalCalibrator> build() { validateTimeBinSize(cadytsConfig.getTimeBinSize()); AnalyticalCalibrator> calibrator = new AnalyticalCalibrator<>( - config.controler().getOutputDirectory() + "/cadyts" + MARGINALS + ".log", + config.controller().getOutputDirectory() + "/cadyts" + MARGINALS + ".log", MatsimRandom.getLocalInstance().nextLong(), cadytsConfig.getTimeBinSize() ); @@ -51,7 +51,7 @@ AnalyticalCalibrator> build() { calibrator.setFreezeIteration(cadytsConfig.getFreezeIteration()); calibrator.setPreparatoryIterations(cadytsConfig.getPreparatoryIterations()); calibrator.setVarianceScale(cadytsConfig.getVarianceScale()); - calibrator.setStatisticsFile(config.controler().getOutputDirectory() + "/calibration-stats"+MARGINALS+".txt"); + calibrator.setStatisticsFile(config.controller().getOutputDirectory() + "/calibration-stats"+MARGINALS+".txt"); calibrator.setBruteForce(cadytsConfig.useBruteForce()); // I don't think this has an influence on any of the variants we are using. (Has an influence only when plan choice is left diff --git a/contribs/vsp/src/main/java/playground/vsp/cadyts/multiModeCadyts/MultiModeCountsControlerListener.java b/contribs/vsp/src/main/java/playground/vsp/cadyts/multiModeCadyts/MultiModeCountsControlerListener.java index 4d7e7407fc9..3cb374b5048 100644 --- a/contribs/vsp/src/main/java/playground/vsp/cadyts/multiModeCadyts/MultiModeCountsControlerListener.java +++ b/contribs/vsp/src/main/java/playground/vsp/cadyts/multiModeCadyts/MultiModeCountsControlerListener.java @@ -30,12 +30,11 @@ import jakarta.inject.Inject; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.analysis.IterationStopWatch; import org.matsim.analysis.VolumesAnalyzer; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.CountsConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -57,7 +56,7 @@ public class MultiModeCountsControlerListener implements StartupListener, Iterat */ public static final String OPERATION_COMPARECOUNTS = "compare with counts"; - private final ControlerConfigGroup controlerConfigGroup; + private final ControllerConfigGroup controllerConfigGroup; private final CountsConfigGroup config; // useful to get the link ids of counting stations and other infor for averaging private final Set analyzedModes; private final VolumesAnalyzer volumesAnalyzer; @@ -71,8 +70,8 @@ public class MultiModeCountsControlerListener implements StartupListener, Iterat private int iterationsUsed = 0; @Inject - private MultiModeCountsControlerListener(QSimConfigGroup qsimConfigGroup, ControlerConfigGroup controlerConfigGroup, CountsConfigGroup countsConfigGroup, VolumesAnalyzer volumesAnalyzer, IterationStopWatch iterationStopwatch, OutputDirectoryHierarchy controlerIO) { - this.controlerConfigGroup = controlerConfigGroup; + private MultiModeCountsControlerListener(QSimConfigGroup qsimConfigGroup, ControllerConfigGroup controllerConfigGroup, CountsConfigGroup countsConfigGroup, VolumesAnalyzer volumesAnalyzer, IterationStopWatch iterationStopwatch, OutputDirectoryHierarchy controlerIO) { + this.controllerConfigGroup = controllerConfigGroup; this.config = countsConfigGroup; this.volumesAnalyzer = volumesAnalyzer; this.analyzedModes = CollectionUtils.stringToSet(this.config.getAnalyzedModes()); @@ -105,13 +104,13 @@ public void notifyStartup(final StartupEvent controlerStartupEvent) { public void notifyIterationEnds(final IterationEndsEvent event) { if(counts==null) { } - else if ( event.getIteration() == controlerConfigGroup.getFirstIteration()){ + else if ( event.getIteration() == controllerConfigGroup.getFirstIteration()){ // write the data for first iteration too addVolumes(volumesAnalyzer); writeData(event, this.linkStats); reset(); } else if ( this.config.getWriteCountsInterval() > 0 ) { - if (useVolumesOfIteration(event.getIteration(), controlerConfigGroup.getFirstIteration())) { + if (useVolumesOfIteration(event.getIteration(), controllerConfigGroup.getFirstIteration())) { addVolumes(volumesAnalyzer); } diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/RunSimpleExample.java b/contribs/vsp/src/main/java/playground/vsp/congestion/RunSimpleExample.java index e8a973e1c77..20eab2ed05b 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/RunSimpleExample.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/RunSimpleExample.java @@ -19,7 +19,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion; @@ -54,7 +54,7 @@ public static void main(String[] args) throws IOException { if (args.length > 0) { - configFile = args[0]; + configFile = args[0]; log.info("first argument (config file): "+ configFile); } else { @@ -70,10 +70,10 @@ private void run() { Controler controler = new Controler(configFile); TollHandler tollHandler = new TollHandler(controler.getScenario()); - + final CongestionTollTimeDistanceTravelDisutilityFactory tollDisutilityCalculatorFactory = new CongestionTollTimeDistanceTravelDisutilityFactory( new RandomizingTimeDistanceTravelDisutilityFactory(TransportMode.car, controler.getConfig()), - tollHandler, controler.getConfig().planCalcScore()); + tollHandler, controler.getConfig().scoring()); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -86,7 +86,7 @@ public void install() { controler.addControlerListener(new MarginalCongestionPricingContolerListener(controler.getScenario(), tollHandler, new CongestionHandlerImplV3(controler.getEvents(), controler.getScenario()))); controler.addOverridingModule(new OTFVisFileWriterModule()); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); controler.run(); } diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/analysis/CongestionAnalysisEventHandler.java b/contribs/vsp/src/main/java/playground/vsp/congestion/analysis/CongestionAnalysisEventHandler.java index f5eba3c57a6..0bd39d2ca33 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/analysis/CongestionAnalysisEventHandler.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/analysis/CongestionAnalysisEventHandler.java @@ -19,7 +19,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.analysis; @@ -55,39 +55,39 @@ import playground.vsp.congestion.handlers.CongestionEventHandler; /** - * + * * @author ikaddoura , lkroeger * */ public class CongestionAnalysisEventHandler implements PersonMoneyEventHandler, TransitDriverStartsEventHandler , ActivityEndEventHandler , PersonDepartureEventHandler , LinkEnterEventHandler, PersonEntersVehicleEventHandler , PersonLeavesVehicleEventHandler , CongestionEventHandler { private final static Logger log = LogManager.getLogger(CongestionAnalysisEventHandler.class); private final double vtts_car; - + // This analysis uses either money events or congestion events. private final boolean useMoneyEvents; - + private Map,Integer> personId2actualTripNumber = new HashMap, Integer>(); private Map,Map> personId2tripNumber2legMode = new HashMap,Map>(); - + private Map,Map> personId2tripNumber2departureTime = new HashMap, Map>(); private Map,Map> personId2tripNumber2tripDistance = new HashMap, Map>(); private Map,Map> personId2tripNumber2amount = new HashMap, Map>(); private Map,Double> driverId2totalDistance = new HashMap,Double>(); - + private Map, Double> causingAgentId2amountSum = new HashMap , Double>(); private Map, Double> affectedAgentId2amountSum = new HashMap , Double>(); private Set> persons = new HashSet>(); - + // for pt-distance calculation private Map,Double> personId2distanceEnterValue = new HashMap,Double>(); - + private List> ptDrivers = new ArrayList>(); private Scenario scenario; - + private double distance = 500.; // TODO: set dynamically! private double maxDistance = 40 * distance; // TODO: set dynamically! private double timeBinSize = 900.0; // TODO: set dynamically! - + public CongestionAnalysisEventHandler(Scenario scenario, boolean useMoneyEvents) { this.scenario = scenario; this.useMoneyEvents = useMoneyEvents; @@ -95,7 +95,7 @@ public CongestionAnalysisEventHandler(Scenario scenario, boolean useMoneyEvents) if (useMoneyEvents) { log.warn("Money events may be thrown later than the congestion events... May result in a wrong interpretation of the results. Better use directly the congestion events for analysis."); } - this.vtts_car = (this.scenario.getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() - this.scenario.getConfig().planCalcScore().getPerforming_utils_hr()) / this.scenario.getConfig().planCalcScore().getMarginalUtilityOfMoney(); + this.vtts_car = (this.scenario.getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() - this.scenario.getConfig().scoring().getPerforming_utils_hr()) / this.scenario.getConfig().scoring().getMarginalUtilityOfMoney(); log.info("Anlayzing the congestion events during the simulation. Assuming the following VTTS (equal for all agents): " + vtts_car); } @@ -116,16 +116,16 @@ public void reset(int iteration) { @Override public void handleEvent(CongestionEvent event) { - + if (useMoneyEvents == false){ - + // trip-based analysis double amount = event.getDelay() / 3600 * this.vtts_car; double emergenceTime = event.getEmergenceTime(); int tripNumber = 0; double maxDepTime = 0.; Map tripNumber2departureTime = personId2tripNumber2departureTime.get(event.getCausingAgentId()); - + for(int tripNr : tripNumber2departureTime.keySet()) { if(emergenceTime >= tripNumber2departureTime.get(tripNr)) { if (tripNumber2departureTime.get(tripNr) >= maxDepTime) { @@ -133,13 +133,13 @@ public void handleEvent(CongestionEvent event) { } } } - + double amountBefore = personId2tripNumber2amount.get(event.getCausingAgentId()).get(tripNumber); double updatedAmount = amountBefore + amount; Map tripNumber2amount = personId2tripNumber2amount.get(event.getCausingAgentId()); tripNumber2amount.put(tripNumber, updatedAmount); personId2tripNumber2amount.put(event.getCausingAgentId(), tripNumber2amount); - + // person-based analysis - causing agent if (this.causingAgentId2amountSum.get(event.getCausingAgentId()) == null) { this.causingAgentId2amountSum.put(event.getCausingAgentId(), amount); @@ -148,7 +148,7 @@ public void handleEvent(CongestionEvent event) { double amountNew = amountSoFar + amount; this.causingAgentId2amountSum.put(event.getCausingAgentId(), amountNew); } - + // person-based analysis - affected agent if (this.affectedAgentId2amountSum.get(event.getAffectedAgentId()) == null) { this.affectedAgentId2amountSum.put(event.getAffectedAgentId(), amount); @@ -159,19 +159,19 @@ public void handleEvent(CongestionEvent event) { } } } - + @Override public void handleEvent(PersonMoneyEvent event) { - + if (useMoneyEvents == true) { - + // trip-based analysis double amount = event.getAmount(); double eventTime = event.getTime(); int tripNumber = 0; double maxDepTime = 0.; Map tripNumber2departureTime = personId2tripNumber2departureTime.get(event.getPersonId()); - + for(int tripNr : tripNumber2departureTime.keySet()) { if(eventTime >= tripNumber2departureTime.get(tripNr)) { if (tripNumber2departureTime.get(tripNr) >= maxDepTime) { @@ -179,13 +179,13 @@ public void handleEvent(PersonMoneyEvent event) { } } } - + double amountBefore = personId2tripNumber2amount.get(event.getPersonId()).get(tripNumber); double updatedAmount = amountBefore + amount; Map tripNumber2amount = personId2tripNumber2amount.get(event.getPersonId()); tripNumber2amount.put(tripNumber, updatedAmount); personId2tripNumber2amount.put(event.getPersonId(), tripNumber2amount); - + // person-based analysis - causing agent if (this.causingAgentId2amountSum.get(event.getPersonId()) == null) { this.causingAgentId2amountSum.put(event.getPersonId(), amount); @@ -194,10 +194,10 @@ public void handleEvent(PersonMoneyEvent event) { double amountNew = amountSoFar + amount; this.causingAgentId2amountSum.put(event.getPersonId(), amountNew); } - + } } - + @Override public void handleEvent(LinkEnterEvent event) { double linkLength = this.scenario.getNetwork().getLinks().get(event.getLinkId()).getLength(); @@ -217,9 +217,9 @@ public void handleEvent(LinkEnterEvent event) { personId2tripNumber2tripDistance.put(Id.createPersonId(event.getVehicleId()), tripNumber2tripDistance); } } - + // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - + public Map,List> getPersonId2listOfDepartureTimes(String mode) { Map,List> personId2listOfDepartureTimes = new HashMap, List>(); for(Id personId: personId2tripNumber2departureTime.keySet()){ @@ -235,7 +235,7 @@ public Map,List> getPersonId2listOfDepartureTimes(String mode } return personId2listOfDepartureTimes; } - + public Map,List> getPersonId2listOfDistances(String mode) { Map,List> personId2listOfDistances = new HashMap, List>(); for(Id personId: personId2tripNumber2tripDistance.keySet()){ @@ -251,7 +251,7 @@ public Map,List> getPersonId2listOfDistances(String mode) { } return personId2listOfDistances; } - + public Map,List> getPersonId2listOfAmounts(String mode) { Map,List> personId2listOfAmounts = new HashMap, List>(); for(Id personId: personId2tripNumber2amount.keySet()){ @@ -267,7 +267,7 @@ public Map,List> getPersonId2listOfAmounts(String mode) { } return personId2listOfAmounts; } - + public Map getAvgAmountPerTripDepartureTime(String mode) { Map tripDepTime2avgFare = new HashMap(); @@ -275,15 +275,15 @@ public Map getAvgAmountPerTripDepartureTime(String mode) { double startTime = this.timeBinSize; double periodLength = this.timeBinSize; double endTime = 30. * 3600; - + for (double time = startTime; time <= endTime; time = time + periodLength){ List fares = new ArrayList(); tripDepTime2fares.put(time, fares); } - + Map counter2allDepartureTimesAndAmounts = new HashMap(); int i = 0; - + for(Id personId : personId2tripNumber2departureTime.keySet()){ for(int tripNumber : personId2tripNumber2departureTime.get(personId).keySet()){ if(personId2tripNumber2legMode.get(personId).get(tripNumber).toString().equals(mode)){ @@ -291,14 +291,14 @@ public Map getAvgAmountPerTripDepartureTime(String mode) { double belongingAmount = personId2tripNumber2amount.get(personId).get(tripNumber); double[] departureTimeAndAmount = new double[2]; departureTimeAndAmount[0] = departureTime; - departureTimeAndAmount[1] = belongingAmount; + departureTimeAndAmount[1] = belongingAmount; counter2allDepartureTimesAndAmounts.put(i, departureTimeAndAmount); i++; }else{ } } } - + for (Double time : tripDepTime2fares.keySet()){ for (int counter : counter2allDepartureTimesAndAmounts.keySet()){ if (counter2allDepartureTimesAndAmounts.get(counter)[0] < time && counter2allDepartureTimesAndAmounts.get(counter)[0] >= (time - periodLength)) { @@ -308,19 +308,19 @@ public Map getAvgAmountPerTripDepartureTime(String mode) { } } } - + for (Double time : tripDepTime2fares.keySet()){ double amountSum = 0.; double counter = 0.; for (Double amount : tripDepTime2fares.get(time)){ if (amount == null){ - + } else { amountSum = amountSum + amount; counter++; } } - + double avgFare = 0.; if (counter!=0.){ avgFare = (-1) * amountSum / counter; @@ -329,7 +329,7 @@ public Map getAvgAmountPerTripDepartureTime(String mode) { } return tripDepTime2avgFare; } - + public Map getAvgAmountPerTripDistance(String mode) { Map tripDistance2avgAmount = new HashMap(); @@ -337,15 +337,15 @@ public Map getAvgAmountPerTripDistance(String mode) { double startDistance = this.distance; double groupsize = this.distance; double endDistance = this.maxDistance; - + for (double distance = startDistance; distance <= endDistance; distance = distance + groupsize){ List amounts = new ArrayList(); tripDistance2amount.put(distance, amounts); } - + Map counter2allDistancesAndAmounts = new HashMap(); int i = 0; - + for(Id personId : personId2tripNumber2tripDistance.keySet()){ for(int tripNumber : personId2tripNumber2tripDistance.get(personId).keySet()){ if(personId2tripNumber2legMode.get(personId).get(tripNumber).toString().equals(mode)){ @@ -353,13 +353,13 @@ public Map getAvgAmountPerTripDistance(String mode) { double belongingAmount = personId2tripNumber2amount.get(personId).get(tripNumber); double[] tripDistanceAndAmount = new double[2]; tripDistanceAndAmount[0] = tripDistance; - tripDistanceAndAmount[1] = belongingAmount; + tripDistanceAndAmount[1] = belongingAmount; counter2allDistancesAndAmounts.put(i, tripDistanceAndAmount); i++; } } } - + for (Double dist : tripDistance2amount.keySet()){ for (int counter : counter2allDistancesAndAmounts.keySet()){ if (counter2allDistancesAndAmounts.get(counter)[0] < dist && counter2allDistancesAndAmounts.get(counter)[0] >= (dist - groupsize)) { @@ -369,19 +369,19 @@ public Map getAvgAmountPerTripDistance(String mode) { } } } - + for (Double dist : tripDistance2amount.keySet()){ double amountSum = 0.; double counter = 0.; for (Double amount : tripDistance2amount.get(dist)){ if (amount == null){ - + } else { amountSum = amountSum + amount; counter++; } } - + double avgAmount = 0.; if (counter!=0.){ avgAmount = (-1) * amountSum / counter; @@ -393,13 +393,13 @@ public Map getAvgAmountPerTripDistance(String mode) { @Override public void handleEvent(ActivityEndEvent event) { - + if (this.persons.contains(event.getPersonId())){ // do nothing } else { this.persons.add(event.getPersonId()); } - + // A transit driver should not practice any activity, // otherwise the code has to be adapted here. if(ptDrivers.contains(event.getPersonId())){ @@ -417,11 +417,11 @@ public void handleEvent(ActivityEndEvent event) { Map tripNumber2tripDistance = personId2tripNumber2tripDistance.get(event.getPersonId()); tripNumber2tripDistance.put(personId2actualTripNumber.get(event.getPersonId()), 0.0); personId2tripNumber2tripDistance.put(event.getPersonId(), tripNumber2tripDistance); - + Map tripNumber2amount = personId2tripNumber2amount.get(event.getPersonId()); tripNumber2amount.put(personId2actualTripNumber.get(event.getPersonId()), 0.0); personId2tripNumber2amount.put(event.getPersonId(), tripNumber2amount); - + } else { // The trip which starts immediately is the first trip of the person personId2actualTripNumber.put(event.getPersonId(), 1); @@ -431,14 +431,14 @@ public void handleEvent(ActivityEndEvent event) { Map tripNumber2tripDistance = new HashMap(); tripNumber2tripDistance.put(1, 0.0); personId2tripNumber2tripDistance.put(event.getPersonId(), tripNumber2tripDistance); - + Map tripNumber2amount = new HashMap(); tripNumber2amount.put(1, 0.0); personId2tripNumber2amount.put(event.getPersonId(), tripNumber2amount); } - } + } } - + @Override public void handleEvent(PersonDepartureEvent event) { if(ptDrivers.contains(event.getPersonId())){ @@ -452,7 +452,7 @@ public void handleEvent(PersonDepartureEvent event) { Map tripNumber2legMode = personId2tripNumber2legMode.get(event.getPersonId()); if(tripNumber2legMode.containsKey(tripNumber)){ // legMode already listed, possible for pt trips - if(tripNumber2legMode.get(tripNumber).toString().equals("pt")){ + if(tripNumber2legMode.get(tripNumber).toString().equals("pt")){ } else{ throw new RuntimeException("A leg mode has already been listed."); } @@ -479,7 +479,7 @@ public void handleEvent(PersonDepartureEvent event) { } } } - + @Override public void handleEvent(TransitDriverStartsEvent event) { if (ptDrivers.contains(event.getDriverId())) { @@ -489,7 +489,7 @@ public void handleEvent(TransitDriverStartsEvent event) { driverId2totalDistance.put(Id.createPersonId(event.getVehicleId()),0.0); } } - + @Override public void handleEvent(PersonLeavesVehicleEvent event) { if(ptDrivers.contains(event.getPersonId())){ @@ -500,11 +500,11 @@ public void handleEvent(PersonLeavesVehicleEvent event) { if((tripNumber2legMode.get(tripNumber)).equals(TransportMode.car)){ // car drivers not considered here } else { - double distanceTravelled = (driverId2totalDistance.get(event.getVehicleId()) - personId2distanceEnterValue.get(event.getPersonId())); - + double distanceTravelled = (driverId2totalDistance.get(event.getVehicleId()) - personId2distanceEnterValue.get(event.getPersonId())); + Map tripNumber2distance = personId2tripNumber2tripDistance.get(event.getPersonId()); tripNumber2distance.put(tripNumber, tripNumber2distance.get(tripNumber) + distanceTravelled); - + personId2distanceEnterValue.remove(event.getPersonId()); } } @@ -528,14 +528,14 @@ public void handleEvent(PersonEntersVehicleEvent event) { public Map, Double> getCausingAgentId2amountSum() { return causingAgentId2amountSum; } - + public Map, Double> getAffectedAgentId2amountSum() { return affectedAgentId2amountSum; } public Map, Double> getCausingAgentId2amountSumAllAgents() { Map, Double> personId2amountSumAllAgents = new HashMap, Double>(); - + List> personIds = new ArrayList>(); if (this.scenario.getPopulation().getPersons().isEmpty()) { log.warn("Scenario does not contain a Population. Using the person IDs from the events file for the person-based analysis (total: " + personIds.size() +")."); @@ -544,7 +544,7 @@ public Map, Double> getCausingAgentId2amountSumAllAgents() { log.info("Scenario contains a Population. Using the person IDs from the population for the person-based analysis."); personIds.addAll(this.scenario.getPopulation().getPersons().keySet()); } - + for (Id id : personIds) { double amountSum = 0.; if (this.causingAgentId2amountSum.get(id) == null) { @@ -556,13 +556,13 @@ public Map, Double> getCausingAgentId2amountSumAllAgents() { } return personId2amountSumAllAgents; } - + public Map, Double> getAffectedAgentId2amountSumAllAgents() { Map, Double> personId2amountSumAllAgents = new HashMap, Double>(); - + if (this.affectedAgentId2amountSum.isEmpty()) { - log.warn("There is no info re the affected agents. This info is only avalable when analyzing congestion events and not the money events."); - + log.warn("There is no info re the affected agents. This info is only avalable when analyzing congestion events and not the money events."); + } else { List> personIds = new ArrayList>(); if (this.scenario.getPopulation().getPersons().isEmpty()) { @@ -572,7 +572,7 @@ public Map, Double> getAffectedAgentId2amountSumAllAgents() { log.info("Scenario contains a Population. Using the person IDs from the population for the person-based analysis."); personIds.addAll(this.scenario.getPopulation().getPersons().keySet()); } - + for (Id id : personIds) { double amountSum = 0.; if (this.affectedAgentId2amountSum.get(id) == null) { diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/analysis/CongestionEventsWriter.java b/contribs/vsp/src/main/java/playground/vsp/congestion/analysis/CongestionEventsWriter.java index 993816f4cea..8c2d421ab91 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/analysis/CongestionEventsWriter.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/analysis/CongestionEventsWriter.java @@ -38,63 +38,63 @@ /** * (1) Computes marginal congestion events based on a standard events file. * (2) Computes agent money events based on these marginal congestion events. - * + * * @author ikaddoura * */ public class CongestionEventsWriter { private static final Logger log = LogManager.getLogger(CongestionEventsWriter.class); - + static String runDirectory; - + public static void main(String[] args) { - + if (args.length > 0) { - - runDirectory = args[0]; + + runDirectory = args[0]; log.info("runDirectory: " + runDirectory); - + } else { runDirectory = "../../runs-svn/berlin_internalizationCar2/output/baseCase_2/"; } - + CongestionEventsWriter congestionEventsWriter = new CongestionEventsWriter(); congestionEventsWriter.run(); } private void run() { - + log.info("Loading scenario..."); Config config = ConfigUtils.loadConfig(runDirectory + "output_config.xml.gz"); config.network().setInputFile(runDirectory + "output_network.xml.gz"); config.plans().setInputFile(runDirectory + "output_plans.xml.gz"); MutableScenario scenario = (MutableScenario) ScenarioUtils.loadScenario(config); log.info("Loading scenario... Done."); - - String outputDirectory = runDirectory + "analysis_it." + config.controler().getLastIteration() + "/"; + + String outputDirectory = runDirectory + "analysis_it." + config.controller().getLastIteration() + "/"; File file = new File(outputDirectory); file.mkdirs(); - + EventsManager events = EventsUtils.createEventsManager(); - - EventWriterXML eventWriter = new EventWriterXML(outputDirectory + config.controler().getLastIteration() + ".events_ExternalCongestionCost_Offline.xml.gz"); + + EventWriterXML eventWriter = new EventWriterXML(outputDirectory + config.controller().getLastIteration() + ".events_ExternalCongestionCost_Offline.xml.gz"); CongestionHandlerImplV3 congestionHandler = new CongestionHandlerImplV3(events, scenario); MarginalCongestionPricingHandler marginalCostTollHandler = new MarginalCongestionPricingHandler(events, scenario); - + events.addHandler(eventWriter); events.addHandler(congestionHandler); events.addHandler(marginalCostTollHandler); - + log.info("Reading events file..."); MatsimEventsReader reader = new MatsimEventsReader(events); - reader.readFile(runDirectory + "ITERS/it." + config.controler().getLastIteration() + "/" + config.controler().getLastIteration() + ".events.xml.gz"); + reader.readFile(runDirectory + "ITERS/it." + config.controller().getLastIteration() + "/" + config.controller().getLastIteration() + ".events.xml.gz"); log.info("Reading events file... Done."); eventWriter.closeFile(); - - congestionHandler.writeCongestionStats(outputDirectory + config.controler().getLastIteration() + ".congestionStats_Offline.csv"); + + congestionHandler.writeCongestionStats(outputDirectory + config.controller().getLastIteration() + ".congestionStats_Offline.csv"); } - + } - + diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/controler/AdvancedMarginalCongestionPricingContolerListener.java b/contribs/vsp/src/main/java/playground/vsp/congestion/controler/AdvancedMarginalCongestionPricingContolerListener.java index 2641fd649e1..d940473e97b 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/controler/AdvancedMarginalCongestionPricingContolerListener.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/controler/AdvancedMarginalCongestionPricingContolerListener.java @@ -19,7 +19,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.controler; @@ -50,60 +50,60 @@ public class AdvancedMarginalCongestionPricingContolerListener implements Startu private final Scenario scenario; private TollHandler tollHandler; private EventHandler congestionHandler; - + private double factor = 1.0; private AdvancedMarginalCongestionPricingHandler pricingHandler; - + /** * @param scenario * @param tollHandler - * @param handler must be one of the implementation for congestion pricing + * @param handler must be one of the implementation for congestion pricing */ public AdvancedMarginalCongestionPricingContolerListener(Scenario scenario, TollHandler tollHandler, EventHandler congestionHandler){ this(scenario, tollHandler, congestionHandler, 1.0); } - + public AdvancedMarginalCongestionPricingContolerListener(Scenario scenario, TollHandler tollHandler, EventHandler congestionHandler, double factor){ this.scenario = scenario; this.tollHandler = tollHandler; this.congestionHandler = congestionHandler; this.factor = factor; } - + @Override public void notifyStartup(StartupEvent event) { - + EventsManager eventsManager = event.getServices().getEvents(); - + this.pricingHandler = new AdvancedMarginalCongestionPricingHandler(eventsManager, this.scenario, this.factor); - + eventsManager.addHandler(this.congestionHandler); eventsManager.addHandler(this.pricingHandler); eventsManager.addHandler(this.tollHandler); } - + @Override public void notifyAfterMobsim(AfterMobsimEvent event) { log.info("Monetize final congestion events..."); this.pricingHandler.processFinalCongestionEvents(); log.info("Total monetized amount: " + this.pricingHandler.getAmountSum()); log.info("Monetize final congestion events... Done."); - + log.info("Writing out VTTS statistics..."); - this.pricingHandler.printVTTS(this.scenario.getConfig().controler().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/VTTS_forAllDelayedTrips.csv"); - this.pricingHandler.printAvgVTTSperPerson(this.scenario.getConfig().controler().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/VTTS_AvgPerPerson_forAllDelayedTrips.csv"); + this.pricingHandler.printVTTS(this.scenario.getConfig().controller().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/VTTS_forAllDelayedTrips.csv"); + this.pricingHandler.printAvgVTTSperPerson(this.scenario.getConfig().controller().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/VTTS_AvgPerPerson_forAllDelayedTrips.csv"); log.info("Writing out VTTS statistics... Done."); } @Override public void notifyIterationEnds(IterationEndsEvent event) { - + log.info("Set average tolls for each link Id and time bin..."); this.tollHandler.setLinkId2timeBin2avgToll(); log.info("Set average tolls for each link Id and time bin... Done."); - + // write out analysis every iteration - this.tollHandler.writeTollStats(this.scenario.getConfig().controler().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/tollStats.csv"); + this.tollHandler.writeTollStats(this.scenario.getConfig().controller().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/tollStats.csv"); } } diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/controler/AverageCongestionPricingControlerListener.java b/contribs/vsp/src/main/java/playground/vsp/congestion/controler/AverageCongestionPricingControlerListener.java index 3a0be7bf7f6..6b62c0bdd73 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/controler/AverageCongestionPricingControlerListener.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/controler/AverageCongestionPricingControlerListener.java @@ -19,7 +19,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.controler; @@ -50,18 +50,18 @@ public class AverageCongestionPricingControlerListener implements StartupListene private final MutableScenario scenario; private TollHandler tollHandler; private CongestionHandlerImplV3 congestionHandler; - + public AverageCongestionPricingControlerListener(MutableScenario scenario, TollHandler tollHandler){ this.scenario = scenario; this.tollHandler = tollHandler; } - + @Override public void notifyStartup(StartupEvent event) { - + EventsManager eventsManager = event.getServices().getEvents(); congestionHandler = new CongestionHandlerImplV3(eventsManager, scenario); - + event.getServices().getEvents().addHandler(congestionHandler); event.getServices().getEvents().addHandler(tollHandler); @@ -69,19 +69,19 @@ public void notifyStartup(StartupEvent event) { @Override public void notifyAfterMobsim(AfterMobsimEvent event) { - + log.info("Set average tolls for each link Id and time bin."); tollHandler.setLinkId2timeBin2avgToll(); - + // write out toll statistics every iteration - tollHandler.writeTollStats(this.scenario.getConfig().controler().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/tollStats.csv"); - + tollHandler.writeTollStats(this.scenario.getConfig().controller().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/tollStats.csv"); + // write out congestion statistics every iteration - congestionHandler.writeCongestionStats(this.scenario.getConfig().controler().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/congestionStats.csv"); - + congestionHandler.writeCongestionStats(this.scenario.getConfig().controller().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/congestionStats.csv"); + log.info("Throwing agent money events based on calculated average marginal cost for each link and time bin."); EventsManager events = event.getServices().getEvents(); - + for (LinkEnterEvent enterEvent : this.tollHandler.getLinkEnterEvents()) { double amount = tollHandler.getAvgToll(enterEvent.getLinkId(), enterEvent.getTime()); PersonMoneyEvent moneyEvent = new PersonMoneyEvent(enterEvent.getTime(), Id.createPersonId(enterEvent.getVehicleId()), amount, "congestionPricing", null); diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/controler/MarginalCongestionPricingContolerListener.java b/contribs/vsp/src/main/java/playground/vsp/congestion/controler/MarginalCongestionPricingContolerListener.java index d43dfcf26ec..7926459c53f 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/controler/MarginalCongestionPricingContolerListener.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/controler/MarginalCongestionPricingContolerListener.java @@ -19,7 +19,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.controler; @@ -51,30 +51,30 @@ public class MarginalCongestionPricingContolerListener implements StartupListene private double factor = 1.0; private MarginalCongestionPricingHandler pricingHandler; - + /** * @param scenario * @param tollHandler - * @param handler must be one of the implementation for congestion pricing + * @param handler must be one of the implementation for congestion pricing */ public MarginalCongestionPricingContolerListener(Scenario scenario, TollHandler tollHandler, EventHandler congestionHandler){ this (scenario, tollHandler, congestionHandler, 1.0); } - + public MarginalCongestionPricingContolerListener(Scenario scenario, TollHandler tollHandler, EventHandler congestionHandler, double factor){ this.scenario = scenario; this.tollHandler = tollHandler; this.congestionHandler = congestionHandler; this.factor = factor; } - + @Override public void notifyStartup(StartupEvent event) { - + EventsManager eventsManager = event.getServices().getEvents(); - + this.pricingHandler = new MarginalCongestionPricingHandler(eventsManager, this.scenario, this.factor); - + eventsManager.addHandler(this.congestionHandler); eventsManager.addHandler(this.pricingHandler); eventsManager.addHandler(this.tollHandler); @@ -82,13 +82,13 @@ public void notifyStartup(StartupEvent event) { @Override public void notifyIterationEnds(IterationEndsEvent event) { - + this.log.info("Set average tolls for each link Id and time bin..."); this.tollHandler.setLinkId2timeBin2avgToll(); this.log.info("Set average tolls for each link Id and time bin... Done."); - + // write out analysis every iteration - this.tollHandler.writeTollStats(this.scenario.getConfig().controler().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/tollStats.csv"); + this.tollHandler.writeTollStats(this.scenario.getConfig().controller().getOutputDirectory() + "/ITERS/it." + event.getIteration() + "/tollStats.csv"); } } diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/AdvancedMarginalCongestionPricingHandler.java b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/AdvancedMarginalCongestionPricingHandler.java index 639cba9d587..e5a56c9ddfc 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/AdvancedMarginalCongestionPricingHandler.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/AdvancedMarginalCongestionPricingHandler.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.handlers; @@ -56,7 +56,7 @@ * This handler calculates agent money events based on marginal congestion events. * The causing agent has to pay a toll depending on the number of affected agents and the external delay in sec. * The delay is monetized using the behavioral parameters from the scenario and taking into account the agent-specific Value of Travel Time Savings (VTTS) - * + * * @author ikaddoura * */ @@ -65,47 +65,47 @@ public class AdvancedMarginalCongestionPricingHandler implements CongestionEvent private final static Logger log = LogManager.getLogger(AdvancedMarginalCongestionPricingHandler.class); private static int incompletedPlanWarning = 0; - + private final Scenario scenario; private final EventsManager events; - + private double factor = 1.0; - + private double amountSum = 0.; - + private Map, Double> affectedPersonId2delayToProcess = new HashMap, Double>(); private Map, List> affectedPersonId2congestionEventsToProcess = new HashMap<>(); private Map, Double> personId2currentActivityStartTime = new HashMap, Double>(); private Map, Double> personId2firstActivityEndTime = new HashMap, Double>(); private Map, String> personId2currentActivityType = new HashMap, String>(); private Map, String> personId2firstActivityType = new HashMap, String>(); - + private Map, List> personId2VTTSh = new HashMap<>(); private MarginalSumScoringFunction marginaSumScoringFunction; - + public AdvancedMarginalCongestionPricingHandler(EventsManager eventsManager, Scenario scenario) { this(eventsManager, scenario, 1.0); } - + public AdvancedMarginalCongestionPricingHandler(EventsManager eventsManager, Scenario scenario, double factor) { log.info("Using the toll factor " + factor); log.info("Using different VTTS to translate delays into monetary units. Computing the actual activity delay costs for each agent."); - + this.events = eventsManager; this.scenario = scenario; this.factor = factor; - + this.marginaSumScoringFunction = new MarginalSumScoringFunction( - new ScoringParameters.Builder(scenario.getConfig().planCalcScore(), scenario.getConfig().planCalcScore().getScoringParameters(null), scenario.getConfig().scenario()).build()); + new ScoringParameters.Builder(scenario.getConfig().scoring(), scenario.getConfig().scoring().getScoringParameters(null), scenario.getConfig().scenario()).build()); } @Override public void reset(int iteration) { - + incompletedPlanWarning = 0; - + this.amountSum = 0.; this.personId2currentActivityStartTime.clear(); this.affectedPersonId2congestionEventsToProcess.clear(); @@ -113,13 +113,13 @@ public void reset(int iteration) { this.personId2currentActivityType.clear(); this.personId2firstActivityType.clear(); this.affectedPersonId2delayToProcess.clear(); - + this.personId2VTTSh.clear(); } @Override public void handleEvent(CongestionEvent event) { - + // store the congestion event if (affectedPersonId2congestionEventsToProcess.containsKey(event.getAffectedAgentId())) { affectedPersonId2congestionEventsToProcess.get(event.getAffectedAgentId()).add(event); @@ -127,8 +127,8 @@ public void handleEvent(CongestionEvent event) { List congestionEventsToProcess = new ArrayList<>(); congestionEventsToProcess.add(event); affectedPersonId2congestionEventsToProcess.put(event.getAffectedAgentId(), congestionEventsToProcess); - } - + } + // compute the total trip delay if (this.affectedPersonId2delayToProcess.containsKey(event.getAffectedAgentId())) { double delayUpdated = affectedPersonId2delayToProcess.get(event.getAffectedAgentId()) + event.getDelay(); @@ -136,12 +136,12 @@ public void handleEvent(CongestionEvent event) { } else { affectedPersonId2delayToProcess.put(event.getAffectedAgentId(), event.getDelay()); } - + } - + @Override public void handleEvent(ActivityStartEvent event) { - + if (event.getActType().contains("interaction")) { // skip } else { @@ -152,24 +152,24 @@ public void handleEvent(ActivityStartEvent event) { @Override public void handleEvent(ActivityEndEvent event) { - + if (event.getActType().contains("interaction")) { // skip } else { if (this.personId2currentActivityStartTime.containsKey(event.getPersonId())) { // This is not the first activity... - + // ... now process all congestion events thrown during the trip to the activity which has just ended, ... processCongestionEventsForAffectedPerson(event.getPersonId(), event.getTime(), event.getLinkId()); - + // ... update the status of the 'current' activity... this.personId2currentActivityType.remove(event.getPersonId()); this.personId2currentActivityStartTime.remove(event.getPersonId()); - - // ... and remove all processed congestion events. + + // ... and remove all processed congestion events. this.affectedPersonId2congestionEventsToProcess.remove(event.getPersonId()); this.affectedPersonId2delayToProcess.remove(event.getPersonId()); - + } else { // This is the first activity. The first and last / overnight activity are / is considered in a final step. // Therefore, the relevant information has to be stored. @@ -189,69 +189,69 @@ public void processFinalCongestionEvents() { processCongestionEventsForAffectedPerson(affectedPersonId, FINAL_CONGESTION_EVENT_TIME, null);// } } - + private void processCongestionEventsForAffectedPerson(Id personId, double activityEndTime, Id linkId) { - + // First, compute the agent's total (affected) delay from the previous trip. double totalDelayThisPerson = 0.0; if (this.affectedPersonId2delayToProcess.containsKey(personId)) { totalDelayThisPerson = this.affectedPersonId2delayToProcess.get(personId); } - + if (totalDelayThisPerson > 0.) { // The agent was delayed on the previous trip... - // ... now calculate the agent's disutility from being late at the current activity: score(arrivalTime_ohneDelay) - score(arrivalTime_withDelay) + // ... now calculate the agent's disutility from being late at the current activity: score(arrivalTime_ohneDelay) - score(arrivalTime_withDelay) double activityDelayDisutility = 0.; - + // First, check if the plan completed is completed, i.e. if the agent has arrived at an activity (after being delayed) if (this.personId2currentActivityType.containsKey(personId) && this.personId2currentActivityStartTime.containsKey(personId)) { // Yes, the plan seems to be completed. - + if (activityEndTime == FINAL_CONGESTION_EVENT_TIME) { // The end time is undefined... - + // ... now handle the first and last OR overnight activity. This is figured out by the scoring function itself (depending on the activity types). - + Activity activityMorning = PopulationUtils.createActivityFromLinkId(this.personId2firstActivityType.get(personId), linkId); activityMorning.setEndTime(this.personId2firstActivityEndTime.get(personId)); - + Activity activityEvening = PopulationUtils.createActivityFromLinkId(this.personId2currentActivityType.get(personId), linkId); activityEvening.setStartTime(this.personId2currentActivityStartTime.get(personId)); - + activityDelayDisutility = marginaSumScoringFunction.getOvernightActivityDelayDisutility(activityMorning, activityEvening, totalDelayThisPerson); - + } else { // The activity has an end time indicating a 'normal' activity. - + Activity activity = PopulationUtils.createActivityFromLinkId(this.personId2currentActivityType.get(personId), linkId); activity.setStartTime(this.personId2currentActivityStartTime.get(personId)); - activity.setEndTime(activityEndTime); + activity.setEndTime(activityEndTime); activityDelayDisutility = marginaSumScoringFunction.getNormalActivityDelayDisutility(activity, totalDelayThisPerson); } - + } else { // No, there is no information about the current activity which indicates that the trip (with the delay) was not completed. - + if (incompletedPlanWarning <= 10) { log.warn("Agent " + personId + " has not yet completed the plan/trip (the agent is probably stucking). Cannot compute the disutility of being late at this activity. " + "Something like the disutility of not arriving at the activity is required. Try to avoid this by setting a smaller stuck time period."); - log.warn("Setting the disutilty of being delayed on the previous trip using the config parameters; assuming the marginal disutility of being delayed at the (hypothetical) activity to be equal to beta_performing: " + this.scenario.getConfig().planCalcScore().getPerforming_utils_hr()); - + log.warn("Setting the disutilty of being delayed on the previous trip using the config parameters; assuming the marginal disutility of being delayed at the (hypothetical) activity to be equal to beta_performing: " + this.scenario.getConfig().scoring().getPerforming_utils_hr()); + if (incompletedPlanWarning == 10) { log.warn("Additional warnings of this type are suppressed."); } incompletedPlanWarning++; } - activityDelayDisutility = (totalDelayThisPerson / 3600.) * this.scenario.getConfig().planCalcScore().getPerforming_utils_hr(); + activityDelayDisutility = (totalDelayThisPerson / 3600.) * this.scenario.getConfig().scoring().getPerforming_utils_hr(); } - + // Calculate the agent's trip delay disutility (could be done similar to the activity delay disutility). - double tripDelayDisutility = (totalDelayThisPerson / 3600.) * this.scenario.getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() * (-1); - + double tripDelayDisutility = (totalDelayThisPerson / 3600.) * this.scenario.getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() * (-1); + // Translate the disutility into monetary units. - double totalDelayCost = (activityDelayDisutility + tripDelayDisutility) / this.scenario.getConfig().planCalcScore().getMarginalUtilityOfMoney(); + double totalDelayCost = (activityDelayDisutility + tripDelayDisutility) / this.scenario.getConfig().scoring().getMarginalUtilityOfMoney(); double delayCostPerSecond = totalDelayCost / totalDelayThisPerson; - + // store the VTTS for analysis purposes if (this.personId2VTTSh.containsKey(personId)) { this.personId2VTTSh.get(personId).add(delayCostPerSecond * 3600); @@ -261,34 +261,34 @@ private void processCongestionEventsForAffectedPerson(Id personId, doubl this.personId2VTTSh.put(personId, vTTSh); } // Go through the congestion events and charge each causing agent his/her contribution to the delay cost: caused delay * activity delay cost per second + caused delay * trip delay cost per second - + for (CongestionEvent congestionEvent : this.affectedPersonId2congestionEventsToProcess.get(personId)) { - + double amount = this.factor * congestionEvent.getDelay() * delayCostPerSecond * (-1); this.amountSum = this.amountSum + amount; - + if (activityEndTime == FINAL_CONGESTION_EVENT_TIME) { activityEndTime = this.scenario.getConfig().qsim().getEndTime().seconds(); } - - PersonMoneyEvent moneyEvent = new PersonMoneyEvent(activityEndTime, congestionEvent.getCausingAgentId(), amount, "congestionPricing", null); + + PersonMoneyEvent moneyEvent = new PersonMoneyEvent(activityEndTime, congestionEvent.getCausingAgentId(), amount, "congestionPricing", null); this.events.processEvent(moneyEvent); - + PersonLinkMoneyEvent linkMoneyEvent = new PersonLinkMoneyEvent(activityEndTime, congestionEvent.getCausingAgentId(), congestionEvent.getLinkId(), amount, congestionEvent.getEmergenceTime(), "congestion"); this.events.processEvent(linkMoneyEvent); } } } - + public void printAvgVTTSperPerson(String fileName) { - + File file = new File(fileName); - + try { BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write("person Id;VTTS (money/hour)"); bw.newLine(); - + for (Id personId : this.personId2VTTSh.keySet()){ double vttsSum = 0.; double counter = 0; @@ -297,36 +297,36 @@ public void printAvgVTTSperPerson(String fileName) { counter++; } bw.write(personId + ";" + (vttsSum / counter) ); - bw.newLine(); + bw.newLine(); } - + bw.close(); log.info("Output written to " + fileName); - + } catch (IOException e) { e.printStackTrace(); } } - + public void printVTTS(String fileName) { - + File file = new File(fileName); - + try { BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write("person Id;VTTS (money/hour)"); bw.newLine(); - + for (Id personId : this.personId2VTTSh.keySet()){ for (Double vTTS : this.personId2VTTSh.get(personId)){ bw.write(personId + ";" + vTTS); - bw.newLine(); + bw.newLine(); } } - + bw.close(); log.info("Output written to " + fileName); - + } catch (IOException e) { e.printStackTrace(); } @@ -335,5 +335,5 @@ public void printVTTS(String fileName) { public double getAmountSum() { return amountSum; } - -} \ No newline at end of file + +} diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/CongestionHandlerBaseImpl.java b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/CongestionHandlerBaseImpl.java index dcd89958b88..fa9f4242055 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/CongestionHandlerBaseImpl.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/CongestionHandlerBaseImpl.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.handlers; @@ -54,7 +54,7 @@ /** * This class provides the basic functionality to calculate congestion effects which may be used for internalization. * One of the main tasks is to keep track of the queues on each link. - * + * * @author ikaddoura * */ @@ -84,7 +84,7 @@ class CongestionHandlerBaseImpl implements CongestionHandler { log.warn("Capacity period is other than 3600."); } - if ( this.scenario.getConfig().parallelEventHandling().getNumberOfThreads()!= null) { + if ( this.scenario.getConfig().eventsManager().getNumberOfThreads()!= null) { log.warn("Parallel event handling is not tested. It should not work properly."); } @@ -103,7 +103,7 @@ public final void reset(int iteration) { this.totalDelay = 0.; this.delayNotInternalized_roundingErrors = 0.; this.totalInternalizedDelay = 0.; - + veh2DriverDelegate.reset(iteration); } @@ -127,9 +127,9 @@ public final void handleEvent( VehicleEntersTrafficEvent event ) { @Override public final void handleEvent(PersonDepartureEvent event) { if (event.getLegMode().toString().equals(TransportMode.car.toString())){ // car! - + this.carPersonIDs.add(event.getPersonId()); - + LinkCongestionInfo linkInfo = CongestionUtils.getOrCreateLinkInfo( event.getLinkId(), linkId2congestionInfo, scenario ) ; AgentOnLinkInfo agentInfo = new AgentOnLinkInfo.Builder().setAgentId( event.getPersonId() ) @@ -144,11 +144,11 @@ public final void handleEvent(PersonDepartureEvent event) { public final void handleEvent(LinkEnterEvent event) { if (this.ptVehicleIDs.contains(event.getVehicleId())) { // skip pt vehicles - } else { // car! + } else { // car! LinkCongestionInfo linkInfo = CongestionUtils.getOrCreateLinkInfo( event.getLinkId(), linkId2congestionInfo, scenario ) ; Id driverId = veh2DriverDelegate.getDriverOfVehicle(event.getVehicleId()); - + if (this.carPersonIDs.contains(driverId)) { // the driver is a car user AgentOnLinkInfo agentInfo = new AgentOnLinkInfo.Builder().setAgentId( driverId ).setLinkId( event.getLinkId() ) @@ -161,8 +161,8 @@ public final void handleEvent(LinkEnterEvent event) { @Override public final void handleEvent(LinkLeaveEvent event) { // yy My preference would be if we found a solution where the basic bookkeeping (e.g. update flow and - // delay queues) is done here. However, delegation does not allow to have custom code in between - // standard code (as was the case before with calculateCongestion). We need to consider if it is possible to + // delay queues) is done here. However, delegation does not allow to have custom code in between + // standard code (as was the case before with calculateCongestion). We need to consider if it is possible to // rather have the standard code in one go and embed it in the delegated class. In the sense of // class MyCongestionHandlerImpl { // ... handleEvent( LinkLeaveEvent event ) { @@ -170,15 +170,15 @@ public final void handleEvent(LinkLeaveEvent event) { // delegate.handleEvent( event ) ; // ... // more custom code // ... - + // coming here ... - + if (this.ptVehicleIDs.contains(event.getVehicleId())) { // skip pt vehicles - } else { // car! - + } else { // car! + Id personId = veh2DriverDelegate.getDriverOfVehicle( event.getVehicleId() ) ; - + if (this.carPersonIDs.contains(personId)) { // this person is a car user LinkCongestionInfo linkInfo = CongestionUtils.getOrCreateLinkInfo(event.getLinkId(), this.getLinkId2congestionInfo(), scenario); @@ -198,44 +198,44 @@ public final void handleEvent(LinkLeaveEvent event) { // global book-keeping: this.totalDelay += ( event.getTime() - delayInfo.freeSpeedLeaveTime ); } - } + } } @Override public final void handleEvent( PersonArrivalEvent event ) { - + if (event.getLegMode().equals(TransportMode.car)) { LinkCongestionInfo linkInfo = CongestionUtils.getOrCreateLinkInfo( event.getLinkId(), linkId2congestionInfo, scenario) ; linkInfo.getAgentsOnLink().remove( event.getPersonId() ) ; - + this.carPersonIDs.remove(event.getPersonId()); } } public final static void updateFlowAndDelayQueues(double time, DelayInfo delayInfo, LinkCongestionInfo linkInfo) { - + double delay = time - delayInfo.freeSpeedLeaveTime; - if ( delay < 1.0 ) { - linkInfo.getFlowQueue().clear(); + if ( delay < 1.0 ) { + linkInfo.getFlowQueue().clear(); return ; // should be ok but not tested (*) - } - + } + if (linkInfo.getFlowQueue().isEmpty() ) { // queue is already empty; nothing to do - + // seems like this should never be called when (*) is used, but in practice it happens, i.e. tests fail when the above if condition // is commented out. maybe initialization? kai, apr'16 } else { double earliestLeaveTimeAfterVehicleAhead = linkInfo.getLastLeaveEvent().getTime() + linkInfo.getMarginalDelayPerLeavingVehicle_sec(); if ( time > earliestLeaveTimeAfterVehicleAhead + 1.) { // Vehicle is delayed by more than 1/cap. That is, we must be spill-back delayed. - - double freeSpeedLeaveTimeGap = delayInfo.freeSpeedLeaveTime - linkInfo.getFlowQueue().getLast().freeSpeedLeaveTime ; + + double freeSpeedLeaveTimeGap = delayInfo.freeSpeedLeaveTime - linkInfo.getFlowQueue().getLast().freeSpeedLeaveTime ; if(freeSpeedLeaveTimeGap < linkInfo.getMarginalDelayPerLeavingVehicle_sec()){ // we are ALSO flow delayed. Therefore, we consider the bottleneck still active - + } else { // we are NOT also flow delayed. The bottleneck is now inactive: linkInfo.getFlowQueue().clear(); @@ -259,7 +259,7 @@ public final static void updateFlowAndDelayQueues(double time, DelayInfo delayIn *

      * Charging the agents that are in the flow queue. */ - final double computeFlowCongestionAndReturnStorageDelay(double now, Id linkId, DelayInfo affectedAgentDelayInfo, double remainingDelay) { + final double computeFlowCongestionAndReturnStorageDelay(double now, Id linkId, DelayInfo affectedAgentDelayInfo, double remainingDelay) { LinkCongestionInfo linkInfo = this.linkId2congestionInfo.get( linkId ); @@ -273,9 +273,9 @@ final double computeFlowCongestionAndReturnStorageDelay(double now, Id lin double allocatedDelay = Math.min(linkInfo.getMarginalDelayPerLeavingVehicle_sec(), remainingDelay); - CongestionEvent congestionEvent = new CongestionEvent(now, "flowAndStorageCapacity", causingAgentDelayInfo.personId, + CongestionEvent congestionEvent = new CongestionEvent(now, "flowAndStorageCapacity", causingAgentDelayInfo.personId, affectedAgentDelayInfo.personId, allocatedDelay, linkId, causingAgentDelayInfo.linkEnterTime ); - this.events.processEvent(congestionEvent); + this.events.processEvent(congestionEvent); this.totalInternalizedDelay += allocatedDelay ; @@ -292,7 +292,7 @@ final double computeFlowCongestionAndReturnStorageDelay(double now, Id lin return remainingDelay; } - + @Override public double getTotalDelay() { return this.totalDelay ; diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/MarginalCongestionPricingHandler.java b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/MarginalCongestionPricingHandler.java index 6bea372918a..56a521e5f9b 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/MarginalCongestionPricingHandler.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/MarginalCongestionPricingHandler.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.handlers; @@ -37,7 +37,7 @@ * This handler calculates agent money events based on marginal congestion events. * The causing agent has to pay a toll depending on the number of affected agents and the external delay in sec. * The delay is monetized using the behavioral parameters from the scenario. - * + * * @author ikaddoura * */ @@ -49,19 +49,19 @@ public class MarginalCongestionPricingHandler implements CongestionEventHandler private final Scenario scenario; private final double vtts_car; private final double factor; - + private double amountSum = 0.; public MarginalCongestionPricingHandler(EventsManager eventsManager, Scenario scenario) { this(eventsManager, scenario, 1.0); } - + public MarginalCongestionPricingHandler(EventsManager eventsManager, Scenario scenario, double factor) { this.events = eventsManager; this.scenario = scenario; - this.vtts_car = (this.scenario.getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() - this.scenario.getConfig().planCalcScore().getPerforming_utils_hr()) / this.scenario.getConfig().planCalcScore().getMarginalUtilityOfMoney(); + this.vtts_car = (this.scenario.getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() - this.scenario.getConfig().scoring().getPerforming_utils_hr()) / this.scenario.getConfig().scoring().getMarginalUtilityOfMoney(); this.factor = factor; - + log.info("Using the toll factor " + factor); log.info("Using the same VTTS for each agent to translate delays into monetary units."); log.info("VTTS_car: " + vtts_car); @@ -74,13 +74,13 @@ public void reset(int iteration) { @Override public void handleEvent(CongestionEvent event) { - + double amount = this.factor * event.getDelay() / 3600 * this.vtts_car; this.amountSum = this.amountSum + amount; - + PersonMoneyEvent moneyEvent = new PersonMoneyEvent(event.getTime(), event.getCausingAgentId(), amount, "congestionPricing", null); this.events.processEvent(moneyEvent); - + PersonLinkMoneyEvent linkMoneyEvent = new PersonLinkMoneyEvent(event.getTime(), event.getCausingAgentId(), event.getLinkId(), amount, event.getEmergenceTime(), "congestion"); this.events.processEvent(linkMoneyEvent); } @@ -88,5 +88,5 @@ public void handleEvent(CongestionEvent event) { public double getAmountSum() { return amountSum; } - -} \ No newline at end of file + +} diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/MarginalSumScoringFunction.java b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/MarginalSumScoringFunction.java index ec5d51bdb78..54c11433467 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/MarginalSumScoringFunction.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/MarginalSumScoringFunction.java @@ -19,8 +19,8 @@ package playground.vsp.congestion.handlers; import org.matsim.api.core.v01.population.Activity; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.TypicalDurationScoreComputation; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.TypicalDurationScoreComputation; import org.matsim.core.population.PopulationUtils; import org.matsim.core.scoring.SumScoringFunction; import org.matsim.core.scoring.functions.ActivityUtilityParameters; @@ -33,29 +33,29 @@ */ public class MarginalSumScoringFunction { // private final static Logger log = LogManager.getLogger(MarginalSumScoringFunction.class); - + CharyparNagelActivityScoring activityScoringA; CharyparNagelActivityScoring activityScoringB; - + public MarginalSumScoringFunction(ScoringParameters params) { - - PlanCalcScoreConfigGroup.ActivityParams taxiActParams = new PlanCalcScoreConfigGroup.ActivityParams("TaxiPickup"); + + ScoringConfigGroup.ActivityParams taxiActParams = new ScoringConfigGroup.ActivityParams("TaxiPickup"); taxiActParams.setTypicalDurationScoreComputation(TypicalDurationScoreComputation.relative); taxiActParams.setScoringThisActivityAtAll(false); taxiActParams.setTypicalDuration(1.0); - + ActivityUtilityParameters actUtilityParams = new ActivityUtilityParameters.Builder(taxiActParams).build(); params.utilParams.put("TaxiPickup", actUtilityParams); - + activityScoringA = new CharyparNagelActivityScoring(params); activityScoringB = new CharyparNagelActivityScoring(params); } public final double getNormalActivityDelayDisutility(Activity activity, double delay) { - + SumScoringFunction sumScoringA = new SumScoringFunction() ; sumScoringA.addScoringFunction(activityScoringA); - + SumScoringFunction sumScoringB = new SumScoringFunction() ; sumScoringB.addScoringFunction(activityScoringB); @@ -70,31 +70,31 @@ public final double getNormalActivityDelayDisutility(Activity activity, double d Activity activityWithoutDelay = PopulationUtils.createActivity(activity); activityWithoutDelay.setStartTime(activity.getStartTime().seconds() - delay); - + // log.info("activity: " + activity.toString()); // log.info("activityWithoutDelay: " + activityWithoutDelay.toString()); - + sumScoringA.handleActivity(activity); sumScoringB.handleActivity(activityWithoutDelay); sumScoringA.finish(); sumScoringB.finish(); - + double scoreA1 = sumScoringA.getScore(); double scoreB1 = sumScoringB.getScore(); - + double scoreWithDelay = scoreA1 - scoreA0; double scoreWithoutDelay = scoreB1 - scoreB0; - + double activityDelayDisutility = scoreWithoutDelay - scoreWithDelay; - return activityDelayDisutility; + return activityDelayDisutility; } - + public final double getOvernightActivityDelayDisutility(Activity activityMorning, Activity activityEvening, double delay) { - + SumScoringFunction delegateA = new SumScoringFunction() ; delegateA.addScoringFunction(activityScoringA); - + SumScoringFunction delegateB = new SumScoringFunction() ; delegateB.addScoringFunction(activityScoringB); @@ -109,34 +109,34 @@ public final double getOvernightActivityDelayDisutility(Activity activityMorning } else { throw new RuntimeException("activityEvening is not the last activity. Or why does it have an end time? Aborting..."); } - + double scoreA0 = delegateA.getScore(); double scoreB0 = delegateB.getScore(); - + delegateA.handleActivity(activityMorning); delegateB.handleActivity(activityMorning); - + Activity activityEveningWithoutDelay = PopulationUtils.createActivity(activityEvening); activityEveningWithoutDelay.setStartTime(activityEvening.getStartTime().seconds() - delay); - + // log.info("activityMorning: " + activityMorning.toString()); // log.info("activityEvening: " + activityEvening.toString()); // log.info("activityEveningWithoutDelay: " + activityEveningWithoutDelay.toString()); delegateA.handleActivity(activityEvening); delegateB.handleActivity(activityEveningWithoutDelay); - + delegateA.finish(); delegateB.finish(); - + double scoreA1 = delegateA.getScore(); double scoreB1 = delegateB.getScore(); - + double scoreWithDelay = scoreA1 - scoreA0; double scoreWithoutDelay = scoreB1 - scoreB0; - + double activityDelayDisutility = scoreWithoutDelay - scoreWithDelay; return activityDelayDisutility; } - + } diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/TollHandler.java b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/TollHandler.java index 3dc92c4caef..7fc6ae63a67 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/TollHandler.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/handlers/TollHandler.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.handlers; @@ -51,29 +51,29 @@ public class TollHandler implements CongestionEventHandler, LinkEnterEventHandler, PersonDepartureEventHandler { private static final Logger log = LogManager.getLogger(TollHandler.class); private double timeBinSize = 900.; - + private Map, Map> linkId2timeBin2tollSum = new HashMap, Map>(); private Map, Map> linkId2timeBin2enteringAndDepartingAgents = new HashMap, Map>(); - + private List congestionEvents = new ArrayList(); private List linkEnterEvents = new ArrayList(); private List personDepartureEvents = new ArrayList(); private Map, Map> linkId2timeBin2avgToll = new HashMap, Map>(); private Map, Map> linkId2timeBin2avgTollOldValue = new HashMap, Map>(); - + private boolean setMethodsExecuted = false; - + private double vtts_car; private double congestionTollFactor; - + public TollHandler(Scenario scenario, double congestionTollFactor) { - this.vtts_car = (scenario.getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() - scenario.getConfig().planCalcScore().getPerforming_utils_hr()) / scenario.getConfig().planCalcScore().getMarginalUtilityOfMoney(); + this.vtts_car = (scenario.getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() - scenario.getConfig().scoring().getPerforming_utils_hr()) / scenario.getConfig().scoring().getMarginalUtilityOfMoney(); this.congestionTollFactor = congestionTollFactor; log.info("VTTS_car: " + vtts_car); log.info("Congestion toll factor: " + congestionTollFactor); } - + public TollHandler(Scenario scenario) { this(scenario, 1.0); } @@ -89,20 +89,20 @@ public void reset(int iteration) { this.linkId2timeBin2avgTollOldValue.clear(); this.linkId2timeBin2avgTollOldValue.putAll(linkId2timeBin2avgToll); this.linkId2timeBin2avgToll.clear(); - - this.setMethodsExecuted = false; + + this.setMethodsExecuted = false; } @Override public void handleEvent(CongestionEvent event) { this.congestionEvents.add(event); } - + @Override public void handleEvent(LinkEnterEvent event) { - this.linkEnterEvents.add(event); + this.linkEnterEvents.add(event); } - + @Override public void handleEvent(PersonDepartureEvent event) { if (event.getLegMode().equals(TransportMode.car.toString())) { @@ -113,30 +113,30 @@ public void handleEvent(PersonDepartureEvent event) { } public void setLinkId2timeBin2avgToll() { - + log.info("Total number of congestion events: " + this.congestionEvents.size()); - + if (!this.linkId2timeBin2tollSum.isEmpty()) { throw new RuntimeException("Map linkId2timeBin2tollSum should be empty!"); } else { // calculate toll sum for each link and time bin setlinkId2timeBin2tollSum(); } - + if (!this.linkId2timeBin2enteringAndDepartingAgents.isEmpty()) { throw new RuntimeException("Map linkId2timeBin2enteringAndDepartingAgents should be empty!"); } else { // calculate leaving agents for each link and time bin setlinkId2timeBin2enteringAndDepartingAgents(); } - + this.setMethodsExecuted = true; - + if (!this.linkId2timeBin2avgToll.isEmpty()) { throw new RuntimeException("Map linkId2timeBin2avgToll should be empty!"); } else { // calculate average toll for each link and time bin - + for (Id linkId : this.linkId2timeBin2tollSum.keySet()) { // log.info("Calculating average toll for link " + linkId); Map timeBin2tollSum = this.linkId2timeBin2tollSum.get(linkId); @@ -164,19 +164,19 @@ public void setLinkId2timeBin2avgToll() { } private void setlinkId2timeBin2enteringAndDepartingAgents() { - + // first go through all link enter events for (LinkEnterEvent event : this.linkEnterEvents){ - + // if (this.linkId2timeBin2tollSum.containsKey(event.getLinkId())){ // // Tolls paid on this link. - + Map timeBin2enteringAgents = new HashMap(); if (this.linkId2timeBin2enteringAndDepartingAgents.containsKey(event.getLinkId())) { // link already in map timeBin2enteringAgents = this.linkId2timeBin2enteringAndDepartingAgents.get(event.getLinkId()); - + // for this link: search for the right time bin for (double time = 0; time < (30 * 3600);) { time = time + this.timeBinSize; @@ -184,7 +184,7 @@ private void setlinkId2timeBin2enteringAndDepartingAgents() { if (event.getTime() < time && event.getTime() >= (time - this.timeBinSize)) { // event in time bin // update entering agents on this link and in this time bin - + if (timeBin2enteringAgents.get(time) != null) { // not the first agent entering this link in this time bin int enteringAgentsSoFar = timeBin2enteringAgents.get(time); @@ -210,16 +210,16 @@ private void setlinkId2timeBin2enteringAndDepartingAgents() { } } } - - this.linkId2timeBin2enteringAndDepartingAgents.put(event.getLinkId(), timeBin2enteringAgents); - + + this.linkId2timeBin2enteringAndDepartingAgents.put(event.getLinkId(), timeBin2enteringAgents); + // } else { // // No tolls paid on that link. Skip that link. -// +// // } } - - + + // then go through all person departure events // a person departure event means an agent also 'enters' the link for (PersonDepartureEvent event : this.personDepartureEvents) { @@ -289,11 +289,11 @@ private void setlinkId2timeBin2tollSum() { // for this link: search for the right time bin for (double time = 0; time < (30 * 3600);) { time = time + this.timeBinSize; - + if (event.getEmergenceTime() < time && event.getEmergenceTime() >= (time - this.timeBinSize)) { // congestion event in time bin // update toll sum of this link and time bin - + if (timeBin2tollSum.get(time) != null) { // toll sum was calculated before for this time bin double sum = timeBin2tollSum.get(time); @@ -304,13 +304,13 @@ private void setlinkId2timeBin2tollSum() { // toll sum was not calculated before for this time bin double amount = this.congestionTollFactor * (event.getDelay() / 3600.0 * this.vtts_car); timeBin2tollSum.put(time, amount); - } + } } } } else { // link not yet in map - + // for this link: search for the right time bin for (double time = 0; time < (30 * 3600);) { time = time + this.timeBinSize; @@ -322,7 +322,7 @@ private void setlinkId2timeBin2tollSum() { } } } - + this.linkId2timeBin2tollSum.put(event.getLinkId(), timeBin2tollSum); } } @@ -332,7 +332,7 @@ private void setlinkId2timeBin2tollSum() { */ public double getAvgToll(Id linkId, double time) { double avgToll = 0.; - + if (this.linkId2timeBin2avgToll.containsKey(linkId)){ Map timeBin2avgToll = this.linkId2timeBin2avgToll.get(linkId); for (Double timeBin : timeBin2avgToll.keySet()) { @@ -341,16 +341,16 @@ public double getAvgToll(Id linkId, double time) { } } } - + return avgToll; } - + /** * Returns the avg toll (old value) (negative monetary amount) paid on that link during that time bin. */ public double getAvgTollOldValue(Id linkId, double time) { double avgTollOldValue = 0.; - + if (this.linkId2timeBin2avgTollOldValue.containsKey(linkId)){ Map timeBin2avgTollOldValue = this.linkId2timeBin2avgTollOldValue.get(linkId); for (Double timeBin : timeBin2avgTollOldValue.keySet()) { @@ -359,52 +359,52 @@ public double getAvgTollOldValue(Id linkId, double time) { } } } - + return avgTollOldValue; } public void writeTollStats(String fileName) { - + if (this.setMethodsExecuted == false) { log.info("Average tolls per link Id and time bin have to be set. Running required method..."); this.setLinkId2timeBin2avgToll(); } - + File file = new File(fileName); - + try { BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write("link;total toll (per day);entering (and departing) agents (per day)"); bw.newLine(); - + for (Id linkId : this.linkId2timeBin2enteringAndDepartingAgents.keySet()){ double totalToll = 0.; int enteringAgents = 0; - + if (this.linkId2timeBin2tollSum.get(linkId) == null) { // There is no toll payment in any time bin. - + } else { for (Double tollSum_timeBin : this.linkId2timeBin2tollSum.get(linkId).values()){ totalToll = totalToll + tollSum_timeBin; } } - + for (Integer enteringDepartingAgents_timeBin : this.linkId2timeBin2enteringAndDepartingAgents.get(linkId).values()){ enteringAgents = enteringAgents + enteringDepartingAgents_timeBin; } - + bw.write(linkId + ";" + totalToll + ";" + enteringAgents); bw.newLine(); } - + bw.close(); log.info("Output written to " + fileName); - + } catch (IOException e) { e.printStackTrace(); } - + } public List getLinkEnterEvents() { diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/routing/CongestionTollTimeDistanceTravelDisutilityFactory.java b/contribs/vsp/src/main/java/playground/vsp/congestion/routing/CongestionTollTimeDistanceTravelDisutilityFactory.java index 2e30bb434d2..9a2c2c7d0f2 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/routing/CongestionTollTimeDistanceTravelDisutilityFactory.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/routing/CongestionTollTimeDistanceTravelDisutilityFactory.java @@ -19,7 +19,7 @@ * *********************************************************************** */ package playground.vsp.congestion.routing; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.costcalculators.RandomizingTimeDistanceTravelDisutilityFactory; import org.matsim.core.router.costcalculators.TravelDisutilityFactory; import org.matsim.core.router.util.TravelDisutility; @@ -38,10 +38,10 @@ public final class CongestionTollTimeDistanceTravelDisutilityFactory implements private double blendFactor = 1.0; private RandomizingTimeDistanceTravelDisutilityFactory timeDistanceTravelDisutilityFactory; private final TollHandler tollHandler; - private final PlanCalcScoreConfigGroup cnScoringGroup; + private final ScoringConfigGroup cnScoringGroup; public CongestionTollTimeDistanceTravelDisutilityFactory(RandomizingTimeDistanceTravelDisutilityFactory timeDistanceTravelDisutilityFactory, - TollHandler tollHandler, PlanCalcScoreConfigGroup cnScoringGroup) { + TollHandler tollHandler, ScoringConfigGroup cnScoringGroup) { this.tollHandler = tollHandler; this.timeDistanceTravelDisutilityFactory = timeDistanceTravelDisutilityFactory; this.cnScoringGroup = cnScoringGroup; @@ -58,11 +58,11 @@ public final TravelDisutility createTravelDisutility(TravelTime timeCalculator) this.blendFactor ); } - + public void setSigma ( double val ) { this.sigma = val; } - + public void setBlendFactor ( double blendFactor ) { this.blendFactor = blendFactor; } diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/routing/TollDisutilityCalculatorFactory.java b/contribs/vsp/src/main/java/playground/vsp/congestion/routing/TollDisutilityCalculatorFactory.java index 2c7b8e8c03d..f3f4edafce3 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/routing/TollDisutilityCalculatorFactory.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/routing/TollDisutilityCalculatorFactory.java @@ -18,13 +18,13 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.routing; 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.costcalculators.TravelDisutilityFactory; import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; @@ -39,10 +39,10 @@ public class TollDisutilityCalculatorFactory implements TravelDisutilityFactory { private TollHandler tollHandler; - private final PlanCalcScoreConfigGroup cnScoringGroup; + private final ScoringConfigGroup cnScoringGroup; @Deprecated - public TollDisutilityCalculatorFactory(TollHandler tollHandler, PlanCalcScoreConfigGroup cnScoringGroup) { + public TollDisutilityCalculatorFactory(TollHandler tollHandler, ScoringConfigGroup cnScoringGroup) { this.tollHandler = tollHandler; this.cnScoringGroup = cnScoringGroup; } @@ -58,7 +58,7 @@ public double getLinkTravelDisutility(final Link link, final double time, final double linkTravelDisutility = ttdc.getLinkTravelDisutility(link, time, person, vehicle); return linkTravelDisutility; } - + @Override public double getLinkMinimumTravelDisutility(Link link) { return ttdc.getLinkMinimumTravelDisutility(link); diff --git a/contribs/vsp/src/main/java/playground/vsp/congestion/routing/TollTravelDisutilityCalculator.java b/contribs/vsp/src/main/java/playground/vsp/congestion/routing/TollTravelDisutilityCalculator.java index 01e76368fcf..d94e382a396 100644 --- a/contribs/vsp/src/main/java/playground/vsp/congestion/routing/TollTravelDisutilityCalculator.java +++ b/contribs/vsp/src/main/java/playground/vsp/congestion/routing/TollTravelDisutilityCalculator.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.congestion.routing; @@ -27,7 +27,7 @@ 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; @@ -48,28 +48,28 @@ public class TollTravelDisutilityCalculator implements TravelDisutility{ * the old value will be totally overwritten. */ private final double blendFactor = 0.1; - + private TravelTime timeCalculator; private double marginalUtlOfMoney; private double distanceCostRateCar; private double marginalUtlOfTravelTime; private TollHandler tollHandler; - + @Deprecated - public TollTravelDisutilityCalculator(TravelTime timeCalculator, PlanCalcScoreConfigGroup cnScoringGroup, TollHandler tollHandler) { + public TollTravelDisutilityCalculator(TravelTime timeCalculator, ScoringConfigGroup cnScoringGroup, TollHandler tollHandler) { this.timeCalculator = timeCalculator; this.marginalUtlOfMoney = cnScoringGroup.getMarginalUtilityOfMoney(); this.distanceCostRateCar = cnScoringGroup.getModes().get(TransportMode.car).getMonetaryDistanceRate(); // ignores cnScoringGroup.getModes().get(TransportMode.car).getMarginalUtilityOfDistance(); this.marginalUtlOfTravelTime = (-cnScoringGroup.getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() / 3600.0) + (cnScoringGroup.getPerforming_utils_hr() / 3600.0); this.tollHandler = tollHandler; - + log.info("The 'blend factor' which is used for the calculation of the expected tolls in the next iteration is set to " + this.blendFactor); } @Override public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle v) { - + double linkTravelTime = this.timeCalculator.getLinkTravelTime(link, time, person, v); double linkTravelTimeDisutility = this.marginalUtlOfTravelTime * linkTravelTime ; @@ -78,7 +78,7 @@ public double getLinkTravelDisutility(final Link link, final double time, final double linkDistanceDisutility = this.marginalUtlOfMoney * distanceCost; double linkExpectedTollDisutility = calculateExpectedTollDisutility(link, time, person); - + double linkTravelDisutility = linkTravelTimeDisutility + linkDistanceDisutility + linkExpectedTollDisutility; return linkTravelDisutility; @@ -88,21 +88,21 @@ private double calculateExpectedTollDisutility(Link link, double time, Person pe /* The following is an estimate of the tolls that an agent would have to pay if choosing that link in the next iteration i based on the tolls in iteration i-1 and i-2 */ - + double linkExpectedTollNewValue = this.tollHandler.getAvgToll(link.getId(), time); double linkExpectedTollOldValue = this.tollHandler.getAvgTollOldValue(link.getId(), time); double blendedOldValue = (1 - blendFactor) * linkExpectedTollOldValue; - double blendedNewValue = blendFactor * linkExpectedTollNewValue; - + double blendedNewValue = blendFactor * linkExpectedTollNewValue; + // if (linkExpectedTollNewValue != 0 || linkExpectedTollOldValue != 0) { // log.info("-----------> Person " + person.getId() + ": Expected toll (new value) on link " + link.getId() + " at " + Time.writeTime(time, Time.TIMEFORMAT_HHMMSS) + ": " + linkExpectedTollNewValue); // log.info("-----------> Person " + person.getId() + ": Expected toll (old value) on link " + link.getId() + " at " + Time.writeTime(time, Time.TIMEFORMAT_HHMMSS) + ": " + linkExpectedTollOldValue); -// +// // log.info("ExpectedToll: " + (blendedNewValue + blendedOldValue) ); // } - - double linkExpectedTollDisutility = -1 * this.marginalUtlOfMoney * (blendedOldValue + blendedNewValue); + + double linkExpectedTollDisutility = -1 * this.marginalUtlOfMoney * (blendedOldValue + blendedNewValue); return linkExpectedTollDisutility; } diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/CommuterDemandWriter.java b/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/CommuterDemandWriter.java index 0a3c94df2f4..10f4c106725 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/CommuterDemandWriter.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/CommuterDemandWriter.java @@ -59,7 +59,7 @@ /** * @author jbischoff * @author dgrether - * + * */ public class CommuterDemandWriter { @@ -122,8 +122,8 @@ public void computeDemand(Scenario scenario) { private void generatePopulation(Scenario scenario) { final FreespeedTravelTimeAndDisutility timeCostCalc = new FreespeedTravelTimeAndDisutility(scenario.getConfig() - .planCalcScore()); - PlanAlgorithm router = + .scoring()); + PlanAlgorithm router = new PlanRouter( new TripRouterFactoryBuilderWithDefaults().build( scenario ).get( diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/PersonRouterFilter.java b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/PersonRouterFilter.java index 6b574ed8aa4..ab638409f4d 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/PersonRouterFilter.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/PersonRouterFilter.java @@ -29,7 +29,7 @@ import org.matsim.api.core.v01.network.Node; import org.matsim.api.core.v01.population.Activity; 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.network.NetworkUtils; import org.matsim.core.router.DijkstraFactory; import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; @@ -40,20 +40,20 @@ import playground.vsp.pipeline.PersonSinkSource; public class PersonRouterFilter implements PersonSinkSource { - + private Network network; - + private LeastCostPathCalculator dijkstra; - + private PersonSink sink; - + private Collection interestingNodeIds = new HashSet(); - + double travelTimeToEntry = 0.0; - + public PersonRouterFilter(Network network) { this.network = network; - FreespeedTravelTimeAndDisutility fttc = new FreespeedTravelTimeAndDisutility(new PlanCalcScoreConfigGroup()); + FreespeedTravelTimeAndDisutility fttc = new FreespeedTravelTimeAndDisutility(new ScoringConfigGroup()); dijkstra = new DijkstraFactory().createPathCalculator(network, fttc, fttc); } @@ -97,7 +97,7 @@ public void process(Person person) { public void setSink(PersonSink sink) { this.sink = sink; } - + private static double calculateFreespeedTravelTimeToNode(Network network, Path path, Node node) { double travelTime = 0.0; for (Link l : path.links) { diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/RouterFilter.java b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/RouterFilter.java index 6a7385c635c..f90921cf67c 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/RouterFilter.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/RouterFilter.java @@ -29,7 +29,7 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.router.DijkstraFactory; import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; @@ -50,16 +50,16 @@ public class RouterFilter implements TripFlowSink { private TripFlowSink sink; private Collection interestingNodeIds = new HashSet(); - + private double travelTimeToLink = 0.0; - + private Coord entryCoord; - + private final Scenario sc ; public RouterFilter(Network network) { this.network = network; - FreespeedTravelTimeAndDisutility fttc = new FreespeedTravelTimeAndDisutility(new PlanCalcScoreConfigGroup()); + FreespeedTravelTimeAndDisutility fttc = new FreespeedTravelTimeAndDisutility(new ScoringConfigGroup()); dijkstra = new DijkstraFactory().createPathCalculator(network, fttc, fttc); this.sc = ScenarioUtils.createScenario(ConfigUtils.createConfig()) ; } @@ -73,7 +73,7 @@ public void process(ActivityFacility quelle, ActivityFacility ziel, int quantity if (isInteresting(path)) { // Facility newQuelle = new Zone(quelle.getId(), quelle.workplaces, quelle.workingPopulation, entryCoord); ActivityFacility newQuelle = factory.createActivityFacility(quelle.getId(), quelle.getCoord() ) ; - for ( ActivityOption option : quelle.getActivityOptions().values() ) { + for ( ActivityOption option : quelle.getActivityOptions().values() ) { newQuelle.addActivityOption(option) ; } diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/TravelTimeToWorkCalculator.java b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/TravelTimeToWorkCalculator.java index 9792acd66b1..a2d26868067 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/TravelTimeToWorkCalculator.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/TravelTimeToWorkCalculator.java @@ -3,7 +3,7 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.router.DijkstraFactory; import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; @@ -21,7 +21,7 @@ public class TravelTimeToWorkCalculator implements TripFlowSink { public TravelTimeToWorkCalculator(Network network) { this.network = network; - FreespeedTravelTimeAndDisutility fttc = new FreespeedTravelTimeAndDisutility(new PlanCalcScoreConfigGroup()); + FreespeedTravelTimeAndDisutility fttc = new FreespeedTravelTimeAndDisutility(new ScoringConfigGroup()); dijkstra = new DijkstraFactory().createPathCalculator(network, fttc, fttc); } diff --git a/contribs/vsp/src/main/java/playground/vsp/ev/RunUrbanEVExample.java b/contribs/vsp/src/main/java/playground/vsp/ev/RunUrbanEVExample.java index 7a897d37cc4..e5b374733f6 100644 --- a/contribs/vsp/src/main/java/playground/vsp/ev/RunUrbanEVExample.java +++ b/contribs/vsp/src/main/java/playground/vsp/ev/RunUrbanEVExample.java @@ -43,7 +43,6 @@ import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.matsim.api.core.v01.Id; @@ -51,23 +50,19 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.Person; import org.matsim.contrib.ev.EvConfigGroup; -import org.matsim.contrib.ev.EvModule; import org.matsim.contrib.ev.fleet.ElectricVehicleSpecifications; 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.config.groups.QSimConfigGroup; import org.matsim.core.controler.Controler; -import org.matsim.core.mobsim.qsim.AbstractQSimModule; -import org.matsim.core.mobsim.qsim.components.QSimComponentsConfigGroup; -import org.matsim.core.modal.AbstractModalQSimModule; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; import org.matsim.vehicles.VehiclesFactory; -import static org.matsim.core.config.groups.PlanCalcScoreConfigGroup.*; +import static org.matsim.core.config.groups.ScoringConfigGroup.*; /** * this is an example of how to run MATSim with the UrbanEV module which inserts charging activities for all legs which use a EV. @@ -113,12 +108,12 @@ private static Config prepareConfig( String[] args ){ urbanEVConfig.setCriticalSOC(0.4); //TODO actually, should also work with all AccessEgressTypes but we have to check (write JUnit test) - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.none ); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.none ); //register charging interaction activities for car - config.planCalcScore().addActivityParams( + config.scoring().addActivityParams( new ActivityParams(TransportMode.car + UrbanEVModule.PLUGOUT_INTERACTION).setScoringThisActivityAtAll(false ) ); - config.planCalcScore().addActivityParams( + config.scoring().addActivityParams( new ActivityParams( TransportMode.car + UrbanEVModule.PLUGIN_INTERACTION).setScoringThisActivityAtAll( false ) ); return config; } diff --git a/contribs/vsp/src/main/java/playground/vsp/ev/UrbanEVModule.java b/contribs/vsp/src/main/java/playground/vsp/ev/UrbanEVModule.java index 7f64ae48d74..84e59275d7b 100644 --- a/contribs/vsp/src/main/java/playground/vsp/ev/UrbanEVModule.java +++ b/contribs/vsp/src/main/java/playground/vsp/ev/UrbanEVModule.java @@ -20,11 +20,6 @@ package playground.vsp.ev; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.matsim.contrib.ev.EvModule; import org.matsim.contrib.ev.charging.ChargingModule; import org.matsim.contrib.ev.discharging.DischargingModule; @@ -33,20 +28,19 @@ import org.matsim.contrib.ev.stats.EvStatsModule; 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.AbstractModule; import org.matsim.core.mobsim.qsim.AbstractQSimModule; import com.google.inject.Inject; import com.google.inject.Singleton; import org.matsim.core.mobsim.qsim.components.QSimComponentsConfigGroup; -import org.matsim.core.modal.AbstractModalQSimModule; public class UrbanEVModule extends AbstractModule { static final String PLUGIN_IDENTIFIER = " plugin"; - public static final String PLUGIN_INTERACTION = PlanCalcScoreConfigGroup.createStageActivityType( PLUGIN_IDENTIFIER ); + public static final String PLUGIN_INTERACTION = ScoringConfigGroup.createStageActivityType( PLUGIN_IDENTIFIER ); static final String PLUGOUT_IDENTIFIER = " plugout"; - public static final String PLUGOUT_INTERACTION = PlanCalcScoreConfigGroup.createStageActivityType( PLUGOUT_IDENTIFIER ); + public static final String PLUGOUT_INTERACTION = ScoringConfigGroup.createStageActivityType( PLUGOUT_IDENTIFIER ); @Inject private Config config; @Override public void install() { diff --git a/contribs/vsp/src/main/java/playground/vsp/ev/UrbanEVTripsPlanner.java b/contribs/vsp/src/main/java/playground/vsp/ev/UrbanEVTripsPlanner.java index 388a93768dd..0449190e8f6 100644 --- a/contribs/vsp/src/main/java/playground/vsp/ev/UrbanEVTripsPlanner.java +++ b/contribs/vsp/src/main/java/playground/vsp/ev/UrbanEVTripsPlanner.java @@ -61,7 +61,7 @@ import org.matsim.contrib.ev.infrastructure.ChargerSpecification; import org.matsim.contrib.ev.infrastructure.ChargingInfrastructureSpecification; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.IterationCounter; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.mobsim.framework.MobsimAgent; @@ -196,7 +196,7 @@ private void processPlans(Map>> selectedEVPlans) { Plan modifiablePlan = WithinDayAgentUtils.getModifiablePlan(mobsimagent); TripRouter tripRouter = tripRouterProvider.get(); Set modesWithVehicles = new HashSet<>(scenario.getConfig().qsim().getMainModes()); - modesWithVehicles.addAll(scenario.getConfig().plansCalcRoute().getNetworkModes()); + modesWithVehicles.addAll(scenario.getConfig().routing().getNetworkModes()); for (Id ev : selectedEVPlans.get(plan)) { //only replan cnt times per vehicle and person. otherwise, there might be a leg which is just too long and we end up in an infinity loop... @@ -350,7 +350,7 @@ private Leg getCriticalOrLastEvLeg(Plan modifiablePlan, ElectricVehicle pseudoVe Double chargingBegin = null; Set modesWithVehicles = new HashSet<>(scenario.getConfig().qsim().getMainModes()); - modesWithVehicles.addAll(scenario.getConfig().plansCalcRoute().getNetworkModes()); + modesWithVehicles.addAll(scenario.getConfig().routing().getNetworkModes()); Leg lastLegWithVehicle = null; @@ -451,7 +451,7 @@ private boolean replanPrecedentAndCurrentEVLegs(MobsimAgent mobsimagent, Plan mo Activity plugoutTripDestination = findRealOrChargingActAfter(mobsimagent, modifiablePlan.getPlanElements().indexOf(plugoutLeg)); { //some consistency checks.. //TODO consider to put in a JUnit test.. - int offset = config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ? 1 : 3; + int offset = config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ? 1 : 3; Preconditions.checkNotNull(pluginTripOrigin, "pluginTripOrigin is null. should never happen.."); Preconditions.checkState(!pluginTripOrigin.equals(actWhileCharging), diff --git a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/planmodification/SplitActivityTypesBasedOnDuration.java b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/planmodification/SplitActivityTypesBasedOnDuration.java index 43bb865b863..045304706fe 100644 --- a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/planmodification/SplitActivityTypesBasedOnDuration.java +++ b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/planmodification/SplitActivityTypesBasedOnDuration.java @@ -28,8 +28,8 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.ConfigWriter; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.TypicalDurationScoreComputation; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.TypicalDurationScoreComputation; import org.matsim.core.population.io.PopulationWriter; import org.matsim.core.scenario.ScenarioUtils; @@ -42,7 +42,7 @@ public class SplitActivityTypesBasedOnDuration { private final Logger log = LogManager.getLogger(SplitActivityTypesBasedOnDuration.class); private Scenario scenario; - + public SplitActivityTypesBasedOnDuration(String inputPopulationFile) { Config config = ConfigUtils.createConfig(); config.plans().setInputFile(inputPopulationFile); @@ -53,46 +53,46 @@ public static void main(String[] args) { final String inputPopulationFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/plans_500_10-1_10pct_clc.xml.gz"; final String outputPopulationFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/plans_500_10-1_10pct_clc_act-split.xml.gz"; final String outputConfigFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/config_act-split.xml"; - + final double timeBinSize_s = 600.; - final String[] activityTypes = {ActivityTypes.HOME, ActivityTypes.WORK, ActivityTypes.EDUCATION, ActivityTypes.LEISURE, ActivityTypes.SHOPPING, ActivityTypes.OTHER}; - + final String[] activityTypes = {ActivityTypes.HOME, ActivityTypes.WORK, ActivityTypes.EDUCATION, ActivityTypes.LEISURE, ActivityTypes.SHOPPING, ActivityTypes.OTHER}; + SplitActivityTypesBasedOnDuration splitAct = new SplitActivityTypesBasedOnDuration(inputPopulationFile); splitAct.run(outputPopulationFile, outputConfigFile, timeBinSize_s, activityTypes, 0.0); } public void run(String outputPopulationFile, String outputConfigFile, double timeBinSize_s, String[] activities, double dayStartTime) { - + CemdapPopulationTools tools = new CemdapPopulationTools(); tools.setActivityTypesAccordingToDurationAndMergeOvernightActivities(scenario.getPopulation(), timeBinSize_s, dayStartTime); - + PopulationWriter writer = new PopulationWriter(scenario.getPopulation()); writer.write(outputPopulationFile); - + // Config List initialActivityParams = new ArrayList<>(); - + log.info("Initial activity parameters: "); for (String activity : activities) { ActivityParams params = new ActivityParams(activity); initialActivityParams.add(params); log.info(" -> " + params.getActivityType()); } - + log.info("Adding duration-specific activity types to config..."); - + List newActivityParams = new ArrayList<>(); - + for (ActivityParams actParams : initialActivityParams) { String activityType = actParams.getActivityType(); - + if (activityType.contains("interaction")) { log.info("Skipping activity " + activityType + "..."); } else { log.info("Splitting activity " + activityType + " in duration-specific activities."); double maximumDuration = tools.getMaxEndTime(); - + for (double n = timeBinSize_s; n <= maximumDuration ; n = n + timeBinSize_s) { ActivityParams params = new ActivityParams(activityType + "_" + n); params.setTypicalDuration(n); @@ -101,19 +101,19 @@ public void run(String outputPopulationFile, String outputConfigFile, double tim } } } - + for (ActivityParams actParams : newActivityParams) { - scenario.getConfig().planCalcScore().addActivityParams(actParams); + scenario.getConfig().scoring().addActivityParams(actParams); } - + log.info("New activity parameters: "); - for (ActivityParams actParams : scenario.getConfig().planCalcScore().getActivityParams()) { + for (ActivityParams actParams : scenario.getConfig().scoring().getActivityParams()) { initialActivityParams.add(actParams); log.info(" -> " + actParams.getActivityType()); } - + log.info("Adding duration-specific activity types to config... Done."); ConfigWriter configWriter = new ConfigWriter(scenario.getConfig()); configWriter.write(outputConfigFile); } -} \ No newline at end of file +} diff --git a/contribs/vsp/src/main/java/playground/vsp/parkAndRide/example/PRRunner.java b/contribs/vsp/src/main/java/playground/vsp/parkAndRide/example/PRRunner.java index 36a22a46b14..b3cebe02ae9 100644 --- a/contribs/vsp/src/main/java/playground/vsp/parkAndRide/example/PRRunner.java +++ b/contribs/vsp/src/main/java/playground/vsp/parkAndRide/example/PRRunner.java @@ -19,7 +19,7 @@ * *********************************************************************** */ /** - * + * */ package playground.vsp.parkAndRide.example; @@ -30,7 +30,7 @@ import org.matsim.api.core.v01.Id; 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.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -52,25 +52,25 @@ * */ public class PRRunner { - + static String configFile; - + public static void main(String[] args) throws IOException { - + configFile = "/path-to/config.xml"; - + PRRunner main = new PRRunner(); main.run(); } - + private void run() { - + Config config = new Config(); config.addModule(new PRConfigGroup()); ConfigUtils.loadConfig(config, configFile); - + final Controler controler = new Controler(config); - controler.getConfig().controler().setOverwriteFileSetting( + controler.getConfig().controller().setOverwriteFileSetting( true ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists ); @@ -79,10 +79,10 @@ private void run() { ActivityParams prActivityParams = new ActivityParams(PRConstants.PARKANDRIDE_ACTIVITY_TYPE); prActivityParams.setTypicalDuration(prSettings.getTypicalDuration()); - controler.getConfig().planCalcScore().addActivityParams(prActivityParams); + controler.getConfig().scoring().addActivityParams(prActivityParams); controler.setScoringFunctionFactory(new PRScoringFunctionFactory(controler.getScenario(), prSettings.getIntermodalTransferPenalty())); - + PRFileReader prReader = new PRFileReader(prSettings.getInputFile()); Map, PRFacility> id2prFacility = prReader.getId2prFacility(); final PRAdaptiveCapacityControl adaptiveControl = new PRAdaptiveCapacityControl(id2prFacility); @@ -105,8 +105,8 @@ public Mobsim get() { }); controler.run(); - + } } - + diff --git a/contribs/vsp/src/main/java/playground/vsp/planselectors/InitialPlanKeeperPlanRemoval.java b/contribs/vsp/src/main/java/playground/vsp/planselectors/InitialPlanKeeperPlanRemoval.java index eb5c39bd9cd..e99af53d6cc 100644 --- a/contribs/vsp/src/main/java/playground/vsp/planselectors/InitialPlanKeeperPlanRemoval.java +++ b/contribs/vsp/src/main/java/playground/vsp/planselectors/InitialPlanKeeperPlanRemoval.java @@ -24,12 +24,11 @@ import java.util.Objects; import jakarta.inject.Inject; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.population.HasPlansAndId; 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.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.replanning.selectors.PlanSelector; import org.matsim.core.replanning.selectors.WorstPlanForRemovalSelector; @@ -48,13 +47,13 @@ public class InitialPlanKeeperPlanRemoval implements PlanSelector private final WorstPlanForRemovalSelector delegate; @Inject - public InitialPlanKeeperPlanRemoval(StrategyConfigGroup strategyConfigGroup, Population population){ + public InitialPlanKeeperPlanRemoval(ReplanningConfigGroup replanningConfigGroup, Population population){ this.delegate = new WorstPlanForRemovalSelector(); - if ( strategyConfigGroup.getMaxAgentPlanMemorySize() < 12) { + if ( replanningConfigGroup.getMaxAgentPlanMemorySize() < 12) { LogManager.getLogger(InitialPlanKeeperPlanRemoval.class).warn("A plans remover is used which keeps the initial plans or at least their copy \n " + - "and maximum number of plans in the choice set is limited to "+ strategyConfigGroup.getMaxAgentPlanMemorySize()+ + "and maximum number of plans in the choice set is limited to "+ replanningConfigGroup.getMaxAgentPlanMemorySize()+ ".\n Lower number of plans in choice set is likely to end up in infinite loop. Setting it to 15."); - strategyConfigGroup.setMaxAgentPlanMemorySize(15); + replanningConfigGroup.setMaxAgentPlanMemorySize(15); } for (Person person : population.getPersons().values()){ diff --git a/contribs/vsp/src/main/java/playground/vsp/pt/fare/PtFareModule.java b/contribs/vsp/src/main/java/playground/vsp/pt/fare/PtFareModule.java index 47753e0559f..9bd25cc81f4 100644 --- a/contribs/vsp/src/main/java/playground/vsp/pt/fare/PtFareModule.java +++ b/contribs/vsp/src/main/java/playground/vsp/pt/fare/PtFareModule.java @@ -8,8 +8,8 @@ public class PtFareModule extends AbstractModule { @Override public void install() { - getConfig().planCalcScore().getModes().get(TransportMode.pt).setDailyMonetaryConstant(0); - getConfig().planCalcScore().getModes().get(TransportMode.pt).setMarginalUtilityOfDistance(0); + getConfig().scoring().getModes().get(TransportMode.pt).setDailyMonetaryConstant(0); + getConfig().scoring().getModes().get(TransportMode.pt).setMarginalUtilityOfDistance(0); PtFareConfigGroup ptFareConfigGroup = ConfigUtils.addOrGetModule(this.getConfig(), PtFareConfigGroup.class); if (ptFareConfigGroup.getPtFareCalculation() == PtFareConfigGroup.PtFareCalculationModels.distanceBased) { DistanceBasedPtFareParams distanceBasedPtFareParams = ConfigUtils.addOrGetModule(this.getConfig(), DistanceBasedPtFareParams.class); diff --git a/contribs/vsp/src/main/java/playground/vsp/randomizedtransitrouter/RunOTFVisDebugRandomizedTransitRouterTravelTimeAndDisutility.java b/contribs/vsp/src/main/java/playground/vsp/randomizedtransitrouter/RunOTFVisDebugRandomizedTransitRouterTravelTimeAndDisutility.java deleted file mode 100644 index 88515eab97e..00000000000 --- a/contribs/vsp/src/main/java/playground/vsp/randomizedtransitrouter/RunOTFVisDebugRandomizedTransitRouterTravelTimeAndDisutility.java +++ /dev/null @@ -1,101 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * RunOTFVisDebugRandomizedTransitRouter - * * - * *********************************************************************** * - * * - * 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 playground.vsp.randomizedtransitrouter; - -import org.matsim.api.core.v01.Scenario; -import org.matsim.contrib.common.randomizedtransitrouter.RandomizingTransitRouterModule; -import org.matsim.contrib.otfvis.OTFVis; -import org.matsim.core.api.experimental.events.EventsManager; -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.framework.Mobsim; -import org.matsim.core.mobsim.framework.MobsimFactory; -import org.matsim.core.mobsim.qsim.QSim; -import org.matsim.core.mobsim.qsim.QSimBuilder; -import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.vis.otfvis.OTFClientLive; -import org.matsim.vis.otfvis.OTFVisConfigGroup; -import org.matsim.vis.otfvis.OnTheFlyServer; - -import com.google.inject.Provider; - - -/** - * @author dgrether - * - */ -public class RunOTFVisDebugRandomizedTransitRouterTravelTimeAndDisutility { - - - public static void main(String[] args) { - final Config config = ConfigUtils.loadConfig(args[0]) ; - - boolean doVisualization = true; - - config.planCalcScore().setWriteExperiencedPlans(true) ; - - ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class).setDrawTransitFacilities(true) ; // this DOES work - ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class).setDrawTransitFacilityIds(false); - ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class).setShowTeleportedAgents(true) ; - ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class).setDrawNonMovingItems(true); - ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class).setScaleQuadTreeRect(true); - - final Scenario scenario = ScenarioUtils.loadScenario(config) ; - - final Controler ctrl = new Controler(scenario) ; - - ctrl.getConfig().controler().setOverwriteFileSetting( - true ? - OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles : - OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists ); - - ctrl.addOverridingModule(new RandomizingTransitRouterModule()); - - if (doVisualization){ - ctrl.addOverridingModule(new AbstractModule() { - @Override - public void install() { - bindMobsim().toProvider(new Provider() { - @Override - public Mobsim get() { - return new MobsimFactory() { - - @Override - public Mobsim createMobsim(final Scenario sc, final EventsManager eventsManager) { - final QSim qSim = new QSimBuilder(sc.getConfig()).useDefaults().build(sc, eventsManager); - - final OnTheFlyServer server = OTFVis.startServerAndRegisterWithQSim(sc.getConfig(), sc, eventsManager, qSim); - OTFClientLive.run(sc.getConfig(), server); - - return qSim; - } - }.createMobsim(ctrl.getScenario(), ctrl.getEvents()); - } - }); - } - }); - } - ctrl.run() ; - - } -} diff --git a/contribs/vsp/src/main/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParameters.java b/contribs/vsp/src/main/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParameters.java index 2c6398f2937..c25bed0527a 100644 --- a/contribs/vsp/src/main/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParameters.java +++ b/contribs/vsp/src/main/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParameters.java @@ -24,7 +24,7 @@ import org.matsim.api.core.v01.IdMap; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.ScenarioConfigGroup; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; @@ -56,7 +56,7 @@ */ public class IncomeDependentUtilityOfMoneyPersonScoringParameters implements ScoringParametersForPerson { Logger log = LogManager.getLogger(IncomeDependentUtilityOfMoneyPersonScoringParameters.class); - private final PlanCalcScoreConfigGroup config; + private final ScoringConfigGroup config; private final ScenarioConfigGroup scConfig; private final TransitConfigGroup transitConfigGroup; private final Map, ScoringParameters> params = new IdMap<>(Person.class); @@ -64,8 +64,8 @@ public class IncomeDependentUtilityOfMoneyPersonScoringParameters implements Sco private final Map> activityParamsPerSubpopulation = new ConcurrentHashMap<>(); @Inject - IncomeDependentUtilityOfMoneyPersonScoringParameters(Population population, PlanCalcScoreConfigGroup planCalcScoreConfigGroup, ScenarioConfigGroup scenarioConfigGroup, TransitConfigGroup transitConfigGroup) { - this.config = planCalcScoreConfigGroup; + IncomeDependentUtilityOfMoneyPersonScoringParameters(Population population, ScoringConfigGroup scoringConfigGroup, ScenarioConfigGroup scenarioConfigGroup, TransitConfigGroup transitConfigGroup) { + this.config = scoringConfigGroup; this.scConfig = scenarioConfigGroup; this.transitConfigGroup = transitConfigGroup; this.globalAvgIncome = computeAvgIncome(population); @@ -110,13 +110,13 @@ public ScoringParameters getScoringParameters(Person person) { * point of view than giving each ScoringFunction its own copy of the params. */ - PlanCalcScoreConfigGroup.ScoringParameterSet subpopulationScoringParams = this.config.getScoringParameters(subpopulation); + ScoringConfigGroup.ScoringParameterSet subpopulationScoringParams = this.config.getScoringParameters(subpopulation); // (we can set scoring params per subpopulation, so retrieve them as starting point. kai, apr'22) // save the activityParams of the subpopulation so we need to build them only once. this.activityParamsPerSubpopulation.computeIfAbsent(subpopulation, k -> { Map activityParams = new TreeMap<>(); - for (PlanCalcScoreConfigGroup.ActivityParams params : subpopulationScoringParams.getActivityParams()) { + for (ScoringConfigGroup.ActivityParams params : subpopulationScoringParams.getActivityParams()) { ActivityUtilityParameters.Builder factory = new ActivityUtilityParameters.Builder(params); activityParams.put(params.getActivityType(), factory.build()); } @@ -130,7 +130,7 @@ public ScoringParameters getScoringParameters(Person person) { if (transitConfigGroup.isUseTransit()) { // this is the PT stage activity: - PlanCalcScoreConfigGroup.ActivityParams transitActivityParams = new PlanCalcScoreConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); + ScoringConfigGroup.ActivityParams transitActivityParams = new ScoringConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); transitActivityParams.setTypicalDuration(120.0); transitActivityParams.setOpeningTime(0.); transitActivityParams.setClosingTime(0.); diff --git a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/MyServiceTrackerEventHandler.java b/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/MyServiceTrackerEventHandler.java deleted file mode 100644 index ed20e653f1f..00000000000 --- a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/MyServiceTrackerEventHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.matsim.contrib.freight.analysis; - -import org.matsim.api.core.v01.events.ActivityStartEvent; -import org.matsim.api.core.v01.events.handler.ActivityStartEventHandler; -import org.matsim.api.core.v01.network.Network; -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.events.CarrierServiceEndEvent; -import org.matsim.contrib.freight.events.CarrierServiceStartEvent; -import org.matsim.contrib.freight.events.eventhandler.FreightServiceEndEventHandler; -import org.matsim.contrib.freight.events.eventhandler.FreightServiceStartEventHandler; -import org.matsim.vehicles.Vehicles; - - class MyServiceTrackerEventHandler implements ActivityStartEventHandler, FreightServiceStartEventHandler, FreightServiceEndEventHandler { - private final Vehicles vehicles; - private final Network network; - private final Carriers carriers; - - private FreightAnalysisServiceTracking serviceTracking = new FreightAnalysisServiceTracking(); - - MyServiceTrackerEventHandler(Vehicles vehicles, Network network, Carriers carriers) { - this.network = network; - this.carriers = carriers; - this.vehicles = vehicles; - this.init(); - } - - private void init() { - for (Carrier carrier : carriers.getCarriers().values()) { - - for (CarrierService service : carrier.getServices().values()) { - serviceTracking.addTracker(service, carrier.getId()); - } - } - serviceTracking.estimateArrivalTimes(carriers); - } - - @Override - public void handleEvent(CarrierServiceEndEvent event) { - serviceTracking.handleEndEvent(event); - } - - @Override - public void handleEvent(CarrierServiceStartEvent event) { - serviceTracking.handleStartEvent(event); - } - - @Override - public void handleEvent(ActivityStartEvent activityStartEvent) { - if (activityStartEvent.getActType().equals("service")) { - serviceTracking.trackServiceActivityStart(activityStartEvent); - } - } - - public FreightAnalysisServiceTracking getServiceTracking() { - return serviceTracking; - } -} diff --git a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/MyShipmentTrackerEventHandler.java b/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/MyShipmentTrackerEventHandler.java deleted file mode 100644 index 6b2409d7e3d..00000000000 --- a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/MyShipmentTrackerEventHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.matsim.contrib.freight.analysis; - -import org.matsim.api.core.v01.events.ActivityStartEvent; -import org.matsim.api.core.v01.events.handler.ActivityStartEventHandler; -import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.Carrier; -import org.matsim.contrib.freight.carrier.CarrierShipment; -import org.matsim.contrib.freight.carrier.Carriers; -import org.matsim.contrib.freight.events.CarrierShipmentDeliveryEndEvent; -import org.matsim.contrib.freight.events.CarrierShipmentPickupEndEvent; -import org.matsim.contrib.freight.events.eventhandler.FreightShipmentDeliveryEventHandler; -import org.matsim.contrib.freight.events.eventhandler.FreightShipmentPickupEventHandler; -import org.matsim.vehicles.Vehicles; - -public class MyShipmentTrackerEventHandler implements ActivityStartEventHandler, FreightShipmentPickupEventHandler, FreightShipmentDeliveryEventHandler { - - private final Vehicles vehicles; - private final Network network; - private final Carriers carriers; - - private FreightAnalysisShipmentTracking shipmentTracking = new FreightAnalysisShipmentTracking(); - - MyShipmentTrackerEventHandler(Vehicles vehicles, Network network, Carriers carriers) { - this.network = network; - this.carriers = carriers; - this.vehicles = vehicles; - this.init(); - } - - private void init(){ - for (Carrier carrier : carriers.getCarriers().values()) { - // for all shipments and services of the carriers, tracking is started here. - for (CarrierShipment shipment : carrier.getShipments().values()) { - shipmentTracking.addTracker(shipment); - } - } - } - - @Override - public void handleEvent(CarrierShipmentDeliveryEndEvent event) { - shipmentTracking.trackDeliveryEvent(event); - } - - @Override - public void handleEvent(CarrierShipmentPickupEndEvent event) { - shipmentTracking.trackPickedUpEvent(event); - } - - @Override - public void reset(int iteration) { - FreightShipmentPickupEventHandler.super.reset(iteration); - } - - @Override - public void handleEvent(ActivityStartEvent activityStartEvent) { - - if (activityStartEvent.getActType().equals("delivery")) { - shipmentTracking.trackDeliveryActivity(activityStartEvent); - } - - if (activityStartEvent.getActType().equals("pickup")){ - shipmentTracking.trackPickupActivity(activityStartEvent); - } - - } - - public FreightAnalysisShipmentTracking getShipmentTracker(){ - return shipmentTracking; - } -} diff --git a/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesIT.java b/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesIT.java index f25b4e54347..7d838d4178a 100644 --- a/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesIT.java +++ b/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesIT.java @@ -48,10 +48,10 @@ public class PersonScoringParametersFromPersonAttributesIT { @Test public void testSetAttributeAndRunEquil(){ Config config = testUtils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); - config.controler().setLastIteration(0); - config.planCalcScore().setPerforming_utils_hr(0.0d); - config.planCalcScore().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(0.0d); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setLastIteration(0); + config.scoring().setPerforming_utils_hr(0.0d); + config.scoring().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(0.0d); config.plans().setInputFile("plans2.xml"); Scenario scenario = ScenarioUtils.loadScenario(config); diff --git a/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesNoSubpopulationTest.java b/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesNoSubpopulationTest.java index 4085cb20f81..bb9ca23ac4a 100644 --- a/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesNoSubpopulationTest.java +++ b/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesNoSubpopulationTest.java @@ -27,7 +27,7 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.*; 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.ScenarioConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PersonUtils; @@ -59,13 +59,13 @@ public class PersonScoringParametersFromPersonAttributesNoSubpopulationTest { public void setUp() { TransitConfigGroup transitConfigGroup = new TransitConfigGroup(); ScenarioConfigGroup scenarioConfigGroup = new ScenarioConfigGroup(); - PlanCalcScoreConfigGroup planCalcScoreConfigGroup = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup scoringConfigGroup = new ScoringConfigGroup(); - PlanCalcScoreConfigGroup.ScoringParameterSet personParams = planCalcScoreConfigGroup.getOrCreateScoringParameters(null); + ScoringConfigGroup.ScoringParameterSet personParams = scoringConfigGroup.getOrCreateScoringParameters(null); personParams.setMarginalUtilityOfMoney(1); personParams.setMarginalUtlOfWaitingPt_utils_hr(0.5 * 3600); - PlanCalcScoreConfigGroup.ModeParams modeParamsCar = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.car); + ScoringConfigGroup.ModeParams modeParamsCar = new ScoringConfigGroup.ModeParams(TransportMode.car); modeParamsCar.setConstant(-1.0); modeParamsCar.setMarginalUtilityOfTraveling(-0.001); modeParamsCar.setMarginalUtilityOfDistance(-0.002); @@ -74,7 +74,7 @@ public void setUp() { modeParamsCar.setDailyUtilityConstant(-0.3); personParams.addModeParams(modeParamsCar); - PlanCalcScoreConfigGroup.ModeParams modeParamsBike = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.bike); + ScoringConfigGroup.ModeParams modeParamsBike = new ScoringConfigGroup.ModeParams(TransportMode.bike); modeParamsBike.setConstant(-0.55); modeParamsBike.setMarginalUtilityOfTraveling(-0.05); modeParamsBike.setMarginalUtilityOfDistance(-0.003); @@ -118,7 +118,7 @@ public void setUp() { } personScoringParams = new PersonScoringParametersFromPersonAttributes(population, - planCalcScoreConfigGroup, + scoringConfigGroup, scenarioConfigGroup, transitConfigGroup); } @@ -228,4 +228,4 @@ private void makeAssertMarginalUtilityOfMoneyAndPtWait(ScoringParameters params, } -} \ No newline at end of file +} diff --git a/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesTest.java b/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesTest.java index a11283749de..cb7da7c9069 100644 --- a/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesTest.java +++ b/contribs/vsp/src/test/java/org/matsim/core/scoring/functions/PersonScoringParametersFromPersonAttributesTest.java @@ -27,7 +27,7 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.*; 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.ScenarioConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PersonUtils; @@ -59,13 +59,13 @@ public class PersonScoringParametersFromPersonAttributesTest { public void setUp() { TransitConfigGroup transitConfigGroup = new TransitConfigGroup(); ScenarioConfigGroup scenarioConfigGroup = new ScenarioConfigGroup(); - PlanCalcScoreConfigGroup planCalcScoreConfigGroup = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup scoringConfigGroup = new ScoringConfigGroup(); - PlanCalcScoreConfigGroup.ScoringParameterSet personParams = planCalcScoreConfigGroup.getOrCreateScoringParameters("person"); + ScoringConfigGroup.ScoringParameterSet personParams = scoringConfigGroup.getOrCreateScoringParameters("person"); personParams.setMarginalUtilityOfMoney(1); personParams.setMarginalUtlOfWaitingPt_utils_hr(0.5 * 3600); - PlanCalcScoreConfigGroup.ModeParams modeParamsCar = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.car); + ScoringConfigGroup.ModeParams modeParamsCar = new ScoringConfigGroup.ModeParams(TransportMode.car); modeParamsCar.setConstant(-1.0); modeParamsCar.setMarginalUtilityOfTraveling(-0.001); modeParamsCar.setMarginalUtilityOfDistance(-0.002); @@ -74,14 +74,14 @@ public void setUp() { modeParamsCar.setDailyUtilityConstant(-0.3); personParams.addModeParams(modeParamsCar); - PlanCalcScoreConfigGroup.ModeParams modeParamsBike = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.bike); + ScoringConfigGroup.ModeParams modeParamsBike = new ScoringConfigGroup.ModeParams(TransportMode.bike); modeParamsBike.setConstant(-0.55); modeParamsBike.setMarginalUtilityOfTraveling(-0.05); modeParamsBike.setMarginalUtilityOfDistance(-0.003); modeParamsBike.setMonetaryDistanceRate(-0.002); personParams.addModeParams(modeParamsBike); - PlanCalcScoreConfigGroup.ScoringParameterSet freightParams = planCalcScoreConfigGroup.getOrCreateScoringParameters("freight"); + ScoringConfigGroup.ScoringParameterSet freightParams = scoringConfigGroup.getOrCreateScoringParameters("freight"); freightParams.setMarginalUtilityOfMoney(444); freightParams.setMarginalUtlOfWaitingPt_utils_hr(1d * 3600); @@ -140,7 +140,7 @@ public void setUp() { population.addPerson(freightWithIncome2); } personScoringParams = new PersonScoringParametersFromPersonAttributes(population, - planCalcScoreConfigGroup, + scoringConfigGroup, scenarioConfigGroup, transitConfigGroup); } @@ -268,4 +268,4 @@ private void makeAssertMarginalUtilityOfMoneyAndPtWait(ScoringParameters params, } -} \ No newline at end of file +} diff --git a/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest.java b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest.java new file mode 100644 index 00000000000..b34c72ac10b --- /dev/null +++ b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest.java @@ -0,0 +1,46 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.analysis; + +import org.junit.Rule; +import org.junit.Test; +import org.matsim.testcases.MatsimTestUtils; + +import java.io.IOException; + +public class FreightAnalysisEventBasedTest { + + @Rule + public MatsimTestUtils testUtils = new MatsimTestUtils(); + + @Test + public void runFreightAnalysisEventBasedTest() throws IOException { + + RunFreightAnalysisEventBased analysisEventBased = new RunFreightAnalysisEventBased(testUtils.getClassInputDirectory(), testUtils.getOutputDirectory(),null); + analysisEventBased.runAnalysis(); + + MatsimTestUtils.assertEqualFilesLineByLine(testUtils.getInputDirectory() + "Carrier_stats.tsv", testUtils.getOutputDirectory() + "Carrier_stats.tsv"); + MatsimTestUtils.assertEqualFilesLineByLine(testUtils.getInputDirectory() + "Load_perVehicle.tsv", testUtils.getOutputDirectory() + "Load_perVehicle.tsv"); + MatsimTestUtils.assertEqualFilesLineByLine(testUtils.getInputDirectory() + "TimeDistance_perVehicle.tsv", testUtils.getOutputDirectory() + "TimeDistance_perVehicle.tsv"); + MatsimTestUtils.assertEqualFilesLineByLine(testUtils.getInputDirectory() + "TimeDistance_perVehicleType.tsv", testUtils.getOutputDirectory() + "TimeDistance_perVehicleType.tsv"); + } +} diff --git a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/MyFreightVehicleTrackerEventHandler.java b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/MyFreightVehicleTrackerEventHandler.java similarity index 95% rename from contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/MyFreightVehicleTrackerEventHandler.java rename to contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/MyFreightVehicleTrackerEventHandler.java index 3f28c73967d..239e6573d87 100644 --- a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/MyFreightVehicleTrackerEventHandler.java +++ b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/MyFreightVehicleTrackerEventHandler.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2021 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,12 +19,12 @@ * */ -package org.matsim.contrib.freight.analysis; +package org.matsim.freight.carriers.analysis; import org.matsim.api.core.v01.events.*; import org.matsim.api.core.v01.events.handler.*; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.Carriers; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.Vehicles; diff --git a/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/MyServiceTrackerEventHandler.java b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/MyServiceTrackerEventHandler.java new file mode 100644 index 00000000000..ae51676c57b --- /dev/null +++ b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/MyServiceTrackerEventHandler.java @@ -0,0 +1,80 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.analysis; + +import org.matsim.api.core.v01.events.ActivityStartEvent; +import org.matsim.api.core.v01.events.handler.ActivityStartEventHandler; +import org.matsim.api.core.v01.network.Network; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierService; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.events.CarrierServiceEndEvent; +import org.matsim.freight.carriers.events.CarrierServiceStartEvent; +import org.matsim.freight.carriers.events.eventhandler.CarrierServiceEndEventHandler; +import org.matsim.freight.carriers.events.eventhandler.CarrierServiceStartEventHandler; +import org.matsim.vehicles.Vehicles; + + class MyServiceTrackerEventHandler implements ActivityStartEventHandler, CarrierServiceStartEventHandler, CarrierServiceEndEventHandler { + private final Vehicles vehicles; + private final Network network; + private final Carriers carriers; + + private FreightAnalysisServiceTracking serviceTracking = new FreightAnalysisServiceTracking(); + + MyServiceTrackerEventHandler(Vehicles vehicles, Network network, Carriers carriers) { + this.network = network; + this.carriers = carriers; + this.vehicles = vehicles; + this.init(); + } + + private void init() { + for (Carrier carrier : carriers.getCarriers().values()) { + + for (CarrierService service : carrier.getServices().values()) { + serviceTracking.addTracker(service, carrier.getId()); + } + } + serviceTracking.estimateArrivalTimes(carriers); + } + + @Override + public void handleEvent(CarrierServiceEndEvent event) { + serviceTracking.handleEndEvent(event); + } + + @Override + public void handleEvent(CarrierServiceStartEvent event) { + serviceTracking.handleStartEvent(event); + } + + @Override + public void handleEvent(ActivityStartEvent activityStartEvent) { + if (activityStartEvent.getActType().equals("service")) { + serviceTracking.trackServiceActivityStart(activityStartEvent); + } + } + + public FreightAnalysisServiceTracking getServiceTracking() { + return serviceTracking; + } +} diff --git a/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/MyShipmentTrackerEventHandler.java b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/MyShipmentTrackerEventHandler.java new file mode 100644 index 00000000000..178652c1c7d --- /dev/null +++ b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/MyShipmentTrackerEventHandler.java @@ -0,0 +1,91 @@ +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.analysis; + +import org.matsim.api.core.v01.events.ActivityStartEvent; +import org.matsim.api.core.v01.events.handler.ActivityStartEventHandler; +import org.matsim.api.core.v01.network.Network; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierShipment; +import org.matsim.freight.carriers.Carriers; +import org.matsim.freight.carriers.events.CarrierShipmentDeliveryEndEvent; +import org.matsim.freight.carriers.events.CarrierShipmentPickupEndEvent; +import org.matsim.freight.carriers.events.eventhandler.CarrierShipmentDeliveryEndEventHandler; +import org.matsim.freight.carriers.events.eventhandler.CarrierShipmentPickupEndEventHandler; +import org.matsim.vehicles.Vehicles; + +public class MyShipmentTrackerEventHandler implements ActivityStartEventHandler, CarrierShipmentPickupEndEventHandler, CarrierShipmentDeliveryEndEventHandler { + + private final Vehicles vehicles; + private final Network network; + private final Carriers carriers; + + private FreightAnalysisShipmentTracking shipmentTracking = new FreightAnalysisShipmentTracking(); + + MyShipmentTrackerEventHandler(Vehicles vehicles, Network network, Carriers carriers) { + this.network = network; + this.carriers = carriers; + this.vehicles = vehicles; + this.init(); + } + + private void init(){ + for (Carrier carrier : carriers.getCarriers().values()) { + // for all shipments and services of the carriers, tracking is started here. + for (CarrierShipment shipment : carrier.getShipments().values()) { + shipmentTracking.addTracker(shipment); + } + } + } + + @Override + public void handleEvent(CarrierShipmentDeliveryEndEvent event) { + shipmentTracking.trackDeliveryEvent(event); + } + + @Override + public void handleEvent(CarrierShipmentPickupEndEvent event) { + shipmentTracking.trackPickedUpEvent(event); + } + + @Override + public void reset(int iteration) { + CarrierShipmentPickupEndEventHandler.super.reset(iteration); + } + + @Override + public void handleEvent(ActivityStartEvent activityStartEvent) { + + if (activityStartEvent.getActType().equals("delivery")) { + shipmentTracking.trackDeliveryActivity(activityStartEvent); + } + + if (activityStartEvent.getActType().equals("pickup")){ + shipmentTracking.trackPickupActivity(activityStartEvent); + } + + } + + public FreightAnalysisShipmentTracking getShipmentTracker(){ + return shipmentTracking; + } +} diff --git a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT.java b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT.java similarity index 99% rename from contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT.java rename to contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT.java index 4eb53f186bd..8dec71ea7f9 100644 --- a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT.java +++ b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT.java @@ -3,7 +3,7 @@ * project: org.matsim.* * *********************************************************************** * * * - * copyright : (C) 2021 by the members listed in the COPYING, * + * copyright : (C) by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -19,17 +19,17 @@ * */ -package org.matsim.contrib.freight.analysis; +package org.matsim.freight.carriers.analysis; import org.junit.*; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Person; -import org.matsim.contrib.freight.carrier.*; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; import org.matsim.core.network.NetworkUtils; +import org.matsim.freight.carriers.*; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.*; diff --git a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest.java b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest.java similarity index 73% rename from contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest.java rename to contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest.java index 77cef7e441a..358b79d8ad4 100644 --- a/contribs/vsp/src/test/java/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest.java +++ b/contribs/vsp/src/test/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest.java @@ -1,4 +1,25 @@ -package org.matsim.contrib.freight.analysis; +/* + * *********************************************************************** * + * project: org.matsim.* + * *********************************************************************** * + * * + * copyright : (C) 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.freight.carriers.analysis; import org.junit.Assert; import org.junit.Rule; @@ -6,10 +27,10 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.contrib.freight.carrier.CarrierPlanXmlReader; -import org.matsim.contrib.freight.carrier.CarrierShipment; -import org.matsim.contrib.freight.carrier.CarrierVehicleTypes; -import org.matsim.contrib.freight.carrier.Carriers; +import org.matsim.freight.carriers.CarrierPlanXmlReader; +import org.matsim.freight.carriers.CarrierShipment; +import org.matsim.freight.carriers.CarrierVehicleTypes; +import org.matsim.freight.carriers.Carriers; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; @@ -20,7 +41,6 @@ import java.io.File; import java.util.Iterator; import java.util.LinkedHashMap; -import java.util.Set; public class RunFreightAnalysisWithShipmentTest { diff --git a/contribs/vsp/src/test/java/org/matsim/integration/drtAndPt/PtAlongALine2Test.java b/contribs/vsp/src/test/java/org/matsim/integration/drtAndPt/PtAlongALine2Test.java index e4e04cc74f7..ef0cc856096 100644 --- a/contribs/vsp/src/test/java/org/matsim/integration/drtAndPt/PtAlongALine2Test.java +++ b/contribs/vsp/src/test/java/org/matsim/integration/drtAndPt/PtAlongALine2Test.java @@ -36,9 +36,9 @@ import org.matsim.contrib.otfvis.OTFVisLiveModule; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; +import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.config.groups.VspExperimentalConfigGroup; import org.matsim.core.controler.AbstractModule; @@ -107,28 +107,28 @@ public void testPtAlongALineWithRaptorAndDrtServiceArea() { // === GBL: === - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); // === ROUTER: === - config.plansCalcRoute().setAccessEgressType(AccessEgressType.accessEgressModeToLink); + config.routing().setAccessEgressType(AccessEgressType.accessEgressModeToLink); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.modeVehicleTypesFromVehiclesData); // (as of today, will also influence router. kai, jun'19) if (drtMode == DrtMode.teleportBeeline) {// (configure teleportation router) - config.plansCalcRoute() + config.routing() .addModeRoutingParams( - new PlansCalcRouteConfigGroup.TeleportedModeParams().setMode(TransportMode.drt ).setTeleportedModeSpeed(100. / 3.6 ) ); + new RoutingConfigGroup.TeleportedModeParams().setMode(TransportMode.drt ).setTeleportedModeSpeed(100. / 3.6 ) ); if (drt2) { - config.plansCalcRoute() + config.routing() .addModeRoutingParams( - new PlansCalcRouteConfigGroup.TeleportedModeParams().setMode("drt2" ).setTeleportedModeSpeed(100. / 3.6 ) ); + new RoutingConfigGroup.TeleportedModeParams().setMode("drt2" ).setTeleportedModeSpeed(100. / 3.6 ) ); } if (drt3) { - config.plansCalcRoute() + config.routing() .addModeRoutingParams( - new PlansCalcRouteConfigGroup.TeleportedModeParams().setMode("drt3" ).setTeleportedModeSpeed(100. / 3.6 ) ); + new RoutingConfigGroup.TeleportedModeParams().setMode("drt3" ).setTeleportedModeSpeed(100. / 3.6 ) ); } // teleportation router for walk or bike is automatically defined. } else if (drtMode == DrtMode.teleportBasedOnNetworkRoute) {// (route as network route) @@ -140,15 +140,15 @@ public void testPtAlongALineWithRaptorAndDrtServiceArea() { if (drt3) { networkModes.add("drt3"); } - config.plansCalcRoute().setNetworkModes(networkModes); + config.routing().setNetworkModes(networkModes); } - config.plansCalcRoute() - .addModeRoutingParams(new PlansCalcRouteConfigGroup.TeleportedModeParams().setMode("walk" ).setTeleportedModeSpeed(5. / 3.6 ) ); + config.routing() + .addModeRoutingParams(new RoutingConfigGroup.TeleportedModeParams().setMode("walk" ).setTeleportedModeSpeed(5. / 3.6 ) ); // set up walk2 so we don't need walk in raptor: - config.plansCalcRoute() - .addModeRoutingParams(new PlansCalcRouteConfigGroup.TeleportedModeParams().setMode("walk2" ).setTeleportedModeSpeed(5. / 3.6 ) ); + config.routing() + .addModeRoutingParams(new RoutingConfigGroup.TeleportedModeParams().setMode("walk2" ).setTeleportedModeSpeed(5. / 3.6 ) ); // === RAPTOR: === { @@ -196,21 +196,21 @@ public void testPtAlongALineWithRaptorAndDrtServiceArea() { // === SCORING: === - double margUtlTravPt = config.planCalcScore().getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling(); + double margUtlTravPt = config.scoring().getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling(); if (drtMode != DrtMode.none) { // (scoring parameters for drt modes) - config.planCalcScore() + config.scoring() .addModeParams(new ModeParams(TransportMode.drt).setMarginalUtilityOfTraveling(margUtlTravPt)); if (drt2) { - config.planCalcScore() + config.scoring() .addModeParams(new ModeParams("drt2").setMarginalUtilityOfTraveling(margUtlTravPt)); } if (drt3) { - config.planCalcScore() + config.scoring() .addModeParams(new ModeParams("drt3").setMarginalUtilityOfTraveling(margUtlTravPt)); } } - config.planCalcScore().addModeParams(new ModeParams("walk2").setMarginalUtilityOfTraveling(margUtlTravPt)); + config.scoring().addModeParams(new ModeParams("walk2").setMarginalUtilityOfTraveling(margUtlTravPt)); // === QSIM: === @@ -269,7 +269,7 @@ public void testPtAlongALineWithRaptorAndDrtServiceArea() { } for (DrtConfigGroup drtConfigGroup : mm.getModalElements()) { - DrtConfigs.adjustDrtConfig(drtConfigGroup, config.planCalcScore(), config.plansCalcRoute()); + DrtConfigs.adjustDrtConfig(drtConfigGroup, config.scoring(), config.routing()); } } @@ -593,22 +593,22 @@ public void intermodalAccessEgressPicksWrongVariant() { // === GBL: === - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); // === ROUTER: === - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.modeVehicleTypesFromVehiclesData); // (as of today, will also influence router. kai, jun'19) - config.plansCalcRoute().setNetworkModes(new HashSet<>(Arrays.asList(TransportMode.drt, "drt2"))); + config.routing().setNetworkModes(new HashSet<>(Arrays.asList(TransportMode.drt, "drt2"))); // set up walk2 so we don't use faulty walk in raptor: - config.plansCalcRoute().addModeRoutingParams(new PlansCalcRouteConfigGroup.TeleportedModeParams("walk2").setTeleportedModeSpeed(5. / 3.6 ) ); + config.routing().addModeRoutingParams(new RoutingConfigGroup.TeleportedModeParams("walk2").setTeleportedModeSpeed(5. / 3.6 ) ); - config.plansCalcRoute() - .addModeRoutingParams(new PlansCalcRouteConfigGroup.TeleportedModeParams(TransportMode.walk).setTeleportedModeSpeed(0. ) ); + config.routing() + .addModeRoutingParams(new RoutingConfigGroup.TeleportedModeParams(TransportMode.walk).setTeleportedModeSpeed(0. ) ); // (when specifying "walk2", all default routing params are cleared. However, swiss rail raptor needs "walk" to function. kai, feb'20) // === RAPTOR: === @@ -647,14 +647,14 @@ public void intermodalAccessEgressPicksWrongVariant() { // === SCORING: === { - double margUtlTravPt = config.planCalcScore() + double margUtlTravPt = config.scoring() .getModes() .get(TransportMode.pt) .getMarginalUtilityOfTraveling(); - config.planCalcScore() + config.scoring() .addModeParams(new ModeParams(TransportMode.drt).setMarginalUtilityOfTraveling(margUtlTravPt)); - config.planCalcScore().addModeParams(new ModeParams("drt2").setMarginalUtilityOfTraveling(margUtlTravPt)); - config.planCalcScore().addModeParams(new ModeParams("walk2").setMarginalUtilityOfTraveling(margUtlTravPt)); + config.scoring().addModeParams(new ModeParams("drt2").setMarginalUtilityOfTraveling(margUtlTravPt)); + config.scoring().addModeParams(new ModeParams("walk2").setMarginalUtilityOfTraveling(margUtlTravPt)); } // === QSIM: === @@ -755,22 +755,22 @@ public void networkWalkDoesNotWorkWithRaptor() { // === GBL: === - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); // === ROUTER: === - config.plansCalcRoute().setAccessEgressType(AccessEgressType.accessEgressModeToLink); + config.routing().setAccessEgressType(AccessEgressType.accessEgressModeToLink); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.modeVehicleTypesFromVehiclesData); // (as of today, will also influence router. kai, jun'19) // remove teleportation walk router: - config.plansCalcRoute().removeModeRoutingParams(TransportMode.walk); + config.routing().removeModeRoutingParams(TransportMode.walk); // add network walk router: - Set networkModes = new HashSet<>(config.plansCalcRoute().getNetworkModes()); + Set networkModes = new HashSet<>(config.routing().getNetworkModes()); networkModes.add(TransportMode.walk); - config.plansCalcRoute().setNetworkModes(networkModes); + config.routing().setNetworkModes(networkModes); // === RAPTOR: === { diff --git a/contribs/vsp/src/test/java/org/matsim/integration/drtAndPt/PtAlongALineTest.java b/contribs/vsp/src/test/java/org/matsim/integration/drtAndPt/PtAlongALineTest.java index bf402c506bc..67534b4b205 100644 --- a/contribs/vsp/src/test/java/org/matsim/integration/drtAndPt/PtAlongALineTest.java +++ b/contribs/vsp/src/test/java/org/matsim/integration/drtAndPt/PtAlongALineTest.java @@ -27,10 +27,10 @@ import org.matsim.contrib.dvrp.run.DvrpQSimComponents; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; +import org.matsim.core.config.groups.RoutingConfigGroup; 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.config.groups.VspExperimentalConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -119,37 +119,37 @@ public void testDrtAlongALine() { } for (DrtConfigGroup drtCfg : multiModeDrtCfg.getModalElements()) { - DrtConfigs.adjustDrtConfig(drtCfg, config.planCalcScore(), config.plansCalcRoute()); + DrtConfigs.adjustDrtConfig(drtCfg, config.scoring(), config.routing()); } - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setLastIteration(0); - config.controler() + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); + config.controller() .setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); { - StrategyConfigGroup.StrategySettings stratSets = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings stratSets = new ReplanningConfigGroup.StrategySettings(); stratSets.setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.SubtourModeChoice); stratSets.setWeight(0.1); - config.strategy().addStrategySettings(stratSets); + config.replanning().addStrategySettings(stratSets); // config.subtourModeChoice().setModes(new String[] { TransportMode.car, "drt_A" }); } { - StrategyConfigGroup.StrategySettings stratSets = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings stratSets = new ReplanningConfigGroup.StrategySettings(); stratSets.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta); stratSets.setWeight(1.); - config.strategy().addStrategySettings(stratSets); + config.replanning().addStrategySettings(stratSets); } { ModeParams modeParams = new ModeParams("drt_A"); - config.planCalcScore().addModeParams(modeParams); + config.scoring().addModeParams(modeParams); } { ModeParams modeParams = new ModeParams("drt_A_walk"); - config.planCalcScore().addModeParams(modeParams); + config.scoring().addModeParams(modeParams); } Scenario scenario = ScenarioUtils.loadScenario(config); @@ -210,21 +210,21 @@ public void testPtAlongALineWithRaptorAndDrtStopFilterAttribute() { config.qsim().setSimStarttimeInterpretation(QSimConfigGroup.StarttimeInterpretation.onlyUseStarttime); // yy why? kai, jun'19 - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); ModeParams accessWalk = new ModeParams(TransportMode.non_network_walk); accessWalk.setMarginalUtilityOfTraveling(0); - config.planCalcScore().addModeParams(accessWalk); + config.scoring().addModeParams(accessWalk); // (scoring parameters for drt modes) { ModeParams modeParams = new ModeParams(TransportMode.drt); - config.planCalcScore().addModeParams(modeParams); + config.scoring().addModeParams(modeParams); } config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.modeVehicleTypesFromVehiclesData); // (as of today, will also influence router. kai, jun'19) - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); { // (raptor config) @@ -257,7 +257,7 @@ public void testPtAlongALineWithRaptorAndDrtStopFilterAttribute() { } for (DrtConfigGroup drtConfigGroup : mm.getModalElements()) { - DrtConfigs.adjustDrtConfig(drtConfigGroup, config.planCalcScore(), config.plansCalcRoute()); + DrtConfigs.adjustDrtConfig(drtConfigGroup, config.scoring(), config.routing()); } config.vspExperimental().setVspDefaultsCheckingLevel(VspExperimentalConfigGroup.VspDefaultsCheckingLevel.warn); @@ -309,11 +309,11 @@ static Config createConfig(String outputDir) { config.global().setNumberOfThreads(1); - config.controler().setOutputDirectory(outputDir); - config.controler().setLastIteration(0); + config.controller().setOutputDirectory(outputDir); + config.controller().setLastIteration(0); - config.plansCalcRoute().getModeRoutingParams().get(TransportMode.walk).setTeleportedModeSpeed(3.); - config.plansCalcRoute().getModeRoutingParams().get(TransportMode.bike).setTeleportedModeSpeed(10.); + config.routing().getModeRoutingParams().get(TransportMode.walk).setTeleportedModeSpeed(3.); + config.routing().getModeRoutingParams().get(TransportMode.bike).setTeleportedModeSpeed(10.); config.qsim().setEndTime(24. * 3600.); @@ -346,19 +346,19 @@ static Config createConfig(String outputDir) { private static void configureScoring(Config config) { ModeParams accessWalk = new ModeParams(TransportMode.non_network_walk); accessWalk.setMarginalUtilityOfTraveling(0); - config.planCalcScore().addModeParams(accessWalk); + config.scoring().addModeParams(accessWalk); ModeParams transitWalk = new ModeParams("transit_walk"); transitWalk.setMarginalUtilityOfTraveling(0); - config.planCalcScore().addModeParams(transitWalk); + config.scoring().addModeParams(transitWalk); ModeParams bike = new ModeParams("bike"); bike.setMarginalUtilityOfTraveling(0); - config.planCalcScore().addModeParams(bike); + config.scoring().addModeParams(bike); ModeParams drt = new ModeParams("drt"); drt.setMarginalUtilityOfTraveling(0); - config.planCalcScore().addModeParams(drt); + config.scoring().addModeParams(drt); } static SwissRailRaptorConfigGroup createRaptorConfigGroup(int radiusWalk, int radiusBike) { diff --git a/contribs/vsp/src/test/java/playground/vsp/TestScenario.java b/contribs/vsp/src/test/java/playground/vsp/TestScenario.java index aba2de831fc..24fde8c688a 100644 --- a/contribs/vsp/src/test/java/playground/vsp/TestScenario.java +++ b/contribs/vsp/src/test/java/playground/vsp/TestScenario.java @@ -45,8 +45,8 @@ public static Config loadConfig(MatsimTestUtils utils) { URL context = ExamplesUtils.getTestScenarioURL("kelheim"); Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(context, "config.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; } diff --git a/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceAndCountsCadytsIT.java b/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceAndCountsCadytsIT.java index ce790c4d024..0974c7e40da 100644 --- a/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceAndCountsCadytsIT.java +++ b/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceAndCountsCadytsIT.java @@ -82,51 +82,51 @@ private Config createConfig() { Config config = ConfigUtils.createConfig(); String[] modes = new String[]{TransportMode.car, TransportMode.bike}; - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(40); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(40); config.counts().setWriteCountsInterval(1); config.counts().setAverageCountsOverIterations(1); - PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setMinimalDuration(3600); home.setTypicalDuration(3600); home.setEarliestEndTime(0); - config.planCalcScore().addActivityParams(home); + config.scoring().addActivityParams(home); - PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setMinimalDuration(3600); work.setTypicalDuration(3600); work.setEarliestEndTime(0); work.setOpeningTime(3600); work.setClosingTime(10 * 3600); - config.planCalcScore().addActivityParams(work); + config.scoring().addActivityParams(work); // have random selection of plans to generate heterogenity in the beginning, so that cadyts can calibrate its correction - StrategyConfigGroup.StrategySettings selectRandom = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings selectRandom = new ReplanningConfigGroup.StrategySettings(); selectRandom.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.SelectRandom); selectRandom.setDisableAfter(33); selectRandom.setWeight(0.5); - config.strategy().addStrategySettings(selectRandom); + config.replanning().addStrategySettings(selectRandom); // have change exp beta, so that mode distribution converges at the end of the simulation - StrategyConfigGroup.StrategySettings changeExpBeta = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings changeExpBeta = new ReplanningConfigGroup.StrategySettings(); changeExpBeta.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta); changeExpBeta.setDisableAfter(38); changeExpBeta.setWeight(0.5); - config.strategy().addStrategySettings(changeExpBeta); + config.replanning().addStrategySettings(changeExpBeta); // at the end of the scenario pick the plans with the best score - StrategyConfigGroup.StrategySettings bestScore = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings bestScore = new ReplanningConfigGroup.StrategySettings(); bestScore.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.BestScore); bestScore.setWeight(0.1); - config.strategy().addStrategySettings(bestScore); + config.replanning().addStrategySettings(bestScore); // remove teleported bike - config.plansCalcRoute().removeModeRoutingParams(TransportMode.bike); - config.plansCalcRoute().setNetworkModes(Arrays.asList(modes)); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.routing().removeModeRoutingParams(TransportMode.bike); + config.routing().setNetworkModes(Arrays.asList(modes)); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); config.qsim().setMainModes(Arrays.asList(modes)); config.qsim().setLinkDynamics(QSimConfigGroup.LinkDynamics.PassingQ); diff --git a/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsMultipleDistancesIT.java b/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsMultipleDistancesIT.java index 8825758ec04..c1a5a6a1e74 100644 --- a/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsMultipleDistancesIT.java +++ b/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsMultipleDistancesIT.java @@ -16,10 +16,10 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.ChangeModeConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; 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; @@ -137,44 +137,44 @@ private Config createConfig() { Config config = ConfigUtils.createConfig(); String[] modes = new String[]{TransportMode.car, TransportMode.bike}; - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(20); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(20); config.counts().setWriteCountsInterval(1); config.counts().setAverageCountsOverIterations(1); - PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setMinimalDuration(6 * 3600); home.setTypicalDuration(6 * 3600); home.setEarliestEndTime(6 * 3600); - config.planCalcScore().addActivityParams(home); + config.scoring().addActivityParams(home); - PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setMinimalDuration(8 * 3600); work.setTypicalDuration(8 * 3600); work.setEarliestEndTime(14 * 3600); work.setOpeningTime(6 * 3600); work.setClosingTime(18 * 3600); - config.planCalcScore().addActivityParams(work); + config.scoring().addActivityParams(work); // have random selection of plans to generate heterogenity in the beginning, so that cadyts can calibrate its correction - StrategyConfigGroup.StrategySettings selectRandom = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings selectRandom = new ReplanningConfigGroup.StrategySettings(); selectRandom.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.SelectRandom); selectRandom.setDisableAfter(17); selectRandom.setWeight(0.5); - config.strategy().addStrategySettings(selectRandom); + config.replanning().addStrategySettings(selectRandom); // have change exp beta, so that mode distribution converges at the end of the simulation - 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); // remove teleported bike - config.plansCalcRoute().removeModeRoutingParams(TransportMode.bike); - config.plansCalcRoute().setNetworkModes(Arrays.asList(modes)); - config.plansCalcRoute().setAccessEgressType(AccessEgressType.accessEgressModeToLink); + config.routing().removeModeRoutingParams(TransportMode.bike); + config.routing().setNetworkModes(Arrays.asList(modes)); + config.routing().setAccessEgressType(AccessEgressType.accessEgressModeToLink); config.qsim().setMainModes(Arrays.asList(modes)); config.qsim().setLinkDynamics(QSimConfigGroup.LinkDynamics.PassingQ); diff --git a/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsSingleDistanceIT.java b/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsSingleDistanceIT.java index bea4e17654b..cbd93316434 100644 --- a/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsSingleDistanceIT.java +++ b/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/ModalDistanceCadytsSingleDistanceIT.java @@ -141,44 +141,44 @@ private Config createConfig() { Config config = ConfigUtils.createConfig(); String[] modes = new String[]{TransportMode.car, TransportMode.bike}; - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(20); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(20); config.counts().setWriteCountsInterval(1); config.counts().setAverageCountsOverIterations(1); - PlanCalcScoreConfigGroup.ActivityParams home = new PlanCalcScoreConfigGroup.ActivityParams("home"); + ScoringConfigGroup.ActivityParams home = new ScoringConfigGroup.ActivityParams("home"); home.setMinimalDuration(6 * 3600); home.setTypicalDuration(6 * 3600); home.setEarliestEndTime(6 * 3600); - config.planCalcScore().addActivityParams(home); + config.scoring().addActivityParams(home); - PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setMinimalDuration(8 * 3600); work.setTypicalDuration(8 * 3600); work.setEarliestEndTime(14 * 3600); work.setOpeningTime(6 * 3600); work.setClosingTime(18 * 3600); - config.planCalcScore().addActivityParams(work); + config.scoring().addActivityParams(work); // have random selection of plans to generate heterogenity in the beginning, so that cadyts can calibrate its correction - StrategyConfigGroup.StrategySettings selectRandom = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings selectRandom = new ReplanningConfigGroup.StrategySettings(); selectRandom.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.SelectRandom); selectRandom.setDisableAfter(17); selectRandom.setWeight(0.5); - config.strategy().addStrategySettings(selectRandom); + config.replanning().addStrategySettings(selectRandom); // have change exp beta, so that mode distribution converges at the end of the simulation - 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); // remove teleported bike - config.plansCalcRoute().removeModeRoutingParams(TransportMode.bike); - config.plansCalcRoute().setNetworkModes(Arrays.asList(modes)); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.routing().removeModeRoutingParams(TransportMode.bike); + config.routing().setNetworkModes(Arrays.asList(modes)); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); config.qsim().setMainModes(Arrays.asList(modes)); config.qsim().setLinkDynamics(QSimConfigGroup.LinkDynamics.PassingQ); @@ -191,7 +191,7 @@ private Config createConfig() { config.travelTimeCalculator().setFilterModes(true); config.changeMode().setModes(modes); config.changeMode().setBehavior(ChangeModeConfigGroup.Behavior.fromSpecifiedModesToSpecifiedModes); - config.strategy().setFractionOfIterationsToDisableInnovation(0.8); + config.replanning().setFractionOfIterationsToDisableInnovation(0.8); return config; } diff --git a/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/TripEventHandlerTest.java b/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/TripEventHandlerTest.java index d3f39021329..83439dd2480 100644 --- a/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/TripEventHandlerTest.java +++ b/contribs/vsp/src/test/java/playground/vsp/cadyts/marginals/TripEventHandlerTest.java @@ -8,7 +8,7 @@ import org.matsim.api.core.v01.population.Person; 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.config.groups.PlansConfigGroup.HandlingOfPlansWithoutRoutingMode; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; @@ -48,11 +48,11 @@ public void test() throws MalformedURLException { config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); // use the config and run only one iteration - config.controler().setFirstIteration(0); - config.controler().setLastIteration(0); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(0); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -107,4 +107,4 @@ public void install() { assertEquals(TransportMode.pt, tripsOfPerson102.get(2).getLegs().get(1).getMode()); assertEquals(TransportMode.walk, tripsOfPerson102.get(2).getLegs().get(2).getMode()); } -} \ No newline at end of file +} diff --git a/contribs/vsp/src/test/java/playground/vsp/congestion/AdvancedMarginalCongestionPricingIT.java b/contribs/vsp/src/test/java/playground/vsp/congestion/AdvancedMarginalCongestionPricingIT.java index 5403d398a2a..78942907bdf 100644 --- a/contribs/vsp/src/test/java/playground/vsp/congestion/AdvancedMarginalCongestionPricingIT.java +++ b/contribs/vsp/src/test/java/playground/vsp/congestion/AdvancedMarginalCongestionPricingIT.java @@ -42,9 +42,9 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; import org.matsim.core.config.groups.ScenarioConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; @@ -78,7 +78,7 @@ public class AdvancedMarginalCongestionPricingIT { @Test public final void test0a(){ - PlanCalcScoreConfigGroup plansCalcScoreConfigGroup = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup plansCalcScoreConfigGroup = new ScoringConfigGroup(); ActivityParams activityParams = new ActivityParams("work"); activityParams.setTypicalDuration(6 * 3600.); activityParams.setOpeningTime(7 * 3600.); @@ -143,7 +143,7 @@ public final void test0a(){ @Test public final void test0b(){ - PlanCalcScoreConfigGroup plansCalcScoreConfigGroup = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup plansCalcScoreConfigGroup = new ScoringConfigGroup(); ActivityParams activityParams = new ActivityParams("overnightActivity"); activityParams.setTypicalDuration(12 * 3600.); @@ -191,7 +191,7 @@ public final void test0b(){ @Test public final void test0c(){ - PlanCalcScoreConfigGroup plansCalcScoreConfigGroup = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup plansCalcScoreConfigGroup = new ScoringConfigGroup(); ActivityParams activityParams1 = new ActivityParams("firstActivityType"); activityParams1.setTypicalDuration(12 * 3600.); @@ -241,7 +241,7 @@ public final void test1(){ String configFile = testUtils.getPackageInputDirectory() + "AdvancedMarginalCongestionPricingTest/config1.xml"; Config config = ConfigUtils.loadConfig( configFile ) ; - config.plansCalcRoute().setAccessEgressType(AccessEgressType.none); + config.routing().setAccessEgressType(AccessEgressType.none); final Scenario scenario = ScenarioUtils.loadScenario( config ); Controler controler = new Controler( scenario ); @@ -279,7 +279,7 @@ public void handleEvent(PersonMoneyEvent event) { final CongestionTollTimeDistanceTravelDisutilityFactory tollDisutilityCalculatorFactory = new CongestionTollTimeDistanceTravelDisutilityFactory( new RandomizingTimeDistanceTravelDisutilityFactory(TransportMode.car, config), - tollHandler, controler.getConfig().planCalcScore()); + tollHandler, controler.getConfig().scoring()); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -296,7 +296,7 @@ public ControlerListener get() { }); controler.addOverridingModule(new OTFVisFileWriterModule()); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); controler.run(); // test if there is only one congestion event and only one money event @@ -308,11 +308,11 @@ public ControlerListener get() { Assert.assertEquals("Wrong delay.", 2.0, delay, MatsimTestUtils.EPSILON); double amountFromEvent = moneyEvents.get(0).getAmount(); - double tripDelayDisutility = delay / 3600. * controler.getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() * (-1); + double tripDelayDisutility = delay / 3600. * controler.getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() * (-1); // with delay --> 70.570685898554200 // without delay --> 70.573360291244900 double activityDelayDisutility = 70.573360291244900 - 70.570685898554200; - double amount = (-1) * (activityDelayDisutility + tripDelayDisutility) / controler.getConfig().planCalcScore().getMarginalUtilityOfMoney(); + double amount = (-1) * (activityDelayDisutility + tripDelayDisutility) / controler.getConfig().scoring().getMarginalUtilityOfMoney(); Assert.assertEquals("Wrong amount.", amount, amountFromEvent, MatsimTestUtils.EPSILON); } @@ -323,7 +323,7 @@ public final void test2(){ String configFile = testUtils.getPackageInputDirectory() + "AdvancedMarginalCongestionPricingTest/config2.xml"; Config config = ConfigUtils.loadConfig( configFile ) ; - config.plansCalcRoute().setAccessEgressType(AccessEgressType.none); + config.routing().setAccessEgressType(AccessEgressType.none); final Scenario scenario = ScenarioUtils.loadScenario( config ); Controler controler = new Controler( scenario ); @@ -360,7 +360,7 @@ public void handleEvent(PersonMoneyEvent event) { final TollHandler tollHandler = new TollHandler(controler.getScenario()); final CongestionTollTimeDistanceTravelDisutilityFactory tollDisutilityCalculatorFactory = new CongestionTollTimeDistanceTravelDisutilityFactory( new RandomizingTimeDistanceTravelDisutilityFactory(TransportMode.car, config), - tollHandler, controler.getConfig().planCalcScore()); + tollHandler, controler.getConfig().scoring()); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -376,7 +376,7 @@ public ControlerListener get() { } }); controler.addOverridingModule(new OTFVisFileWriterModule()); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); controler.run(); // test if there is only one congestion event and only one money event @@ -388,7 +388,7 @@ public ControlerListener get() { Assert.assertEquals("Wrong delay.", 2.0, delay, MatsimTestUtils.EPSILON); double amountFromEvent = moneyEvents.get(0).getAmount(); - double tripDelayDisutility = delay / 3600. * controler.getConfig().planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() * (-1); + double tripDelayDisutility = delay / 3600. * controler.getConfig().scoring().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() * (-1); // home duration morning: 28800. // home duration evening with delay: (24 * 3600.) - 57705. @@ -398,7 +398,7 @@ public ControlerListener get() { // without delay --> 80.584243964094500 double activityDelayDisutility = 80.584243964094500 - 80.581739442040600; - double amount = (-1) * (activityDelayDisutility + tripDelayDisutility) / controler.getConfig().planCalcScore().getMarginalUtilityOfMoney(); + double amount = (-1) * (activityDelayDisutility + tripDelayDisutility) / controler.getConfig().scoring().getMarginalUtilityOfMoney(); Assert.assertEquals("Wrong amount.", amount, amountFromEvent, MatsimTestUtils.EPSILON); } @@ -409,7 +409,7 @@ public final void test3(){ String configFile = testUtils.getPackageInputDirectory() + "AdvancedMarginalCongestionPricingTest/config3.xml"; Config config = ConfigUtils.loadConfig( configFile ) ; - config.plansCalcRoute().setAccessEgressType(AccessEgressType.none); + config.routing().setAccessEgressType(AccessEgressType.none); final Scenario scenario = ScenarioUtils.loadScenario( config); Controler controler = new Controler( scenario ); @@ -446,7 +446,7 @@ public void handleEvent(PersonMoneyEvent event) { final TollHandler tollHandler = new TollHandler(controler.getScenario()); final CongestionTollTimeDistanceTravelDisutilityFactory tollDisutilityCalculatorFactory = new CongestionTollTimeDistanceTravelDisutilityFactory( new RandomizingTimeDistanceTravelDisutilityFactory(TransportMode.car, config), - tollHandler, controler.getConfig().planCalcScore()); + tollHandler, controler.getConfig().scoring()); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -462,7 +462,7 @@ public ControlerListener get() { } }); controler.addOverridingModule(new OTFVisFileWriterModule()); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); controler.run(); // test if there are three congestion events and three money events @@ -477,7 +477,7 @@ public final void test4(){ String configFile = testUtils.getPackageInputDirectory() + "AdvancedMarginalCongestionPricingTest/config4.xml"; Config config = ConfigUtils.loadConfig( configFile ) ; - config.plansCalcRoute().setAccessEgressType(AccessEgressType.none); + config.routing().setAccessEgressType(AccessEgressType.none); final Scenario scenario = ScenarioUtils.loadScenario( config ); Controler controler = new Controler( scenario ); @@ -514,7 +514,7 @@ public void handleEvent(PersonMoneyEvent event) { final TollHandler tollHandler = new TollHandler(controler.getScenario()); final CongestionTollTimeDistanceTravelDisutilityFactory tollDisutilityCalculatorFactory = new CongestionTollTimeDistanceTravelDisutilityFactory( new RandomizingTimeDistanceTravelDisutilityFactory(TransportMode.car, config), - tollHandler, controler.getConfig().planCalcScore()); + tollHandler, controler.getConfig().scoring()); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -530,7 +530,7 @@ public ControlerListener get() { } }); controler.addOverridingModule(new OTFVisFileWriterModule()); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); controler.run(); // test if there are three congestion events and three money events diff --git a/contribs/vsp/src/test/java/playground/vsp/congestion/MarginalCongestionHandlerFlowSpillbackQueueQsimTest.java b/contribs/vsp/src/test/java/playground/vsp/congestion/MarginalCongestionHandlerFlowSpillbackQueueQsimTest.java index 2198bb4d66a..0a5aae8bb70 100644 --- a/contribs/vsp/src/test/java/playground/vsp/congestion/MarginalCongestionHandlerFlowSpillbackQueueQsimTest.java +++ b/contribs/vsp/src/test/java/playground/vsp/congestion/MarginalCongestionHandlerFlowSpillbackQueueQsimTest.java @@ -56,7 +56,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.config.groups.QSimConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; @@ -317,7 +317,7 @@ public final void testRouting(){ Config config = ConfigUtils.loadConfig( configFile ) ; - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.none); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.none); final Scenario scenario = ScenarioUtils.loadScenario( config ); Controler controler = new Controler( scenario ); @@ -326,7 +326,7 @@ public final void testRouting(){ final CongestionTollTimeDistanceTravelDisutilityFactory tollDisutilityCalculatorFactory = new CongestionTollTimeDistanceTravelDisutilityFactory( new RandomizingTimeDistanceTravelDisutilityFactory(TransportMode.car, config), - tollHandler, controler.getConfig().planCalcScore()); + tollHandler, controler.getConfig().scoring()); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -402,14 +402,14 @@ public void handleEvent(LinkLeaveEvent event) { @Override public void notifyIterationStarts(IterationStartsEvent event) { // last but one iteration - if(((event.getServices().getConfig().controler().getLastIteration())-(event.getIteration()))==1){ + if(((event.getServices().getConfig().controller().getLastIteration())-(event.getIteration()))==1){ avgValue1 = tollHandler.getAvgToll(linkId2_, 28800); avgValue2 = tollHandler.getAvgToll(linkId2_, 29700); avgOldValue1 = tollHandler.getAvgTollOldValue(linkId2_, 28800); avgOldValue2 = tollHandler.getAvgTollOldValue(linkId2_, 28800); } // last iteration - else if(((event.getServices().getConfig().controler().getLastIteration())-(event.getIteration()))==0){ + else if(((event.getServices().getConfig().controller().getLastIteration())-(event.getIteration()))==0){ avgValue3 = tollHandler.getAvgToll(linkId2_, 28800); avgValue4 = tollHandler.getAvgToll(linkId2_, 29700); avgOldValue3 = tollHandler.getAvgTollOldValue(linkId2_, 28800); @@ -419,7 +419,7 @@ else if(((event.getServices().getConfig().controler().getLastIteration())-(event }); - controler.getConfig().controler().setOverwriteFileSetting( + controler.getConfig().controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); controler.run(); diff --git a/contribs/vsp/src/test/java/playground/vsp/congestion/MarginalCongestionHandlerV3Test.java b/contribs/vsp/src/test/java/playground/vsp/congestion/MarginalCongestionHandlerV3Test.java index fb236dde784..2c040502c4d 100644 --- a/contribs/vsp/src/test/java/playground/vsp/congestion/MarginalCongestionHandlerV3Test.java +++ b/contribs/vsp/src/test/java/playground/vsp/congestion/MarginalCongestionHandlerV3Test.java @@ -39,7 +39,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -70,7 +70,7 @@ public final void testCongestionExample(){ final List congestionEvents = new ArrayList(); Config config = ConfigUtils.loadConfig( configFile ) ; - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.none); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.none); final Controler controler = new Controler(config); controler.addOverridingModule(new AbstractModule() { @@ -92,7 +92,7 @@ public void install() { } }); - controler.getConfig().controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); + controler.getConfig().controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); controler.run(); // process diff --git a/contribs/vsp/src/test/java/playground/vsp/ev/CreateUrbanEVTestScenario.java b/contribs/vsp/src/test/java/playground/vsp/ev/CreateUrbanEVTestScenario.java index 994dade91b8..94a9ea4604c 100644 --- a/contribs/vsp/src/test/java/playground/vsp/ev/CreateUrbanEVTestScenario.java +++ b/contribs/vsp/src/test/java/playground/vsp/ev/CreateUrbanEVTestScenario.java @@ -25,8 +25,8 @@ import org.matsim.contrib.ev.EvConfigGroup; 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.config.groups.QSimConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.scenario.ScenarioUtils; @@ -45,17 +45,17 @@ static Scenario createTestScenario(){ evReplanningCfg.setCriticalSOC(0.4); //TODO actually, should also work with all AccessEgressTypes but we have to check (write JUnit test) - config.plansCalcRoute().setAccessEgressType( PlansCalcRouteConfigGroup.AccessEgressType.none ); + config.routing().setAccessEgressType( RoutingConfigGroup.AccessEgressType.none ); //register charging interaction activities for car - config.planCalcScore().addActivityParams( - new PlanCalcScoreConfigGroup.ActivityParams( TransportMode.car + UrbanEVModule.PLUGOUT_INTERACTION).setScoringThisActivityAtAll(false ) ); - config.planCalcScore().addActivityParams( - new PlanCalcScoreConfigGroup.ActivityParams( TransportMode.car + UrbanEVModule.PLUGIN_INTERACTION).setScoringThisActivityAtAll( false ) ); + config.scoring().addActivityParams( + new ScoringConfigGroup.ActivityParams( TransportMode.car + UrbanEVModule.PLUGOUT_INTERACTION).setScoringThisActivityAtAll(false ) ); + config.scoring().addActivityParams( + new ScoringConfigGroup.ActivityParams( TransportMode.car + UrbanEVModule.PLUGIN_INTERACTION).setScoringThisActivityAtAll( false ) ); config.network().setInputFile("1pctNetwork.xml"); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - config.controler().setLastIteration(5); - config.controler().setWriteEventsInterval(1); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setLastIteration(5); + config.controller().setWriteEventsInterval(1); //set VehicleSource config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.fromVehiclesData); config.qsim().setEndTime(20*3600); diff --git a/contribs/vsp/src/test/java/playground/vsp/ev/TransferFinalSocToNextIterTest.java b/contribs/vsp/src/test/java/playground/vsp/ev/TransferFinalSocToNextIterTest.java index 27d07e6f589..b77b0352fc0 100644 --- a/contribs/vsp/src/test/java/playground/vsp/ev/TransferFinalSocToNextIterTest.java +++ b/contribs/vsp/src/test/java/playground/vsp/ev/TransferFinalSocToNextIterTest.java @@ -52,8 +52,8 @@ public class TransferFinalSocToNextIterTest { @Test public void test() { //adapt scenario - scenario.getConfig().controler().setLastIteration(LAST_ITERATION); - scenario.getConfig().controler().setOutputDirectory("test/output/playground/vsp/ev/FinalSoc2VehicleTypeTest/"); + scenario.getConfig().controller().setLastIteration(LAST_ITERATION); + scenario.getConfig().controller().setOutputDirectory("test/output/playground/vsp/ev/FinalSoc2VehicleTypeTest/"); var vehicle1 = scenario.getVehicles().getVehicles().get(Id.create("Triple Charger_car", Vehicle.class)); ElectricVehicleSpecifications.setInitialSoc(vehicle1, INITIAL_SOC); diff --git a/contribs/vsp/src/test/java/playground/vsp/ev/UrbanEVTests.java b/contribs/vsp/src/test/java/playground/vsp/ev/UrbanEVTests.java index c4fc69df74c..aa1e6143b24 100644 --- a/contribs/vsp/src/test/java/playground/vsp/ev/UrbanEVTests.java +++ b/contribs/vsp/src/test/java/playground/vsp/ev/UrbanEVTests.java @@ -63,9 +63,9 @@ public class UrbanEVTests { @BeforeClass public static void run() { Scenario scenario = CreateUrbanEVTestScenario.createTestScenario(); - scenario.getConfig().controler().setOutputDirectory("test/output/playground/vsp/ev/UrbanEVTests/"); + scenario.getConfig().controller().setOutputDirectory("test/output/playground/vsp/ev/UrbanEVTests/"); - scenario.getConfig().controler().setLastIteration(0); + scenario.getConfig().controller().setLastIteration(0); //modify population overridePopulation(scenario); diff --git a/contribs/vsp/src/test/java/playground/vsp/flowEfficiency/HierarchicalFLowEfficiencyCalculatorTest.java b/contribs/vsp/src/test/java/playground/vsp/flowEfficiency/HierarchicalFLowEfficiencyCalculatorTest.java index da0ab06db96..d8033195348 100644 --- a/contribs/vsp/src/test/java/playground/vsp/flowEfficiency/HierarchicalFLowEfficiencyCalculatorTest.java +++ b/contribs/vsp/src/test/java/playground/vsp/flowEfficiency/HierarchicalFLowEfficiencyCalculatorTest.java @@ -1,7 +1,6 @@ package playground.vsp.flowEfficiency; import com.google.inject.Provides; -import com.google.inject.name.Names; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -26,7 +25,6 @@ import org.matsim.contrib.dvrp.run.DvrpConfigGroup; import org.matsim.contrib.dvrp.run.DvrpModule; import org.matsim.contrib.dvrp.run.DvrpQSimComponents; -import org.matsim.contrib.dvrp.vrpagent.VrpAgentSourceQSimModule; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; @@ -91,7 +89,7 @@ public void simulate(){ "eight_shared_taxi_config.xml"); Config config = ConfigUtils.loadConfig(configUrl, new DvrpConfigGroup(), new MultiModeDrtConfigGroup(), new OTFVisConfigGroup()); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); config.qsim().setEndTime(4*3600); MultiModeDrtConfigGroup multiModeDrtConfigGroup = ConfigUtils.addOrGetModule(config, MultiModeDrtConfigGroup.class); @@ -301,4 +299,4 @@ public void reset(int iteration) { } -} \ No newline at end of file +} diff --git a/contribs/vsp/src/test/java/playground/vsp/pt/fare/PtTripFareEstimatorTest.java b/contribs/vsp/src/test/java/playground/vsp/pt/fare/PtTripFareEstimatorTest.java index fee58b21390..e4b686fc810 100644 --- a/contribs/vsp/src/test/java/playground/vsp/pt/fare/PtTripFareEstimatorTest.java +++ b/contribs/vsp/src/test/java/playground/vsp/pt/fare/PtTripFareEstimatorTest.java @@ -15,7 +15,7 @@ import org.matsim.application.MATSimApplication; 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.scoring.functions.ScoringParametersForPerson; import org.matsim.modechoice.*; @@ -52,10 +52,10 @@ public void setUp() throws Exception { Config config = TestScenario.loadConfig(utils); - Map modes = config.planCalcScore().getScoringParameters("person").getModes(); + Map modes = config.scoring().getScoringParameters("person").getModes(); - PlanCalcScoreConfigGroup.ModeParams pt = modes.get(TransportMode.pt); - PlanCalcScoreConfigGroup.ModeParams walk = modes.get(TransportMode.walk); + ScoringConfigGroup.ModeParams pt = modes.get(TransportMode.pt); + ScoringConfigGroup.ModeParams walk = modes.get(TransportMode.walk); group = ConfigUtils.addOrGetModule(config, InformedModeChoiceConfigGroup.class); diff --git a/contribs/vsp/src/test/java/playground/vsp/pt/ptdisturbances/EditTripsTest.java b/contribs/vsp/src/test/java/playground/vsp/pt/ptdisturbances/EditTripsTest.java index d82509af72c..c9e063abf12 100644 --- a/contribs/vsp/src/test/java/playground/vsp/pt/ptdisturbances/EditTripsTest.java +++ b/contribs/vsp/src/test/java/playground/vsp/pt/ptdisturbances/EditTripsTest.java @@ -120,7 +120,7 @@ public void testAgentStaysAtStop() { Config config = ConfigUtils .loadConfig(configURL); String outputDirectory = utils.getOutputDirectory(); - config.controler() + config.controller() .setOutputDirectory(outputDirectory); Scenario scenario = ScenarioUtils.loadScenario(config); scenario.getPopulation().getPersons().clear(); @@ -158,9 +158,8 @@ public void testAgentLeavesStop() { HashMap, Double> arrivalTimes = new HashMap<>(); HashMap, List> trips = new HashMap<>(); Config config = ConfigUtils.loadConfig(configURL); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); String outputDirectory = utils.getOutputDirectory(); - config.controler().setOutputDirectory(outputDirectory); + config.controller().setOutputDirectory(outputDirectory); Scenario scenario = ScenarioUtils.loadScenario(config); scenario.getPopulation().getPersons().clear(); double activityEndTime = 7. * 3600 + 15. * 60; @@ -171,20 +170,16 @@ public void testAgentLeavesStop() { double travelTime = arrivalTimes.get(person.getId()) - activityEndTime; List trip = trips.get(person.getId()); - assertEquals("Travel time has changed", 2990.0, travelTime, MatsimTestUtils.EPSILON); - assertEquals("Number of trip elements has changed", 11 ,trip.size()); + assertEquals("Travel time has changed", 1344.0, travelTime, MatsimTestUtils.EPSILON); + assertEquals("Number of trip elements has changed", 7 ,trip.size()); assertEquals("Trip element has changed", "dummy@car_17bOut", trip.get(0)); assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(1)); assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(2)); - assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(3)); - assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(4)); - assertEquals("Trip element has changed", "pt interaction@pt7", trip.get(5)); - assertEquals("Trip element has changed", "pt interaction@pt7", trip.get(6)); - assertEquals("Trip element has changed", "tr_334", trip.get(7)); - assertEquals("Trip element has changed", "pt interaction@pt8", trip.get(8)); - assertEquals("Trip element has changed", "pt interaction@pt8", trip.get(9)); - assertEquals("Trip element has changed", "dummy@work0", trip.get(10)); + assertEquals("Trip element has changed", "tr_333", trip.get(3)); + assertEquals("Trip element has changed", "pt interaction@pt8", trip.get(4)); + assertEquals("Trip element has changed", "pt interaction@pt8", trip.get(5)); + assertEquals("Trip element has changed", "dummy@work0", trip.get(6)); } @@ -198,7 +193,7 @@ public void testAgentStaysInVehicle() { Config config = ConfigUtils .loadConfig(configURL);; String outputDirectory = utils.getOutputDirectory(); - config.controler() + config.controller() .setOutputDirectory(outputDirectory); config.network().setTimeVariantNetwork(true); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -235,7 +230,7 @@ public void testAgentLeavesVehicleAtNextStop() { Config config = ConfigUtils .loadConfig(configURL); String outputDirectory = utils.getOutputDirectory(); - config.controler() + config.controller() .setOutputDirectory(outputDirectory); Scenario scenario = ScenarioUtils.loadScenario(config); scenario.getPopulation().getPersons().clear(); @@ -277,9 +272,8 @@ public void testAgentIsAtTeleportLegAndLeavesStop() { HashMap, Double> arrivalTimes = new HashMap<>(); HashMap, List> trips = new HashMap<>(); Config config = ConfigUtils.loadConfig(configURL); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); String outputDirectory = utils.getOutputDirectory(); - config.controler().setOutputDirectory(outputDirectory); + config.controller().setOutputDirectory(outputDirectory); Scenario scenario = ScenarioUtils.loadScenario(config); scenario.getPopulation().getPersons().clear(); double activityEndTime = 7. * 3600 + 22. * 60; @@ -296,8 +290,8 @@ public void testAgentIsAtTeleportLegAndLeavesStop() { assertEquals("Trip element has changed", "dummy@car_17bOut", trip.get(0)); assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(1)); assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(2)); - assertEquals("Trip element has changed", "pt interaction@pt7", trip.get(3)); - assertEquals("Trip element has changed", "pt interaction@pt7", trip.get(4)); + assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(3)); + assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(4)); assertEquals("Trip element has changed", "tr_334", trip.get(5)); assertEquals("Trip element has changed", "pt interaction@pt8", trip.get(6)); assertEquals("Trip element has changed", "pt interaction@pt8", trip.get(7)); @@ -318,10 +312,10 @@ public void testAgentIsAtTeleportLegAndWaitsAtStop_walkUnattractive() { Config config = ConfigUtils .loadConfig(configURL);; String outputDirectory = utils.getOutputDirectory(); - config.controler() + config.controller() .setOutputDirectory(outputDirectory); - config.planCalcScore().getModes().get(TransportMode.walk).setMarginalUtilityOfTraveling( - config.planCalcScore().getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - 3); + config.scoring().getModes().get(TransportMode.walk).setMarginalUtilityOfTraveling( + config.scoring().getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() - 3); Scenario scenario = ScenarioUtils.loadScenario(config); scenario.getPopulation().getPersons().clear(); double activityEndTime = 7. * 3600 + 22. * 60; @@ -356,9 +350,8 @@ public void testAgentIsAtTeleportLegAndWaitsAtStop() { HashMap, Double> arrivalTimes = new HashMap<>(); HashMap, List> trips = new HashMap<>(); Config config = ConfigUtils.loadConfig(configURL); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); String outputDirectory = utils.getOutputDirectory(); - config.controler().setOutputDirectory(outputDirectory); + config.controller().setOutputDirectory(outputDirectory); Scenario scenario = ScenarioUtils.loadScenario(config); scenario.getPopulation().getPersons().clear(); double activityEndTime = 7. * 3600 + 22. * 60; @@ -375,8 +368,8 @@ public void testAgentIsAtTeleportLegAndWaitsAtStop() { assertEquals("Trip element has changed", "dummy@car_17bOut", trip.get(0)); assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(1)); assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(2)); - assertEquals("Trip element has changed", "pt interaction@pt7", trip.get(3)); - assertEquals("Trip element has changed", "pt interaction@pt7", trip.get(4)); + assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(3)); + assertEquals("Trip element has changed", "pt interaction@pt6c", trip.get(4)); assertEquals("Trip element has changed", "tr_334", trip.get(5)); assertEquals("Trip element has changed", "pt interaction@pt8", trip.get(6)); assertEquals("Trip element has changed", "pt interaction@pt8", trip.get(7)); @@ -396,7 +389,7 @@ public void testOneAgentEveryFourSeconds() { Config config = ConfigUtils .loadConfig(configURL); String outputDirectory = utils.getOutputDirectory(); - config.controler() + config.controller() .setOutputDirectory(outputDirectory); Scenario scenario = ScenarioUtils.loadScenario(config); scenario.getPopulation().getPersons().clear(); @@ -421,7 +414,7 @@ public void testOneAgentEveryFourSeconds() { } assertTrue("Number of used lines ist not plausible", numberOfUsedLines == 1 || numberOfUsedLines == 2); } - System.out.println(config.controler().getOutputDirectory()); + System.out.println(config.controller().getOutputDirectory()); } diff --git a/contribs/vsp/src/test/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParametersNoSubpopulationTest.java b/contribs/vsp/src/test/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParametersNoSubpopulationTest.java index 7fb4fb7e312..f7a08b4ea4b 100644 --- a/contribs/vsp/src/test/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParametersNoSubpopulationTest.java +++ b/contribs/vsp/src/test/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParametersNoSubpopulationTest.java @@ -9,7 +9,7 @@ import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationFactory; 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.ScenarioConfigGroup; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; @@ -37,9 +37,9 @@ public class IncomeDependentUtilityOfMoneyPersonScoringParametersNoSubpopulation public void setUp() { TransitConfigGroup transitConfigGroup = new TransitConfigGroup(); ScenarioConfigGroup scenarioConfigGroup = new ScenarioConfigGroup(); - PlanCalcScoreConfigGroup planCalcScoreConfigGroup = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup scoringConfigGroup = new ScoringConfigGroup(); - PlanCalcScoreConfigGroup.ScoringParameterSet defaultParams = planCalcScoreConfigGroup.getOrCreateScoringParameters(null); + ScoringConfigGroup.ScoringParameterSet defaultParams = scoringConfigGroup.getOrCreateScoringParameters(null); defaultParams.setMarginalUtilityOfMoney(20); defaultParams.setMarginalUtlOfWaitingPt_utils_hr(0.5d * 3600); @@ -69,7 +69,7 @@ public void setUp() { } personScoringParams = new IncomeDependentUtilityOfMoneyPersonScoringParameters(population, - planCalcScoreConfigGroup, + scoringConfigGroup, scenarioConfigGroup, transitConfigGroup); } @@ -132,4 +132,4 @@ private void makeAssert(ScoringParameters params, double income, double marginal } -} \ No newline at end of file +} diff --git a/contribs/vsp/src/test/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParametersTest.java b/contribs/vsp/src/test/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParametersTest.java index 43b65dd4c82..daa410350d4 100644 --- a/contribs/vsp/src/test/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParametersTest.java +++ b/contribs/vsp/src/test/java/playground/vsp/scoring/IncomeDependentUtilityOfMoneyPersonScoringParametersTest.java @@ -6,7 +6,7 @@ import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationFactory; 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.ScenarioConfigGroup; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; @@ -34,13 +34,13 @@ public class IncomeDependentUtilityOfMoneyPersonScoringParametersTest { public void setUp() { TransitConfigGroup transitConfigGroup = new TransitConfigGroup(); ScenarioConfigGroup scenarioConfigGroup = new ScenarioConfigGroup(); - PlanCalcScoreConfigGroup planCalcScoreConfigGroup = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup scoringConfigGroup = new ScoringConfigGroup(); - PlanCalcScoreConfigGroup.ScoringParameterSet personParams = planCalcScoreConfigGroup.getOrCreateScoringParameters("person"); + ScoringConfigGroup.ScoringParameterSet personParams = scoringConfigGroup.getOrCreateScoringParameters("person"); personParams.setMarginalUtilityOfMoney(1); personParams.setMarginalUtlOfWaitingPt_utils_hr(0.5 * 3600); - PlanCalcScoreConfigGroup.ScoringParameterSet freightParams = planCalcScoreConfigGroup.getOrCreateScoringParameters("freight"); + ScoringConfigGroup.ScoringParameterSet freightParams = scoringConfigGroup.getOrCreateScoringParameters("freight"); freightParams.setMarginalUtilityOfMoney(444); freightParams.setMarginalUtlOfWaitingPt_utils_hr(1d * 3600); @@ -88,7 +88,7 @@ public void setUp() { population.addPerson(freightWithIncome2); } personScoringParams = new IncomeDependentUtilityOfMoneyPersonScoringParameters(population, - planCalcScoreConfigGroup, + scoringConfigGroup, scenarioConfigGroup, transitConfigGroup); } @@ -169,4 +169,4 @@ private void makeAssert(ScoringParameters params, double income, double marginal } -} \ No newline at end of file +} diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/output_allVehicles.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_allVehicles.xml.gz similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/output_allVehicles.xml.gz rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_allVehicles.xml.gz diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/output_carriers.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_carriers.xml.gz similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/output_carriers.xml.gz rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_carriers.xml.gz diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/output_events.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_events.xml.gz similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/output_events.xml.gz rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_events.xml.gz diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/output_network.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_network.xml.gz similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/output_network.xml.gz rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_network.xml.gz diff --git a/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/Carrier_stats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/Carrier_stats.tsv new file mode 100644 index 00000000000..21421192918 --- /dev/null +++ b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/Carrier_stats.tsv @@ -0,0 +1,2 @@ +carrierId MATSimScoreSelectedPlan jSpritScoreSelectedPlan nuOfTours nuOfShipments(input) nuOfServices(input) +carrier1 -263.4 null 2 0 7 diff --git a/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/Load_perVehicle.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/Load_perVehicle.tsv new file mode 100644 index 00000000000..8cff896d44c --- /dev/null +++ b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/Load_perVehicle.tsv @@ -0,0 +1 @@ +vehicleId capacity maxLoad load state during tour diff --git a/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/TimeDistance_perVehicle.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/TimeDistance_perVehicle.tsv new file mode 100644 index 00000000000..a3716b50cdc --- /dev/null +++ b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/TimeDistance_perVehicle.tsv @@ -0,0 +1 @@ +vehicleId carrierId vehicleTypeId tourId tourDuration[s] travelDistance[m] costPerSecond[EUR/s] costPerMeter[EUR/m] fixedCosts[EUR] varCostsTime[EUR] varCostsDist[EUR] totalCosts[EUR] diff --git a/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/TimeDistance_perVehicleType.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/TimeDistance_perVehicleType.tsv new file mode 100644 index 00000000000..dacd1779828 --- /dev/null +++ b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runFreightAnalysisEventBasedTest/TimeDistance_perVehicleType.tsv @@ -0,0 +1,2 @@ +vehicleTypeId nuOfVehicles SumOfTourDuration[s] SumOfTravelDistances[m] costPerSecond[EUR/s] costPerMeter[EUR/m] fixedCosts[EUR/veh] varCostsTime[EUR] varCostsDist[EUR] fixedCosts[EUR] totalCosts[EUR] +light 0 0.0 60000.0 0.008 4.7E-4 84.0 0.0 28.2 0.0 28.2 diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrierStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrierStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrierStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrierStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_##carrier1_tripStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_##carrier1_tripStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_##carrier1_tripStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_##carrier1_tripStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_##carrier1_vehicleStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_##carrier1_vehicleStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_##carrier1_vehicleStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_##carrier1_vehicleStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_ServiceStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_ServiceStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_ServiceStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_ServiceStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_ShipmentStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_ShipmentStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_ShipmentStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_ShipmentStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_VehicleTypeStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_VehicleTypeStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_VehicleTypeStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/carrier_carrier1_VehicleTypeStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/freightVehicleStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/freightVehicleStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/freightVehicleStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/freightVehicleStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/freightVehicleTripStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/freightVehicleTripStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/freightVehicleTripStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/freightVehicleTripStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/serviceStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/serviceStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/serviceStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/serviceStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/shipmentStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/shipmentStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisIT/compareResults/shipmentStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/compareResults/shipmentStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_allVehicles.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_allVehicles.xml.gz new file mode 100644 index 00000000000..199380ef6a0 Binary files /dev/null and b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_allVehicles.xml.gz differ diff --git a/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_carriers.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_carriers.xml.gz new file mode 100644 index 00000000000..f1423329b98 Binary files /dev/null and b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_carriers.xml.gz differ diff --git a/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_events.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_events.xml.gz new file mode 100644 index 00000000000..23e96d838a7 Binary files /dev/null and b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_events.xml.gz differ diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_network.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_network.xml.gz similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_network.xml.gz rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisIT/output_network.xml.gz diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrierStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrierStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrierStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrierStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_##carrier1_tripStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_##carrier1_tripStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_##carrier1_tripStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_##carrier1_tripStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_##carrier1_vehicleStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_##carrier1_vehicleStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_##carrier1_vehicleStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_##carrier1_vehicleStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_carrier1_ShipmentStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_carrier1_ShipmentStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_carrier1_ShipmentStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_carrier1_ShipmentStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_carrier1_VehicleTypeStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_carrier1_VehicleTypeStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_carrier1_VehicleTypeStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/carrier_carrier1_VehicleTypeStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/freightVehicleStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/freightVehicleStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/freightVehicleStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/freightVehicleStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/freightVehicleTripStats.tsv b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/freightVehicleTripStats.tsv similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/freightVehicleTripStats.tsv rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/compareResults/shipment/freightVehicleTripStats.tsv diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_allVehicles.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_allVehicles.xml.gz similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_allVehicles.xml.gz rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_allVehicles.xml.gz diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_carriers.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_carriers.xml.gz similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_carriers.xml.gz rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_carriers.xml.gz diff --git a/contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_events.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_events.xml.gz similarity index 100% rename from contribs/vsp/test/input/org/matsim/contrib/freight/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_events.xml.gz rename to contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_events.xml.gz diff --git a/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_network.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_network.xml.gz new file mode 100644 index 00000000000..cb668e2933b Binary files /dev/null and b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/RunFreightAnalysisWithShipmentTest/shipment/output_network.xml.gz differ diff --git a/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_events.xml.gz b/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_events.xml.gz index cde54cca414..e4bd42f3c0f 100644 Binary files a/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_events.xml.gz and b/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_events.xml.gz differ diff --git a/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_plans.xml.gz b/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_plans.xml.gz index 138f52486ac..2aee19d2e77 100644 Binary files a/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_plans.xml.gz and b/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_plans.xml.gz differ diff --git a/examples/scenarios/benchmark/config.xml b/examples/scenarios/benchmark/config.xml index 241477eaebc..21b81fe965a 100644 --- a/examples/scenarios/benchmark/config.xml +++ b/examples/scenarios/benchmark/config.xml @@ -16,7 +16,7 @@ - + @@ -27,16 +27,16 @@ - + - + - + - + @@ -75,8 +75,8 @@ - - + + diff --git a/examples/scenarios/berlin/config.xml b/examples/scenarios/berlin/config.xml index 00953b6ed19..849080d1798 100644 --- a/examples/scenarios/berlin/config.xml +++ b/examples/scenarios/berlin/config.xml @@ -15,19 +15,15 @@ - + - - - - - + - + @@ -75,8 +71,8 @@ - - + + diff --git a/examples/scenarios/berlin/config_multimodal.xml b/examples/scenarios/berlin/config_multimodal.xml index 79f0250d871..0e81bf84fa9 100644 --- a/examples/scenarios/berlin/config_multimodal.xml +++ b/examples/scenarios/berlin/config_multimodal.xml @@ -15,28 +15,28 @@ - + - - + + - + - + - + @@ -45,10 +45,10 @@ - - + + - + @@ -100,8 +100,8 @@ - - + + diff --git a/examples/scenarios/berlin/config_withinday.xml b/examples/scenarios/berlin/config_withinday.xml index 0b980b99c8e..63f74259e9b 100644 --- a/examples/scenarios/berlin/config_withinday.xml +++ b/examples/scenarios/berlin/config_withinday.xml @@ -15,31 +15,31 @@ - + - - + + - + - + - + - + @@ -87,8 +87,8 @@ - - + + diff --git a/examples/scenarios/chessboard/config.xml b/examples/scenarios/chessboard/config.xml index 1a2577bbfae..5520454364a 100755 --- a/examples/scenarios/chessboard/config.xml +++ b/examples/scenarios/chessboard/config.xml @@ -18,10 +18,10 @@ - - + + - + @@ -78,7 +78,7 @@ - + diff --git a/examples/scenarios/daganzo/config.xml b/examples/scenarios/daganzo/config.xml index 09883208ec4..154f0afdb82 100644 --- a/examples/scenarios/daganzo/config.xml +++ b/examples/scenarios/daganzo/config.xml @@ -16,7 +16,7 @@ - + @@ -25,7 +25,7 @@ - + @@ -45,9 +45,9 @@ - + - + @@ -71,7 +71,7 @@ - + diff --git a/examples/scenarios/dvrp-grid/eight_shared_taxi_config.xml b/examples/scenarios/dvrp-grid/eight_shared_taxi_config.xml index 9122ab3ee45..fa26707492f 100644 --- a/examples/scenarios/dvrp-grid/eight_shared_taxi_config.xml +++ b/examples/scenarios/dvrp-grid/eight_shared_taxi_config.xml @@ -33,20 +33,20 @@ - + - + - + diff --git a/examples/scenarios/dvrp-grid/generic_dvrp_one_taxi_config.xml b/examples/scenarios/dvrp-grid/generic_dvrp_one_taxi_config.xml index bddf61f8647..1573fab0bc1 100644 --- a/examples/scenarios/dvrp-grid/generic_dvrp_one_taxi_config.xml +++ b/examples/scenarios/dvrp-grid/generic_dvrp_one_taxi_config.xml @@ -20,20 +20,20 @@ - + - + - + diff --git a/examples/scenarios/dvrp-grid/multi_mode_one_shared_taxi_config.xml b/examples/scenarios/dvrp-grid/multi_mode_one_shared_taxi_config.xml index d8274d55658..4c218d03a23 100644 --- a/examples/scenarios/dvrp-grid/multi_mode_one_shared_taxi_config.xml +++ b/examples/scenarios/dvrp-grid/multi_mode_one_shared_taxi_config.xml @@ -64,14 +64,14 @@ - + - + @@ -85,7 +85,7 @@ - + diff --git a/examples/scenarios/dvrp-grid/multi_mode_one_taxi_config.xml b/examples/scenarios/dvrp-grid/multi_mode_one_taxi_config.xml index 57d4f8d4258..ffc5b9dea0a 100644 --- a/examples/scenarios/dvrp-grid/multi_mode_one_taxi_config.xml +++ b/examples/scenarios/dvrp-grid/multi_mode_one_taxi_config.xml @@ -76,14 +76,14 @@ - + - + @@ -101,7 +101,7 @@ - + diff --git a/examples/scenarios/dvrp-grid/one_etaxi_benchmark_config.xml b/examples/scenarios/dvrp-grid/one_etaxi_benchmark_config.xml index d6eb3f758d7..dc38c096a0c 100644 --- a/examples/scenarios/dvrp-grid/one_etaxi_benchmark_config.xml +++ b/examples/scenarios/dvrp-grid/one_etaxi_benchmark_config.xml @@ -56,7 +56,7 @@ - + @@ -68,13 +68,13 @@ - + - + diff --git a/examples/scenarios/dvrp-grid/one_etaxi_config.xml b/examples/scenarios/dvrp-grid/one_etaxi_config.xml index 1edcffbb546..87d69f624a7 100644 --- a/examples/scenarios/dvrp-grid/one_etaxi_config.xml +++ b/examples/scenarios/dvrp-grid/one_etaxi_config.xml @@ -56,20 +56,20 @@ - + - + - + diff --git a/examples/scenarios/dvrp-grid/one_shared_taxi_config.xml b/examples/scenarios/dvrp-grid/one_shared_taxi_config.xml index e0ccdd2ef74..4e59438bbff 100644 --- a/examples/scenarios/dvrp-grid/one_shared_taxi_config.xml +++ b/examples/scenarios/dvrp-grid/one_shared_taxi_config.xml @@ -39,20 +39,20 @@ - + - + - + diff --git a/examples/scenarios/dvrp-grid/one_taxi_and_one_shared_taxi_config.xml b/examples/scenarios/dvrp-grid/one_taxi_and_one_shared_taxi_config.xml index ddcb59aecb3..4d953cfcf33 100644 --- a/examples/scenarios/dvrp-grid/one_taxi_and_one_shared_taxi_config.xml +++ b/examples/scenarios/dvrp-grid/one_taxi_and_one_shared_taxi_config.xml @@ -52,14 +52,14 @@ - + - + @@ -68,7 +68,7 @@ - + diff --git a/examples/scenarios/dvrp-grid/one_taxi_benchmark_config.xml b/examples/scenarios/dvrp-grid/one_taxi_benchmark_config.xml index 0186ae8ff51..541d14ca29b 100644 --- a/examples/scenarios/dvrp-grid/one_taxi_benchmark_config.xml +++ b/examples/scenarios/dvrp-grid/one_taxi_benchmark_config.xml @@ -37,7 +37,7 @@ - + @@ -49,13 +49,13 @@ - + - + diff --git a/examples/scenarios/dvrp-grid/one_taxi_config.xml b/examples/scenarios/dvrp-grid/one_taxi_config.xml index 140d79c8953..5cef94a0c96 100644 --- a/examples/scenarios/dvrp-grid/one_taxi_config.xml +++ b/examples/scenarios/dvrp-grid/one_taxi_config.xml @@ -37,20 +37,20 @@ - + - + - + diff --git a/examples/scenarios/dvrp-grid/one_taxi_one_truck_config.xml b/examples/scenarios/dvrp-grid/one_taxi_one_truck_config.xml index a8ea3bdb0f1..af587298e73 100644 --- a/examples/scenarios/dvrp-grid/one_taxi_one_truck_config.xml +++ b/examples/scenarios/dvrp-grid/one_taxi_one_truck_config.xml @@ -25,20 +25,20 @@ - + - + - + diff --git a/examples/scenarios/dvrp-grid/one_truck_config.xml b/examples/scenarios/dvrp-grid/one_truck_config.xml index b53844fbb4e..70ea1977db0 100644 --- a/examples/scenarios/dvrp-grid/one_truck_config.xml +++ b/examples/scenarios/dvrp-grid/one_truck_config.xml @@ -21,7 +21,7 @@ - + diff --git a/examples/scenarios/emissions-sampleScenario/testv2_Vehv1/config_average.xml b/examples/scenarios/emissions-sampleScenario/testv2_Vehv1/config_average.xml index 2016ff10164..854b768ce28 100644 --- a/examples/scenarios/emissions-sampleScenario/testv2_Vehv1/config_average.xml +++ b/examples/scenarios/emissions-sampleScenario/testv2_Vehv1/config_average.xml @@ -4,7 +4,7 @@ - + @@ -65,7 +65,7 @@ - + @@ -76,7 +76,7 @@ - + @@ -196,7 +196,7 @@ - + @@ -247,14 +247,14 @@ - + - + - + diff --git a/examples/scenarios/emissions-sampleScenario/testv2_Vehv1/config_detailed.xml b/examples/scenarios/emissions-sampleScenario/testv2_Vehv1/config_detailed.xml index e66a0b4cda0..f3e81cbbf33 100644 --- a/examples/scenarios/emissions-sampleScenario/testv2_Vehv1/config_detailed.xml +++ b/examples/scenarios/emissions-sampleScenario/testv2_Vehv1/config_detailed.xml @@ -4,7 +4,7 @@ - + @@ -69,7 +69,7 @@ - + @@ -80,7 +80,7 @@ - + @@ -200,7 +200,7 @@ - + @@ -251,14 +251,14 @@ - + - + - + diff --git a/examples/scenarios/emissions-sampleScenario/testv2_Vehv2/config_average.xml b/examples/scenarios/emissions-sampleScenario/testv2_Vehv2/config_average.xml index 38682a2a37e..ada64770327 100644 --- a/examples/scenarios/emissions-sampleScenario/testv2_Vehv2/config_average.xml +++ b/examples/scenarios/emissions-sampleScenario/testv2_Vehv2/config_average.xml @@ -4,7 +4,7 @@ - + @@ -58,7 +58,7 @@ - + @@ -69,7 +69,7 @@ - + @@ -189,7 +189,7 @@ - + @@ -240,14 +240,14 @@ - + - + - + diff --git a/examples/scenarios/emissions-sampleScenario/testv2_Vehv2/config_detailed.xml b/examples/scenarios/emissions-sampleScenario/testv2_Vehv2/config_detailed.xml index 14a268b8fe4..3390afc888d 100644 --- a/examples/scenarios/emissions-sampleScenario/testv2_Vehv2/config_detailed.xml +++ b/examples/scenarios/emissions-sampleScenario/testv2_Vehv2/config_detailed.xml @@ -4,7 +4,7 @@ - + @@ -66,7 +66,7 @@ - + @@ -77,7 +77,7 @@ - + @@ -197,7 +197,7 @@ - + @@ -250,14 +250,14 @@ - + - + - + - + diff --git a/examples/scenarios/equil-extended/config-with-lanes.xml b/examples/scenarios/equil-extended/config-with-lanes.xml index f46e5632c55..dfb69732040 100644 --- a/examples/scenarios/equil-extended/config-with-lanes.xml +++ b/examples/scenarios/equil-extended/config-with-lanes.xml @@ -16,7 +16,7 @@ - + @@ -30,13 +30,13 @@ - + - + - + @@ -70,8 +70,8 @@ - - + + @@ -84,7 +84,7 @@ - + diff --git a/examples/scenarios/equil-extended/config-with-network-change-events.xml b/examples/scenarios/equil-extended/config-with-network-change-events.xml index bf5335cb38c..c592ad75e20 100644 --- a/examples/scenarios/equil-extended/config-with-network-change-events.xml +++ b/examples/scenarios/equil-extended/config-with-network-change-events.xml @@ -17,26 +17,26 @@ - + - + - + - + - + @@ -70,8 +70,8 @@ - - + + diff --git a/examples/scenarios/equil-extended/config-with-roadpricing.xml b/examples/scenarios/equil-extended/config-with-roadpricing.xml index 3801d88f0fb..3cb0f97280a 100644 --- a/examples/scenarios/equil-extended/config-with-roadpricing.xml +++ b/examples/scenarios/equil-extended/config-with-roadpricing.xml @@ -19,26 +19,26 @@ - + - + - + - + - + @@ -72,8 +72,8 @@ - - + + diff --git a/examples/scenarios/equil-extended/config-with-subpopulation.xml b/examples/scenarios/equil-extended/config-with-subpopulation.xml index f70c0eb319f..234267d8d6a 100644 --- a/examples/scenarios/equil-extended/config-with-subpopulation.xml +++ b/examples/scenarios/equil-extended/config-with-subpopulation.xml @@ -4,13 +4,13 @@ - + - + @@ -37,8 +37,8 @@ - - + + @@ -99,7 +99,7 @@ - + diff --git a/examples/scenarios/equil-extended/config.xml b/examples/scenarios/equil-extended/config.xml index b1822bd96cf..eb3d56e93c2 100644 --- a/examples/scenarios/equil-extended/config.xml +++ b/examples/scenarios/equil-extended/config.xml @@ -15,26 +15,26 @@ - + - + - + - + - + @@ -68,8 +68,8 @@ - - + + diff --git a/examples/scenarios/equil-mixedTraffic/config-with-all-vehicles-from-file.xml b/examples/scenarios/equil-mixedTraffic/config-with-all-vehicles-from-file.xml index 20a7f3c6b53..2ed4aa5e123 100644 --- a/examples/scenarios/equil-mixedTraffic/config-with-all-vehicles-from-file.xml +++ b/examples/scenarios/equil-mixedTraffic/config-with-all-vehicles-from-file.xml @@ -15,34 +15,34 @@ - + - + - + - + - + - + - + @@ -51,7 +51,7 @@ - + @@ -59,18 +59,18 @@ - + - - + + - + - + - - + + @@ -83,10 +83,10 @@ - + - + diff --git a/examples/scenarios/equil-mixedTraffic/config-with-mode-vehicles.xml b/examples/scenarios/equil-mixedTraffic/config-with-mode-vehicles.xml index 8eeb8ddf395..138d6918359 100644 --- a/examples/scenarios/equil-mixedTraffic/config-with-mode-vehicles.xml +++ b/examples/scenarios/equil-mixedTraffic/config-with-mode-vehicles.xml @@ -15,34 +15,34 @@ - + - + - + - + - + - + - + @@ -51,7 +51,7 @@ - + @@ -59,18 +59,18 @@ - + - - + + - + - + - - + + @@ -83,10 +83,10 @@ - + - + diff --git a/examples/scenarios/equil/config.xml b/examples/scenarios/equil/config.xml index f7f24bc1708..b84cf324be0 100755 --- a/examples/scenarios/equil/config.xml +++ b/examples/scenarios/equil/config.xml @@ -20,7 +20,7 @@ - + @@ -30,13 +30,13 @@ - + - + - + @@ -73,8 +73,8 @@ - - + + diff --git a/examples/scenarios/equil/config_plans1.xml b/examples/scenarios/equil/config_plans1.xml index e08dc1a38d5..8a3be162708 100755 --- a/examples/scenarios/equil/config_plans1.xml +++ b/examples/scenarios/equil/config_plans1.xml @@ -20,7 +20,7 @@ - + @@ -35,9 +35,9 @@ - + - + @@ -71,8 +71,8 @@ - - + + diff --git a/examples/scenarios/evacuation-tutorial/evacuationConf.xml b/examples/scenarios/evacuation-tutorial/evacuationConf.xml index 0c2e62fe5d1..ee717e515f4 100644 --- a/examples/scenarios/evacuation-tutorial/evacuationConf.xml +++ b/examples/scenarios/evacuation-tutorial/evacuationConf.xml @@ -29,7 +29,7 @@ - + @@ -45,11 +45,10 @@ - + - - + @@ -84,7 +83,7 @@ - + diff --git a/examples/scenarios/evacuation-tutorial/withinDayEvacuationConf.xml b/examples/scenarios/evacuation-tutorial/withinDayEvacuationConf.xml index 5e7845adf1b..c2c376cc27a 100644 --- a/examples/scenarios/evacuation-tutorial/withinDayEvacuationConf.xml +++ b/examples/scenarios/evacuation-tutorial/withinDayEvacuationConf.xml @@ -17,17 +17,16 @@ - - + - + @@ -36,12 +35,11 @@ - + - - + @@ -53,11 +51,10 @@ - + - - + @@ -92,7 +89,7 @@ - + diff --git a/examples/scenarios/example8DemandGeneration/config.xml b/examples/scenarios/example8DemandGeneration/config.xml index 2255459c59b..3daebaca573 100644 --- a/examples/scenarios/example8DemandGeneration/config.xml +++ b/examples/scenarios/example8DemandGeneration/config.xml @@ -11,7 +11,7 @@ - + @@ -23,7 +23,7 @@ - + @@ -41,6 +41,6 @@ - + diff --git a/examples/scenarios/freight-chessboard-9x9/config.xml b/examples/scenarios/freight-chessboard-9x9/config.xml index 8a811ca100c..369971fb320 100644 --- a/examples/scenarios/freight-chessboard-9x9/config.xml +++ b/examples/scenarios/freight-chessboard-9x9/config.xml @@ -11,7 +11,7 @@ - + @@ -24,7 +24,7 @@ - + @@ -55,7 +55,7 @@ - + diff --git a/examples/scenarios/gridCarRestrictedInCenter/gridCarRestrictedInCenter_config.xml b/examples/scenarios/gridCarRestrictedInCenter/gridCarRestrictedInCenter_config.xml index bed46db24b6..106e768f27d 100644 --- a/examples/scenarios/gridCarRestrictedInCenter/gridCarRestrictedInCenter_config.xml +++ b/examples/scenarios/gridCarRestrictedInCenter/gridCarRestrictedInCenter_config.xml @@ -33,20 +33,20 @@ - + - + - + diff --git a/examples/scenarios/itsumo-sesam-scenario/config.xml b/examples/scenarios/itsumo-sesam-scenario/config.xml index 55fb23c70ff..ede3a701136 100755 --- a/examples/scenarios/itsumo-sesam-scenario/config.xml +++ b/examples/scenarios/itsumo-sesam-scenario/config.xml @@ -20,7 +20,7 @@ - + @@ -36,9 +36,9 @@ - + - + @@ -62,8 +62,8 @@ - - + + diff --git a/examples/scenarios/kelheim/config-with-drt.xml b/examples/scenarios/kelheim/config-with-drt.xml index e6f59db2d7d..76020e10903 100644 --- a/examples/scenarios/kelheim/config-with-drt.xml +++ b/examples/scenarios/kelheim/config-with-drt.xml @@ -1,11 +1,11 @@ - + - + @@ -43,7 +43,7 @@ - + @@ -73,7 +73,7 @@ - + @@ -142,7 +142,7 @@ - + diff --git a/examples/scenarios/kelheim/config.xml b/examples/scenarios/kelheim/config.xml index 7419c8e3a38..885e8191c67 100644 --- a/examples/scenarios/kelheim/config.xml +++ b/examples/scenarios/kelheim/config.xml @@ -1,11 +1,11 @@ - + - + @@ -43,7 +43,7 @@ - + @@ -73,7 +73,7 @@ - + @@ -140,7 +140,7 @@ - + @@ -215,4 +215,4 @@ - \ No newline at end of file + diff --git a/examples/scenarios/lesson-3/config.xml b/examples/scenarios/lesson-3/config.xml index a76f8c5351c..ed7b4aaae1f 100644 --- a/examples/scenarios/lesson-3/config.xml +++ b/examples/scenarios/lesson-3/config.xml @@ -3,34 +3,34 @@ - + - + - + - + - + - + @@ -39,13 +39,13 @@ - + - + - + @@ -54,9 +54,9 @@ - + - + @@ -67,7 +67,7 @@ - + @@ -85,20 +85,19 @@ - - + + - - - + + - - + + - + - + @@ -160,707 +159,707 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -878,6 +877,6 @@ - + diff --git a/examples/scenarios/mielec/mielec_drt_config.xml b/examples/scenarios/mielec/mielec_drt_config.xml index d19574049e0..db2a8763ade 100644 --- a/examples/scenarios/mielec/mielec_drt_config.xml +++ b/examples/scenarios/mielec/mielec_drt_config.xml @@ -49,20 +49,20 @@ - + - + - + diff --git a/examples/scenarios/mielec/mielec_edrt_config.xml b/examples/scenarios/mielec/mielec_edrt_config.xml index a230fe0c3cd..fdb3bd3c0f6 100644 --- a/examples/scenarios/mielec/mielec_edrt_config.xml +++ b/examples/scenarios/mielec/mielec_edrt_config.xml @@ -66,20 +66,20 @@ - + - + - + diff --git a/examples/scenarios/mielec/mielec_etaxi_benchmark_config.xml b/examples/scenarios/mielec/mielec_etaxi_benchmark_config.xml index 7e17db28699..5102b37d246 100644 --- a/examples/scenarios/mielec/mielec_etaxi_benchmark_config.xml +++ b/examples/scenarios/mielec/mielec_etaxi_benchmark_config.xml @@ -52,20 +52,20 @@ - + - + - + diff --git a/examples/scenarios/mielec/mielec_etaxi_config.xml b/examples/scenarios/mielec/mielec_etaxi_config.xml index 350877df1eb..59bfc20c581 100644 --- a/examples/scenarios/mielec/mielec_etaxi_config.xml +++ b/examples/scenarios/mielec/mielec_etaxi_config.xml @@ -58,20 +58,20 @@ - + - + - + diff --git a/examples/scenarios/mielec/mielec_etaxi_config_assignment.xml b/examples/scenarios/mielec/mielec_etaxi_config_assignment.xml index 501ef7e9364..b5df7dc9a9e 100644 --- a/examples/scenarios/mielec/mielec_etaxi_config_assignment.xml +++ b/examples/scenarios/mielec/mielec_etaxi_config_assignment.xml @@ -65,20 +65,20 @@ - + - + - + diff --git a/examples/scenarios/mielec/mielec_serviceArea_based_drt_config.xml b/examples/scenarios/mielec/mielec_serviceArea_based_drt_config.xml index 2af263fd983..d2bdd9305f7 100644 --- a/examples/scenarios/mielec/mielec_serviceArea_based_drt_config.xml +++ b/examples/scenarios/mielec/mielec_serviceArea_based_drt_config.xml @@ -63,20 +63,20 @@ - + - + - + diff --git a/examples/scenarios/mielec/mielec_stop_based_drt_config.xml b/examples/scenarios/mielec/mielec_stop_based_drt_config.xml index a7ca57a91aa..dd3df82fa60 100644 --- a/examples/scenarios/mielec/mielec_stop_based_drt_config.xml +++ b/examples/scenarios/mielec/mielec_stop_based_drt_config.xml @@ -59,20 +59,20 @@ - + - + - + diff --git a/examples/scenarios/mielec/mielec_taxi_benchmark_config.xml b/examples/scenarios/mielec/mielec_taxi_benchmark_config.xml index ac460c08fd5..f94bca1d15e 100644 --- a/examples/scenarios/mielec/mielec_taxi_benchmark_config.xml +++ b/examples/scenarios/mielec/mielec_taxi_benchmark_config.xml @@ -37,7 +37,7 @@ - + @@ -49,13 +49,13 @@ - + - + diff --git a/examples/scenarios/mielec/mielec_taxi_config.xml b/examples/scenarios/mielec/mielec_taxi_config.xml index ecfabf7d988..43389699cba 100644 --- a/examples/scenarios/mielec/mielec_taxi_config.xml +++ b/examples/scenarios/mielec/mielec_taxi_config.xml @@ -43,20 +43,20 @@ - + - + - + diff --git a/examples/scenarios/mielec/mielec_taxi_mini_benchmark_config.xml b/examples/scenarios/mielec/mielec_taxi_mini_benchmark_config.xml index c0441f76a5c..8ab14beb61a 100644 --- a/examples/scenarios/mielec/mielec_taxi_mini_benchmark_config.xml +++ b/examples/scenarios/mielec/mielec_taxi_mini_benchmark_config.xml @@ -33,7 +33,7 @@ - + @@ -45,13 +45,13 @@ - + - + diff --git a/examples/scenarios/pt-simple-lineswitch/config.xml b/examples/scenarios/pt-simple-lineswitch/config.xml index 967c37eeec3..ab0b7d7481f 100644 --- a/examples/scenarios/pt-simple-lineswitch/config.xml +++ b/examples/scenarios/pt-simple-lineswitch/config.xml @@ -22,11 +22,11 @@ - + - + @@ -47,8 +47,8 @@ - - + + @@ -80,8 +80,8 @@ - - + + @@ -115,6 +115,6 @@ - + diff --git a/examples/scenarios/pt-simple/config.xml b/examples/scenarios/pt-simple/config.xml index 19ee7006e9f..c97a2ce0874 100644 --- a/examples/scenarios/pt-simple/config.xml +++ b/examples/scenarios/pt-simple/config.xml @@ -22,23 +22,23 @@ - + - + - + - + @@ -46,8 +46,8 @@ - - + + @@ -80,8 +80,8 @@ - - + + @@ -115,6 +115,6 @@ - + diff --git a/examples/scenarios/pt-tutorial/0.config.xml b/examples/scenarios/pt-tutorial/0.config.xml index 72dd8e2c6f2..53354abfbef 100644 --- a/examples/scenarios/pt-tutorial/0.config.xml +++ b/examples/scenarios/pt-tutorial/0.config.xml @@ -15,7 +15,7 @@ - + @@ -27,13 +27,13 @@ - + - + - + @@ -82,8 +82,8 @@ - - + + @@ -113,7 +113,7 @@ - + diff --git a/examples/scenarios/ptdisturbances/config.xml b/examples/scenarios/ptdisturbances/config.xml index 1da30fbc8cd..a2d9036aaee 100644 --- a/examples/scenarios/ptdisturbances/config.xml +++ b/examples/scenarios/ptdisturbances/config.xml @@ -1,7 +1,7 @@ - + @@ -15,7 +15,7 @@ - + @@ -56,7 +56,7 @@ - + diff --git a/examples/scenarios/roundabout/config.xml b/examples/scenarios/roundabout/config.xml index 01d5c3494e5..35877624a50 100644 --- a/examples/scenarios/roundabout/config.xml +++ b/examples/scenarios/roundabout/config.xml @@ -11,7 +11,7 @@ - + @@ -24,9 +24,9 @@ - + - + @@ -59,7 +59,7 @@ - + diff --git a/examples/scenarios/siouxfalls-2014/config_default.xml b/examples/scenarios/siouxfalls-2014/config_default.xml index a3cf7ab6ede..237bf23ed66 100644 --- a/examples/scenarios/siouxfalls-2014/config_default.xml +++ b/examples/scenarios/siouxfalls-2014/config_default.xml @@ -10,13 +10,13 @@ - + - - + + @@ -25,7 +25,7 @@ - + @@ -43,13 +43,13 @@ - + - + - + @@ -107,8 +107,8 @@ - - + + @@ -134,10 +134,10 @@ - + - + @@ -158,7 +158,7 @@ - + @@ -170,13 +170,13 @@ - + - - - \ No newline at end of file + + + diff --git a/examples/scenarios/two-routes/config.xml b/examples/scenarios/two-routes/config.xml index 3f5538f6c9e..bb3bc0b91fc 100644 --- a/examples/scenarios/two-routes/config.xml +++ b/examples/scenarios/two-routes/config.xml @@ -2,7 +2,7 @@ - + @@ -11,7 +11,7 @@ - + @@ -21,14 +21,14 @@ - + - + - + @@ -58,8 +58,8 @@ - - + + @@ -72,5 +72,5 @@ - - \ No newline at end of file + + diff --git a/matsim/pom.xml b/matsim/pom.xml index b7feb34e61d..4dc0348e536 100644 --- a/matsim/pom.xml +++ b/matsim/pom.xml @@ -203,7 +203,7 @@ com.github.luben zstd-jni - 1.5.5-5 + 1.5.5-6 jakarta.validation diff --git a/matsim/src/main/java/ch/sbb/matsim/RunSwissRailRaptorExample.java b/matsim/src/main/java/ch/sbb/matsim/RunSwissRailRaptorExample.java index 8d4cd0a7e36..ead8406f0c6 100644 --- a/matsim/src/main/java/ch/sbb/matsim/RunSwissRailRaptorExample.java +++ b/matsim/src/main/java/ch/sbb/matsim/RunSwissRailRaptorExample.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorModule; diff --git a/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java b/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java index 024a101002e..2473517c9d1 100644 --- a/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java +++ b/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.config; import com.google.common.base.Verify; @@ -45,6 +60,8 @@ public class SwissRailRaptorConfigGroup extends ReflectiveConfigGroup { private static final String PARAM_TRANSFER_WALK_MARGIN = "transferWalkMargin"; private static final String PARAM_TRANSFER_WALK_MARGIN_DESC = "time deducted from transfer walk leg during transfers between pt legs in order to avoid missing a vehicle by a few seconds due to delays."; + private static final String PARAM_INTERMODAL_LEG_ONLYHANDLING = "intermodalLegOnlyHandling"; + private static final String PARAM_INTERMODAL_LEG_ONLYHANDLING_DESC = "Define how routes containing only intermodal legs are handled: Useful options: alllow, avoid, forbid"; private boolean useRangeQuery = false; private boolean useIntermodality = false; @@ -57,6 +74,7 @@ public class SwissRailRaptorConfigGroup extends ReflectiveConfigGroup { private double transferPenaltyMaxCost = Double.POSITIVE_INFINITY; private double transferPenaltyHourlyCost = 0; private double transferWalkMargin = 5; + private IntermodalLegOnlyHandling intermodalLegOnlyHandling = IntermodalLegOnlyHandling.forbid; private ScoringParameters scoringParameters = ScoringParameters.Default; @@ -69,7 +87,27 @@ public class SwissRailRaptorConfigGroup extends ReflectiveConfigGroup { public enum IntermodalAccessEgressModeSelection { CalcLeastCostModePerStop, RandomSelectOneModePerRoutingRequestAndDirection } - + + public enum IntermodalLegOnlyHandling { + /** + * allows transit routes that only consist of intermodal feeder legs if these have the lowest cost. + */ + allow, + /** + * avoids transit routes that only consist of feeder routes, unless no route containing at least one pt leg is found + */ + avoid, + /** + * explicitly forbids such routes, tries to find a pt route and returns null if nothing is found + */ + forbid, + /** + * mimics the behaviour implemented between 2019 and 2023. Returns null if a purely intermodal route has the lowest cost, does not check if a real pt route exists. + */ + @Deprecated + returnNull + } + public enum ScoringParameters { Default, Individual } @@ -78,7 +116,24 @@ public SwissRailRaptorConfigGroup() { super(GROUP); } - @StringGetter(PARAM_USE_RANGE_QUERY) + @StringSetter(PARAM_INTERMODAL_LEG_ONLYHANDLING) + public void setIntermodalLegOnlyHandling(String intermodalLegOnlyHandling) { + this.intermodalLegOnlyHandling = IntermodalLegOnlyHandling.valueOf(intermodalLegOnlyHandling); + } + public void setIntermodalLegOnlyHandling(IntermodalLegOnlyHandling intermodalLegOnlyHandling) { + this.intermodalLegOnlyHandling = intermodalLegOnlyHandling; + } + + @StringGetter(PARAM_INTERMODAL_LEG_ONLYHANDLING) + public String getIntermodalLegOnlyHandlingString() { + return intermodalLegOnlyHandling.toString(); + } + + public IntermodalLegOnlyHandling getIntermodalLegOnlyHandling() { + return intermodalLegOnlyHandling; + } + + @StringGetter(PARAM_USE_RANGE_QUERY) public boolean isUseRangeQuery() { return this.useRangeQuery; } @@ -284,7 +339,8 @@ public Collection getModeMappingForPasseng return this.modeMappingForPassengersByRouteMode.values(); } - public static class RangeQuerySettingsParameterSet extends ReflectiveConfigGroup { + + public static class RangeQuerySettingsParameterSet extends ReflectiveConfigGroup { private static final String TYPE = "rangeQuerySettings"; @@ -459,7 +515,7 @@ public IntermodalAccessEgressParameterSet setMaxRadius(double maxRadius) { this.maxRadius = maxRadius; return this ; } - + @StringGetter(PARAM_INITIAL_SEARCH_RADIUS) public double getInitialSearchRadius() { return initialSearchRadius; @@ -470,7 +526,7 @@ public IntermodalAccessEgressParameterSet setInitialSearchRadius(double initialS this.initialSearchRadius = initialSearchRadius; return this ; } - + @StringGetter(PARAM_SEARCH_EXTENSION_RADIUS) public double getSearchExtensionRadius() { return searchExtensionRadius; @@ -536,7 +592,7 @@ public IntermodalAccessEgressParameterSet setStopFilterValue(String stopFilterVa this.stopFilterValue = stopFilterValue; return this ; } - + @StringGetter(PARAM_SHARE_TRIP_SEARCH_RADIUS) public double getShareTripSearchRadius() { return shareTripSearchRadius; @@ -560,7 +616,7 @@ public Map getComments() { map.put(PARAM_INITIAL_SEARCH_RADIUS, "Radius from the origin / destination coord in which transit stops are searched. Only if less than 2 transit stops are found the search radius is increased step-wise until the maximum search radius set in param radius is reached."); map.put(PARAM_SEARCH_EXTENSION_RADIUS, "If less than 2 stops were found in initialSearchRadius take the distance of the closest transit stop and add this extension radius to search again.The search radius will not exceed the maximum search radius set in param radius. Default is 200 meters."); map.put(PARAM_SHARE_TRIP_SEARCH_RADIUS, "The share of the trip crowfly distance within which the stops for access and egress will be searched for. This is a harder constraint than initial search radius. Default is positive infinity."); - + return map; } } diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/CapacityDependentInVehicleCostCalculator.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/CapacityDependentInVehicleCostCalculator.java index 5736b305ea6..00cc019b720 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/CapacityDependentInVehicleCostCalculator.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/CapacityDependentInVehicleCostCalculator.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.matsim.api.core.v01.population.Person; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/ConfigurableRaptorRouteSelector.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/ConfigurableRaptorRouteSelector.java index f3c75972829..80d3be07024 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/ConfigurableRaptorRouteSelector.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/ConfigurableRaptorRouteSelector.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.matsim.core.gbl.MatsimRandom; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorInVehicleCostCalculator.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorInVehicleCostCalculator.java index 17b6dfb50de..bb684485e41 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorInVehicleCostCalculator.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorInVehicleCostCalculator.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.matsim.api.core.v01.population.Person; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorIntermodalAccessEgress.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorIntermodalAccessEgress.java index 8908831b1bd..a900e79e945 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorIntermodalAccessEgress.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorIntermodalAccessEgress.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.List; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorParametersForPerson.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorParametersForPerson.java index a83e951789b..be18feaffa2 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorParametersForPerson.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorParametersForPerson.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.matsim.api.core.v01.population.Person; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorStopFinder.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorStopFinder.java index 71a0d2bbff9..ab7ee9948bb 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorStopFinder.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorStopFinder.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.ArrayList; @@ -31,6 +50,7 @@ import org.matsim.core.utils.collections.QuadTree; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.facilities.Facility; +import org.matsim.pt.transitSchedule.TransitScheduleUtils; import org.matsim.pt.transitSchedule.api.TransitStopFacility; import org.matsim.utils.objectattributes.attributable.Attributes; @@ -86,7 +106,8 @@ private List findAccessStops(Facility fromFacility, Facility toFaci List stops = findNearbyStops(fromFacility, parameters, data); List initialStops = stops.stream().map(stop -> { double beelineDistance = CoordUtils.calcEuclideanDistance(stop.getCoord(), fromFacility.getCoord()); - double travelTime = Math.ceil(beelineDistance / parameters.getBeelineWalkSpeed()); + double accessTime = TransitScheduleUtils.getStopAccessTime(stop); + double travelTime = Math.ceil(beelineDistance / parameters.getBeelineWalkSpeed()) + accessTime; double disutility = travelTime * -parameters.getMarginalUtilityOfTravelTime_utl_s(TransportMode.walk); return new InitialStop(stop, disutility, travelTime, beelineDistance * distanceFactor, TransportMode.walk); }).collect(Collectors.toList()); @@ -103,7 +124,8 @@ private List findEgressStops(Facility fromFacility, Facility toFaci List stops = findNearbyStops(toFacility, parameters, data); List initialStops = stops.stream().map(stop -> { double beelineDistance = CoordUtils.calcEuclideanDistance(stop.getCoord(), toFacility.getCoord()); - double travelTime = Math.ceil(beelineDistance / parameters.getBeelineWalkSpeed()); + double egressTime = TransitScheduleUtils.getStopEgressTime(stop); + double travelTime = Math.ceil(beelineDistance / parameters.getBeelineWalkSpeed()) + egressTime; double disutility = travelTime * -parameters.getMarginalUtilityOfTravelTime_utl_s(TransportMode.walk); return new InitialStop(stop, disutility, travelTime, beelineDistance * distanceFactor, TransportMode.walk); }).collect(Collectors.toList()); @@ -204,26 +226,28 @@ private void addInitialStopsForParamSet(Facility fromFacility, Facility toFacili // the router for the access/egress mode could not find a route, skip that access/egress mode continue; } - if (stopFacility != stop) { - if (direction == Direction.ACCESS) { - Leg transferLeg = PopulationUtils.createLeg(TransportMode.walk); - Route transferRoute = RouteUtils.createGenericRouteImpl(stopFacility.getLinkId(), stop.getLinkId()); - transferRoute.setTravelTime(0); - transferRoute.setDistance(0); - transferLeg.setRoute(transferRoute); - transferLeg.setTravelTime(0); + double accessTime = TransitScheduleUtils.getStopAccessTime(stop); + double egressTime = TransitScheduleUtils.getStopEgressTime(stop); + if ((stopFacility != stop) || accessTime>0.0 || egressTime>0.0) { + if (direction == Direction.ACCESS) { + Leg transferLeg = PopulationUtils.createLeg(TransportMode.walk); + Route transferRoute = RouteUtils.createGenericRouteImpl(stopFacility.getLinkId(), stop.getLinkId()); + transferRoute.setTravelTime(accessTime); + transferRoute.setDistance(0); + transferLeg.setRoute(transferRoute); + transferLeg.setTravelTime(accessTime); - List tmp = new ArrayList<>(routeParts.size() + 1); - tmp.addAll(routeParts); - tmp.add(transferLeg); - routeParts = tmp; - } else { - Leg transferLeg = PopulationUtils.createLeg(TransportMode.walk); - Route transferRoute = RouteUtils.createGenericRouteImpl(stop.getLinkId(), stopFacility.getLinkId()); - transferRoute.setTravelTime(0); + List tmp = new ArrayList<>(routeParts.size() + 1); + tmp.addAll(routeParts); + tmp.add(transferLeg); + routeParts = tmp; + } else { + Leg transferLeg = PopulationUtils.createLeg(TransportMode.walk); + Route transferRoute = RouteUtils.createGenericRouteImpl(stop.getLinkId(), stopFacility.getLinkId()); + transferRoute.setTravelTime(egressTime); transferRoute.setDistance(0); transferLeg.setRoute(transferRoute); - transferLeg.setTravelTime(0); + transferLeg.setTravelTime(egressTime); List tmp = new ArrayList<>(routeParts.size() + 1); tmp.add(transferLeg); diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorTransferCostCalculator.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorTransferCostCalculator.java index 3e7578e0e81..5522400f8cb 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorTransferCostCalculator.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorTransferCostCalculator.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.function.Supplier; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/IndividualRaptorParametersForPerson.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/IndividualRaptorParametersForPerson.java index 26e95cb0a7b..fb5eb9a020b 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/IndividualRaptorParametersForPerson.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/IndividualRaptorParametersForPerson.java @@ -1,10 +1,29 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; import org.matsim.api.core.v01.population.Person; 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.scoring.functions.ModeUtilityParameters; import org.matsim.core.scoring.functions.ScoringParameters; import org.matsim.core.scoring.functions.ScoringParametersForPerson; @@ -41,9 +60,9 @@ public RaptorParameters getRaptorParameters(Person person) { raptorParameters.setMarginalUtilityOfWaitingPt_utl_s( scoringParameters.marginalUtilityOfWaitingPt_s - marginalUtilityOfPerforming); - PlanCalcScoreConfigGroup pcsConfig = config.planCalcScore(); + ScoringConfigGroup pcsConfig = config.scoring(); - for (Map.Entry e : pcsConfig.getModes().entrySet()) { + for (Map.Entry e : pcsConfig.getModes().entrySet()) { String mode = e.getKey(); ModeUtilityParameters modeParams = scoringParameters.modeParams.get(mode); diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/InitialStop.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/InitialStop.java index ab39246b16e..822c5a0cab6 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/InitialStop.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/InitialStop.java @@ -1,6 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2017. - */ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/LeastCostRaptorRouteSelector.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/LeastCostRaptorRouteSelector.java index 363d3bc2e6f..4af1ba1df93 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/LeastCostRaptorRouteSelector.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/LeastCostRaptorRouteSelector.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.List; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/OccupancyData.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/OccupancyData.java index 629f8476bfa..640960e8ad7 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/OccupancyData.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/OccupancyData.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.apache.logging.log4j.LogManager; @@ -5,7 +24,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.IdMap; import org.matsim.api.core.v01.population.Person; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; import org.matsim.core.scoring.functions.ModeUtilityParameters; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.TransitLine; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/OccupancyTracker.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/OccupancyTracker.java index b407efadd07..8051b09d842 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/OccupancyTracker.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/OccupancyTracker.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.routing.pt.raptor.OccupancyData.DepartureData; @@ -226,10 +245,7 @@ public void next() { break; } if (!searchStart) { - this.hasNext = true; - if (this.nextFromStop.getStopFacility().getId().equals(alightingStopId)) { - this.hasNext = false; - } + this.hasNext = !this.nextFromStop.getStopFacility().getId().equals(alightingStopId); break; } this.nextFromStop = this.nextToStop; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorInVehicleCostCalculator.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorInVehicleCostCalculator.java index f23f8e918b8..cc34dcda6d7 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorInVehicleCostCalculator.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorInVehicleCostCalculator.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.matsim.api.core.v01.population.Person; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorIntermodalAccessEgress.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorIntermodalAccessEgress.java index 75142910a90..6630d6225df 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorIntermodalAccessEgress.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorIntermodalAccessEgress.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.matsim.api.core.v01.population.Person; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorParameters.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorParameters.java index aa8ce2abfeb..ba79214ff73 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorParameters.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorParameters.java @@ -1,6 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2017. - */ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; @@ -33,8 +49,8 @@ public class RaptorParameters { private double extensionRadius = 200.0; /** - * Factor with which direct walk generalized cost is multiplied before - * it is compared to the pt generalized cost. + * Factor with which direct walk generalized cost is multiplied before + * it is compared to the pt generalized cost. * Set to a very high value to reduce direct walk results. */ private double directWalkFactor = 1.0; @@ -75,7 +91,7 @@ public double getExtensionRadius() { public void setExtensionRadius(double extensionRadius) { this.extensionRadius = extensionRadius; } - + public double getDirectWalkFactor() { return this.directWalkFactor; } diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorParametersForPerson.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorParametersForPerson.java index cbff35ed095..b280c40e527 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorParametersForPerson.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorParametersForPerson.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.matsim.api.core.v01.population.Person; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorRoute.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorRoute.java index 1c7d3e510f4..ab4c991d99c 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorRoute.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorRoute.java @@ -1,6 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2017. - */ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; @@ -25,7 +41,7 @@ public class RaptorRoute { private double departureTime = Double.NaN; private double travelTime = 0; private int ptLegCount = 0; - private List editableParts = new ArrayList<>(); + private final List editableParts = new ArrayList<>(); final List parts = Collections.unmodifiableList(this.editableParts); RaptorRoute(Facility fromFacility, Facility toFacility, double totalCosts) { diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorRouteSelector.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorRouteSelector.java index 1d5ee7d7543..1ef288c03cc 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorRouteSelector.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorRouteSelector.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.List; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java index 64f9f556028..e80561feea5 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java @@ -1,9 +1,26 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; +import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; + import java.util.HashMap; import java.util.Map; @@ -29,7 +46,8 @@ public enum RaptorOptimization { */ OneToAllRouting } - /** + + /** * The distance in meters that agents can walk to get from one stop to * another stop of a nearby transit line. */ @@ -47,6 +65,8 @@ public enum RaptorOptimization { private RaptorOptimization optimization = RaptorOptimization.OneToOneRouting; + private SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling intermodalLegOnlyHandling = SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.forbid; + public double getBeelineWalkConnectionDistance() { return this.beelineWalkConnectionDistance; } @@ -118,4 +138,12 @@ public RaptorOptimization getOptimization() { public void setOptimization(RaptorOptimization optimization) { this.optimization = optimization; } + + public SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling getIntermodalLegOnlyHandling() { + return intermodalLegOnlyHandling; + } + + public void setIntermodalLegOnlyHandling(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling intermodalLegOnlyHandling) { + this.intermodalLegOnlyHandling = intermodalLegOnlyHandling; + } } diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStopFinder.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStopFinder.java index 78e42955fd8..e2ea7ef7edc 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStopFinder.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStopFinder.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.matsim.api.core.v01.population.Person; @@ -14,7 +33,7 @@ @FunctionalInterface public interface RaptorStopFinder { - public enum Direction { ACCESS, EGRESS } + enum Direction { ACCESS, EGRESS } List findStops(Facility fromFacility, Facility toFacility, Person person, double departureTime, Attributes routingAttributes, RaptorParameters parameters, SwissRailRaptorData data, Direction type); diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorTransferCostCalculator.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorTransferCostCalculator.java index 402a1c83b5a..1a114db0a61 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorTransferCostCalculator.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorTransferCostCalculator.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.function.Supplier; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtils.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtils.java index 199b8be1096..2fae233bf34 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtils.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtils.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.ArrayList; @@ -17,8 +32,8 @@ import org.matsim.api.core.v01.population.Route; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.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.population.PopulationUtils; import org.matsim.core.population.routes.RouteUtils; import org.matsim.pt.router.TransitRouterConfig; @@ -36,18 +51,18 @@ private RaptorUtils() { } public static RaptorStaticConfig createStaticConfig(Config config) { - PlansCalcRouteConfigGroup pcrConfig = config.plansCalcRoute(); + RoutingConfigGroup pcrConfig = config.routing(); SwissRailRaptorConfigGroup srrConfig = ConfigUtils.addOrGetModule(config, SwissRailRaptorConfigGroup.class); RaptorStaticConfig staticConfig = new RaptorStaticConfig(); - staticConfig.setBeelineWalkConnectionDistance(config.transitRouter().getMaxBeelineWalkConnectionDistance()); - - PlansCalcRouteConfigGroup.TeleportedModeParams walk = pcrConfig.getModeRoutingParams().get(TransportMode.walk ); - staticConfig.setBeelineWalkSpeed(walk.getTeleportedModeSpeed() / walk.getBeelineDistanceFactor()); - staticConfig.setBeelineWalkDistanceFactor(walk.getBeelineDistanceFactor()); - staticConfig.setTransferWalkMargin(srrConfig.getTransferWalkMargin()); - staticConfig.setMinimalTransferTime(config.transitRouter().getAdditionalTransferTime()); + staticConfig.setBeelineWalkConnectionDistance(config.transitRouter().getMaxBeelineWalkConnectionDistance()); + RoutingConfigGroup.TeleportedModeParams walk = pcrConfig.getModeRoutingParams().get(TransportMode.walk ); + staticConfig.setBeelineWalkSpeed(walk.getTeleportedModeSpeed() / walk.getBeelineDistanceFactor()); + staticConfig.setBeelineWalkDistanceFactor(walk.getBeelineDistanceFactor()); + staticConfig.setTransferWalkMargin(srrConfig.getTransferWalkMargin()); + staticConfig.setIntermodalLegOnlyHandling(srrConfig.getIntermodalLegOnlyHandling()); + staticConfig.setMinimalTransferTime(config.transitRouter().getAdditionalTransferTime()); staticConfig.setUseModeMappingForPassengers(srrConfig.isUseModeMappingForPassengers()); if (srrConfig.isUseModeMappingForPassengers()) { @@ -73,15 +88,15 @@ public static RaptorParameters createParameters(Config config) { raptorParams.setMarginalUtilityOfWaitingPt_utl_s(trConfig.getMarginalUtilityOfWaitingPt_utl_s()); - PlanCalcScoreConfigGroup pcsConfig = config.planCalcScore(); + ScoringConfigGroup pcsConfig = config.scoring(); double marginalUtilityPerforming = pcsConfig.getPerforming_utils_hr() / 3600.0; - for (Map.Entry e : pcsConfig.getModes().entrySet()) { + for (Map.Entry e : pcsConfig.getModes().entrySet()) { String mode = e.getKey(); - PlanCalcScoreConfigGroup.ModeParams modeParams = e.getValue(); + ScoringConfigGroup.ModeParams modeParams = e.getValue(); double marginalUtility_utl_s = modeParams.getMarginalUtilityOfTraveling()/3600.0 - marginalUtilityPerforming; raptorParams.setMarginalUtilityOfTravelTime_utl_s(mode, marginalUtility_utl_s); } - + double costPerHour = advancedConfig.getTransferPenaltyCostPerTravelTimeHour(); if (costPerHour == 0.0) { // for backwards compatibility, use the default utility of line switch. @@ -104,9 +119,8 @@ public static List convertRouteToLegs(RaptorRoute route, for (RaptorRoute.RoutePart part : route.parts) { if (part.planElements != null) { for (PlanElement pe : part.planElements) { - if (pe instanceof Leg) { - Leg leg = (Leg) pe; - legs.add(leg); + if (pe instanceof Leg leg) { + legs.add(leg); if (leg.getDepartureTime().isUndefined()) { leg.setDepartureTime(lastArrivalTime); } diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptor.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptor.java index d83df73f7c4..2808064eb1f 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptor.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptor.java @@ -1,6 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2017. - */ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; @@ -67,7 +83,7 @@ public List calcRoute(RoutingRequest request) { final double departureTime = request.getDepartureTime(); final Person person = request.getPerson(); final Attributes routingAttributes = request.getAttributes(); - + RaptorParameters parameters = this.parametersForPerson.getRaptorParameters(person); if (parameters.getConfig().isUseRangeQuery()) { return this.performRangeQuery(fromFacility, toFacility, departureTime, person, routingAttributes, parameters); @@ -79,50 +95,32 @@ public List calcRoute(RoutingRequest request) { RaptorRoute directWalk = createDirectWalk(fromFacility, toFacility, departureTime, person, parameters); /* - * The pt trip is compared with a direct walk from trip origin to trip destination. This is useful for backwards - * compatibility, but leads to many trips with only a single "transit_walk" leg which are then considered pt - * trips by the main mode identifier even though they do not contain any pt leg and should rather be considered - * "walk" trips. - * - * That problem can be avoided by setting a very high direct walk factor in TransitRouterConfigGroup. However - * this should be combined with enabling mode choice for pt and walk trips such that slow pt trips can be - * replaced by (faster) walk trips by mode choice. Otherwise agents can be stuck with very slow pt trips. - * - * Comparison is only made between a pt trip and a direct walk trip, other modes (e.g. intermodal access/egress - * modes) are not considered. If they had been considered here, the router would effectively be a mode choice - * module although it is supposed not to change mode choice but rather to simply return a route for a given - * mode. Furthermore there is the problem that the generalized cost calculated by the router can be different - * from the cost the agent will be exposed to in scoring, because the mode performed differently in mobsim than - * anticipated by the router (e.g. the drt travel time turns out to be higher than expected, but the router will - * always chose a direct drt trip over the pt trip, because the router might consistently underestimate drt - * travel time). So it seems a bad idea to compare other modes than walk here. Walk is usually teleported at a - * fixed speed, so it is usually completely deterministic whereas other modes are not. - * - * Overall enabling mode choice and setting a very high direct walk factor (e.g. Double.POSITIVE_INFINITY which - * effectively excludes all direct walks) seems cleaner and better. - * - * vsp-gleich sep'19 (after talking with KN) - * - * * foundRoute.parts.size() == 0 can happen if SwissRasilRaptorCore.createRaptorRoute() finds a trip made up of, * only 2 parts which consists only of an access and an egress leg without any pt leg inbetween. */ - if (foundRoute == null || foundRoute.parts.size() == 0 || hasNoPtLeg(foundRoute.parts)) { + if (directWalk.getTotalCosts() * parameters.getDirectWalkFactor() < foundRoute.getTotalCosts()) { + foundRoute = directWalk; + } + boolean forbidPurelyIntermodalRoutes = data.config.getIntermodalLegOnlyHandling().equals(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.forbid) || data.config.getIntermodalLegOnlyHandling().equals(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.returnNull); + if (foundRoute == null || (foundRoute.parts.size() == 0 && forbidPurelyIntermodalRoutes)) { if (person == null) { log.debug("No route found for person null: trip from x=" + fromFacility.getCoord().getX() + ",y=" + fromFacility.getCoord().getY() + " departure at " + departureTime + " to x=" + toFacility.getCoord().getX() + ",y=" + toFacility.getCoord().getY()); } else { log.debug("No route found for person " + person.getId() + ": trip from x=" + fromFacility.getCoord().getX() + ",y=" + fromFacility.getCoord().getY() + " departure at " + departureTime + " to x=" + toFacility.getCoord().getX() + ",y=" + toFacility.getCoord().getY()); } - return null; - } - if (directWalk.getTotalCosts() * parameters.getDirectWalkFactor() < foundRoute.getTotalCosts()) { - foundRoute = directWalk; + return null; } + else if ((hasNoPtLeg(foundRoute.parts))){ + if (forbidPurelyIntermodalRoutes){ + return null; + } + } + List legs = RaptorUtils.convertRouteToLegs(foundRoute, this.data.config.getTransferWalkMargin()); return legs; } - + private boolean hasNoPtLeg(List parts) { for (RoutePart part : parts) { // if the route part has a TransitLine, it must be a real pt leg @@ -142,10 +140,9 @@ private List performRangeQuery(Facility fromFacility, Fac double earliestDepartureTime = desiredDepartureTime - rangeSettings.getMaxEarlierDeparture(); double latestDepartureTime = desiredDepartureTime + rangeSettings.getMaxLaterDeparture(); - if (this.defaultRouteSelector instanceof ConfigurableRaptorRouteSelector) { - ConfigurableRaptorRouteSelector selector = (ConfigurableRaptorRouteSelector) this.defaultRouteSelector; + if (this.defaultRouteSelector instanceof ConfigurableRaptorRouteSelector selector) { - SwissRailRaptorConfigGroup.RouteSelectorParameterSet params = srrConfig.getRouteSelector(subpopulation); + SwissRailRaptorConfigGroup.RouteSelectorParameterSet params = srrConfig.getRouteSelector(subpopulation); selector.setBetaTransfer(params.getBetaTransfers()); selector.setBetaTravelTime(params.getBetaTravelTime()); @@ -174,7 +171,7 @@ public List calcRoute(Facility fromFacility, Facility toF } else { log.debug("No route found for person " + person.getId() + ": trip from x=" + fromFacility.getCoord().getX() + ",y=" + fromFacility.getCoord().getY() + " departure at " + desiredDepartureTime + " to x=" + toFacility.getCoord().getX() + ",y=" + toFacility.getCoord().getY()); } - return null; + return null; } if (directWalk.getTotalCosts() * parameters.getDirectWalkFactor() < foundRoute.getTotalCosts()) { foundRoute = directWalk; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java index adca5d074ed..c0cfeb893bc 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java @@ -1,9 +1,25 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; +import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; import ch.sbb.matsim.routing.pt.raptor.OccupancyData.DepartureData; import ch.sbb.matsim.routing.pt.raptor.RaptorInVehicleCostCalculator.RouteSegmentIterator; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorData.CachingTransferProvider; @@ -694,7 +710,7 @@ private int findNextDepartureIndex(RRoute route, RRouteStop routeStop, int time) if (this.useCapacityConstraints) { return findNextDepartureIndexWithConstraints(route, routeStop, time); } - int depTimeAtRouteStart = (int) (time - routeStop.departureOffset); + int depTimeAtRouteStart = time - routeStop.departureOffset; int fromIndex = route.indexFirstDeparture; int toIndex = fromIndex + route.countDepartures; int pos = Arrays.binarySearch(this.data.departures, fromIndex, toIndex, depTimeAtRouteStart); @@ -771,23 +787,45 @@ private void handleTransfers(boolean strict, RaptorParameters raptorParams) { private PathElement findLeastCostArrival(Map destinationStops) { double leastCost = Double.POSITIVE_INFINITY; + double leastCostFeederOnly = Double.POSITIVE_INFINITY; PathElement leastCostPath = null; + PathElement leastCostPathFeederOnly = null; - for (Map.Entry e : destinationStops.entrySet()) { + SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling intermodalLegOnlyHandling = data.config.getIntermodalLegOnlyHandling(); + boolean checkBothPtAndPurelyIntermodalRoutes = intermodalLegOnlyHandling.equals(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.avoid) || intermodalLegOnlyHandling.equals(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.forbid); + for (Map.Entry e : destinationStops.entrySet()) { TransitStopFacility stop = e.getKey(); int stopIndex = this.data.stopFacilityIndices.get(stop); PathElement pe = this.arrivalPathPerStop[stopIndex]; - if (pe != null) { - InitialStop egressStop = e.getValue(); - int arrivalTime = (int) (pe.arrivalTime + egressStop.accessTime); - double arrivalTravelCost = pe.arrivalTravelCost + egressStop.accessCost; - double totalCost = arrivalTravelCost + pe.arrivalTransferCost; - if ((totalCost < leastCost) || (totalCost == leastCost && pe.transferCount < leastCostPath.transferCount)) { - leastCost = totalCost; - leastCostPath = new PathElement(pe, null, pe.firstDepartureTime, TIME_UNDEFINED, arrivalTime, arrivalTravelCost, pe.arrivalTransferCost, egressStop.distance, pe.transferCount, true, null, egressStop); // this is the egress leg - } - } + if (pe!=null) { + InitialStop egressStop = e.getValue(); + int arrivalTime = (int) (pe.arrivalTime + egressStop.accessTime); + double arrivalTravelCost = pe.arrivalTravelCost + egressStop.accessCost; + double totalCost = arrivalTravelCost + pe.arrivalTransferCost; + if ((totalCost < leastCost) || (totalCost == leastCost && pe.transferCount < leastCostPath.transferCount)) { + PathElement egressLegCandidate = new PathElement(pe, null, pe.firstDepartureTime, TIME_UNDEFINED, arrivalTime, arrivalTravelCost, pe.arrivalTransferCost, egressStop.distance, pe.transferCount, true, null, egressStop); + + if (pe.comingFrom == null && checkBothPtAndPurelyIntermodalRoutes) { + if (totalCost < leastCostFeederOnly) { + leastCostFeederOnly = totalCost; + leastCostPathFeederOnly = egressLegCandidate; + } + } else { + // this is the egress leg + leastCostPath = egressLegCandidate; + leastCost = totalCost; + } + } + + } + } + + if (checkBothPtAndPurelyIntermodalRoutes){ + if (Double.isInfinite(leastCost)){ + return leastCostPathFeederOnly; + } + } return leastCostPath; } @@ -803,18 +841,6 @@ private static RaptorRoute createRaptorRoute(Facility fromFacility, Facility toF } pes.addFirst(pe); } - if (pes.size() == 2 && pes.get(0).isTransfer && pes.get(1).isTransfer) { - // it's only access and egress, no real pt trip - arrivalCost = Double.POSITIVE_INFINITY; - pes.clear(); - } - - // yyyyyy I am having the following situation: - // * assume there is only one drt link. This happens when the pt trip is outside the service area, and then both the starting and the ending - // location are mapped to the same link. - // * In consequence, the trip becomes "access_walk_to_drt"---"egress_walk_to_drt" (*). However, the cost of that is set to infty here ... with the - // consequence that the raptor returns a "pure transit walk" later. - // I thought that you said that it would directly return (*). It would (I think) also be easier to debug. kai, jun'19 RaptorRoute raptorRoute = new RaptorRoute(fromFacility, toFacility, arrivalCost); double time = departureTime; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java index 1fdb7882f15..5abe7fb49e0 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java @@ -1,6 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2017. - */ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; @@ -329,9 +345,7 @@ private static boolean isUsefulTransfer(RRouteStop fromRouteStop, RRouteStop toR // e.g. when starting at a single stop, users would expect that the stop facility // in the opposite direction could be reached within a minute or so by walk. But the algorithm // would find this if the transfers are missing. - if (couldHaveTransferredOneStopEarlierInOppositeDirection(fromRouteStop, toRouteStop, maxBeelineWalkConnectionDistance)) { - return false; - } + return !couldHaveTransferredOneStopEarlierInOppositeDirection(fromRouteStop, toRouteStop, maxBeelineWalkConnectionDistance); } // if we failed all other checks, it looks like this transfer is useful return true; @@ -542,18 +556,18 @@ public static final class RTransfer { this.transferDistance = (int) Math.ceil(transferDistance); } } - + /* - * synchronized in order to avoid that multiple quad trees for the very same stop filter attribute/value combination are prepared at the same time + * synchronized in order to avoid that multiple quad trees for the very same stop filter attribute/value combination are prepared at the same time */ public synchronized void prepareStopFilterQuadTreeIfNotExistent(String stopFilterAttribute, String stopFilterValue) { // if stopFilterAttribute/stopFilterValue combination exists // we do not have to do anything - Map> filteredQTs = + Map> filteredQTs = this.stopFilterAttribute2Value2StopsQT.computeIfAbsent(stopFilterAttribute, key -> new HashMap<>()); if (filteredQTs.containsKey(stopFilterValue)) return; - + Set stops = routeStopsPerStopFacility.keySet(); QuadTree stopsQTFiltered = new QuadTree<>(stopsQT.getMinEasting(), stopsQT.getMinNorthing(), stopsQT.getMaxEasting(), stopsQT.getMaxNorthing()); for (TransitStopFacility stopFacility : stops) { @@ -571,7 +585,7 @@ public synchronized void prepareStopFilterQuadTreeIfNotExistent(String stopFilte public class CachingTransferProvider implements Supplier { private RTransfer raptorTransfer = null; - private Transfer transfer = new Transfer(); + private final Transfer transfer = new Transfer(); public CachingTransferProvider() { } diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorFactory.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorFactory.java index ba79d4ff291..51c740ebb98 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorFactory.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorFactory.java @@ -1,6 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2017. - */ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorModule.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorModule.java index 350caf37441..9389dc5469a 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorModule.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorModule.java @@ -1,6 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2017. - */ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; @@ -29,7 +45,7 @@ public void install() { for (String mode : getConfig().transit().getTransitModes()) { addRoutingModuleBinding(mode).toProvider(SwissRailRaptorRoutingModuleProvider.class); } - + SwissRailRaptorConfigGroup srrConfig = ConfigUtils.addOrGetModule(getConfig(), SwissRailRaptorConfigGroup.class); if (srrConfig.isUseRangeQuery()) { @@ -37,7 +53,7 @@ public void install() { } else { bind(RaptorRouteSelector.class).to(LeastCostRaptorRouteSelector.class); // just a simple default in case it ever gets used. } - + switch (srrConfig.getScoringParameters()) { case Default: bind(RaptorParametersForPerson.class).to(DefaultRaptorParametersForPerson.class); @@ -54,7 +70,7 @@ public void install() { if (useCapacityConstraints) { addEventHandlerBinding().to(OccupancyTracker.class); } - + bind(RaptorIntermodalAccessEgress.class).to(DefaultRaptorIntermodalAccessEgress.class); bind(RaptorInVehicleCostCalculator.class).to(DefaultRaptorInVehicleCostCalculator.class); bind(RaptorTransferCostCalculator.class).to(DefaultRaptorTransferCostCalculator.class); diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModule.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModule.java index e9cf7f4961c..94c346b120b 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModule.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModule.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.ArrayList; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModuleProvider.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModuleProvider.java index 5a9b5b45be9..c6c23184169 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModuleProvider.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModuleProvider.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import com.google.inject.name.Named; @@ -31,7 +46,8 @@ public class SwissRailRaptorRoutingModuleProvider implements Provider currentMeasuredOperations; private Map> currentIterationChildren; - private Map>> children; - + private final Map>> children; + /** Creates a new IterationStopWatch. */ public IterationStopWatch() { - this.iterations = new LinkedHashMap>(); - this.identifiers = new LinkedList(); - this.operations = new LinkedList(); + this.iterations = new LinkedHashMap<>(); + this.identifiers = new LinkedList<>(); + this.operations = new LinkedList<>(); this.currentIterationValues = null; - this.children = new LinkedHashMap>>(); + this.children = new LinkedHashMap<>(); } /** @@ -109,18 +109,16 @@ public void reset() { * Sets the current iteration, so that the times measured using {@link #beginOperation(String)}, * {@link #endOperation(String)} and {@link #timestamp(String)} are assigned to the correct iteration for * the analysis. - * - * @param iteration */ public void beginIteration(final int iteration) { - this.iteration = Integer.valueOf(iteration); + this.iteration = iteration; if (this.iterations.get(this.iteration) == null) { - this.currentIterationValues = new HashMap(); + this.currentIterationValues = new HashMap<>(); this.iterations.put(this.iteration, this.currentIterationValues); this.nextIdentifierPosition = 0; this.nextOperationPosition = 0; - this.currentMeasuredOperations = new Stack(); - this.currentIterationChildren = new HashMap>(); + this.currentMeasuredOperations = new Stack<>(); + this.currentIterationChildren = new HashMap<>(); this.children.put(this.iteration, this.currentIterationChildren); } this.beginOperation(OPERATION_ITERATION); @@ -139,16 +137,16 @@ public void beginOperation(final String identifier) { String ident = "BEGIN " + identifier; ensureIdentifier(ident); - this.currentIterationValues.put(ident, Long.valueOf(System.currentTimeMillis())); - - this.currentIterationChildren.put(identifier, new ArrayList()); + this.currentIterationValues.put(ident, System.currentTimeMillis()); + + this.currentIterationChildren.put(identifier, new ArrayList<>()); // check whether this operation has a parent operation - if (this.currentMeasuredOperations.size() > 0) { + if (!this.currentMeasuredOperations.isEmpty()) { String parent = this.currentMeasuredOperations.peek(); this.currentIterationChildren.get(parent).add(identifier); } - + // add ident to stack this.currentMeasuredOperations.push(identifier); } @@ -163,9 +161,9 @@ public void endOperation(final String identifier) { String ident = "END " + identifier; ensureIdentifier(ident); ensureOperation(identifier); - this.currentIterationValues.put(ident, Long.valueOf(System.currentTimeMillis())); - - + this.currentIterationValues.put(ident, System.currentTimeMillis()); + + this.currentMeasuredOperations.pop(); } @@ -180,31 +178,30 @@ public void endIteration() { */ public void timestamp(final String identifier) { ensureIdentifier(identifier); - this.currentIterationValues.put(identifier, Long.valueOf(System.currentTimeMillis())); + this.currentIterationValues.put(identifier, System.currentTimeMillis()); } /** - * Writes the gathered data tab-separated into a text file. + * Writes the gathered data into a file. * * @param filename The name of a file where to write the gathered data. + * @param delimiter The delimiter to be used as field separator. */ - public void writeTextFile(final String filename) { - - try { - BufferedWriter writer = IOUtils.getBufferedWriter(filename + ".txt"); + public void writeSeparatedFile(final String filename, final String delimiter) { + try (BufferedWriter writer = IOUtils.getBufferedWriter(filename)) { // print header - writer.write("Iteration"); + writer.write("iteration"); for (String identifier : this.identifiers) { - writer.write('\t'); + writer.write(delimiter); writer.write(identifier); } - writer.write('\t'); + writer.write(delimiter); for (String identifier : this.operations) { - writer.write('\t'); + writer.write(delimiter); writer.write(identifier); } - writer.write("\n"); + writer.write('\n'); // print data for (Map.Entry> entry : this.iterations.entrySet()) { @@ -215,18 +212,18 @@ public void writeTextFile(final String filename) { // identifiers for (String identifier : this.identifiers) { Long time = data.get(identifier); - writer.write('\t'); + writer.write(delimiter); writer.write(formatMilliTime(time)); } // blank separator - writer.write('\t'); + writer.write(delimiter); // durations of operations for (String identifier: this.operations) { Long startTime = data.get("BEGIN " + identifier); Long endTime = data.get("END " + identifier); - writer.write('\t'); + writer.write(delimiter); if (startTime != null && endTime != null) { - double diff = (endTime.longValue() - startTime.longValue()) / 1000.0; + double diff = (endTime - startTime) / 1000.0; writer.write(Time.writeTime(diff)); } } @@ -235,7 +232,6 @@ public void writeTextFile(final String filename) { writer.write("\n"); } writer.flush(); - writer.close(); } catch (IOException e) { throw new RuntimeException(e); } @@ -249,13 +245,13 @@ public void writeTextFile(final String filename) { public void writeGraphFile(String filename) { int iterations = this.iterations.entrySet().size(); - Map arrayMap = new HashMap(); + Map arrayMap = new HashMap<>(); for (String identifier : this.operations) arrayMap.put(identifier, new double[iterations]); int iter = 0; for(Entry> entry : this.iterations.entrySet()) { Map data = entry.getValue(); - + // children map of current iteration Map> childrenMap = this.children.get(entry.getKey()); @@ -264,18 +260,18 @@ public void writeGraphFile(String filename) { Long startTime = data.get("BEGIN " + identifier); Long endTime = data.get("END " + identifier); if (startTime != null && endTime != null) { - double diff = (endTime.longValue() - startTime.longValue()); + double diff = (endTime - startTime); /* * If the operation has children, subtract their durations since they are - * also included in the plot. Otherwise their duration would be counted twice. + * also included in the plot. Otherwise, their duration would be counted twice. */ for (String child : childrenMap.get(identifier)) { Long childStartTime = data.get("BEGIN " + child); Long childEndTime = data.get("END " + child); - diff -= (childEndTime.longValue() - childStartTime.longValue()); + diff -= (childEndTime - childStartTime); } - + arrayMap.get(identifier)[iter] = diff / 1000.0; } else arrayMap.get(identifier)[iter] = 0.0; } @@ -304,17 +300,12 @@ public void writeGraphFile(String filename) { chart.getChart().getCategoryPlot().getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_90); double[] iterationData = null; -// double[] sumData = new double[iterations]; for (String operation : this.operations) { double[] data = arrayMap.get(operation); if (operation.equals(OPERATION_ITERATION)) { iterationData = data; - continue; } else { chart.addSeries(operation, data); -// for (int i = 0; i < iterations; i++) { -// sumData[i] += data[i]; -// } } } if (iterationData != null) { @@ -330,8 +321,6 @@ public void writeGraphFile(String filename) { * Make sure the given identifier exists in our collection. If it is missing, insert it at the correct * place. "Correct" means that it tries to insert this identifier right after the last-requested identifier. * This should help to write the gathered data out in a natural way. - * - * @param identifier */ private void ensureIdentifier(final String identifier) { int pos = this.identifiers.indexOf(identifier); @@ -345,8 +334,6 @@ private void ensureIdentifier(final String identifier) { /** * Does the same as {@link #ensureIdentifier(String)}, but for operation-identifiers. - * - * @param identifier */ private void ensureOperation(final String identifier) { int pos = this.operations.indexOf(identifier); @@ -359,7 +346,7 @@ private void ensureOperation(final String identifier) { } /** - * Formats the time given in milliseconds (e.g. returned by {@link java.lang.System#currentTimeMillis()} + * Formats the time given in milliseconds (e.g. returned by {@link java.lang.System#currentTimeMillis()}) * nicely for output. * * @param millis A time value in milliseconds @@ -369,7 +356,7 @@ private String formatMilliTime(final Long millis) { if (millis == null) { return ""; } - return this.formatter.format(new Date(millis.longValue())); + return this.formatter.format(new Date(millis)); } } diff --git a/matsim/src/main/java/org/matsim/analysis/IterationTravelStatsControlerListener.java b/matsim/src/main/java/org/matsim/analysis/IterationTravelStatsControlerListener.java index 4f2b25530d0..17ea8796459 100644 --- a/matsim/src/main/java/org/matsim/analysis/IterationTravelStatsControlerListener.java +++ b/matsim/src/main/java/org/matsim/analysis/IterationTravelStatsControlerListener.java @@ -90,8 +90,8 @@ public void notifyIterationEnds(IterationEndsEvent event) { pkMbyModeCalculator.addIteration(event.getIteration(), experiencedPlansService.getExperiencedPlans()); pHbyModeCalculator.writeOutput(); pkMbyModeCalculator.writeOutput(); - final boolean writingTripsAtAll = config.controler().getWriteTripsInterval() > 0; - final boolean regularWriteEvents = writingTripsAtAll && ((event.getIteration() > 0 && event.getIteration() % config.controler().getWriteTripsInterval() == 0) || event.isLastIteration()); + final boolean writingTripsAtAll = config.controller().getWriteTripsInterval() > 0; + final boolean regularWriteEvents = writingTripsAtAll && ((event.getIteration() > 0 && event.getIteration() % config.controller().getWriteTripsInterval() == 0) || event.isLastIteration()); if (regularWriteEvents || (writingTripsAtAll && event.getIteration() == 0)) { new TripsAndLegsCSVWriter(scenario, customTripsWriterExtension, customLegsWriterExtension, mainModeIdentifier, customTimeWriter).write(experiencedPlansService.getExperiencedPlans() , outputDirectoryHierarchy.getIterationFilename(event.getIteration(), Controler.DefaultFiles.tripscsv) @@ -106,7 +106,7 @@ public void notifyIterationEnds(IterationEndsEvent event) { public void notifyShutdown(ShutdownEvent event) { travelDistanceStats.close(); - if (config.controler().getWriteTripsInterval() > 0) { + if (config.controller().getWriteTripsInterval() > 0) { writePersonsCSV(); } } diff --git a/matsim/src/main/java/org/matsim/analysis/LegHistogram.java b/matsim/src/main/java/org/matsim/analysis/LegHistogram.java index 32b8f28b94e..aa912700fdb 100644 --- a/matsim/src/main/java/org/matsim/analysis/LegHistogram.java +++ b/matsim/src/main/java/org/matsim/analysis/LegHistogram.java @@ -32,7 +32,6 @@ import org.matsim.core.api.experimental.events.EventsManager; 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 jakarta.inject.Inject; @@ -40,6 +39,7 @@ import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; +import java.io.UncheckedIOException; import java.util.Map; import java.util.Set; import java.util.TreeMap; diff --git a/matsim/src/main/java/org/matsim/analysis/LegHistogramChart.java b/matsim/src/main/java/org/matsim/analysis/LegHistogramChart.java index 31d5a86c9c7..551f29e4cd2 100644 --- a/matsim/src/main/java/org/matsim/analysis/LegHistogramChart.java +++ b/matsim/src/main/java/org/matsim/analysis/LegHistogramChart.java @@ -31,11 +31,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; public class LegHistogramChart { static JFreeChart getGraphic(final LegHistogram.DataFrame dataFrame, final String mode, int iteration) { diff --git a/matsim/src/main/java/org/matsim/analysis/LegHistogramListener.java b/matsim/src/main/java/org/matsim/analysis/LegHistogramListener.java index 4ea53bb2da6..e5c1a9b8e2d 100644 --- a/matsim/src/main/java/org/matsim/analysis/LegHistogramListener.java +++ b/matsim/src/main/java/org/matsim/analysis/LegHistogramListener.java @@ -22,8 +22,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.controler.events.IterationStartsEvent; @@ -42,7 +41,7 @@ final class LegHistogramListener implements IterationEndsListener, IterationStartsListener { @Inject private LegHistogram histogram; - @Inject private ControlerConfigGroup controlerConfigGroup; + @Inject private ControllerConfigGroup controllerConfigGroup; @Inject private OutputDirectoryHierarchy controlerIO; static private final Logger log = LogManager.getLogger(LegHistogramListener.class); @@ -56,7 +55,7 @@ public void notifyIterationStarts(final IterationStartsEvent event) { public void notifyIterationEnds(final IterationEndsEvent event) { this.histogram.write(controlerIO.getIterationFilename(event.getIteration(), "legHistogram.txt")); this.printStats(); - if (controlerConfigGroup.isCreateGraphs()) { + if (controllerConfigGroup.isCreateGraphs()) { LegHistogramChart.writeGraphic(this.histogram, controlerIO.getIterationFilename(event.getIteration(), "legHistogram_all.png")); for (String legMode : this.histogram.getLegModes()) { LegHistogramChart.writeGraphic(this.histogram, controlerIO.getIterationFilename(event.getIteration(), "legHistogram_" + legMode + ".png"), legMode); diff --git a/matsim/src/main/java/org/matsim/analysis/LinkStatsControlerListener.java b/matsim/src/main/java/org/matsim/analysis/LinkStatsControlerListener.java index b968af1d8bf..771b2dc2b95 100644 --- a/matsim/src/main/java/org/matsim/analysis/LinkStatsControlerListener.java +++ b/matsim/src/main/java/org/matsim/analysis/LinkStatsControlerListener.java @@ -25,7 +25,7 @@ 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.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.LinkStatsConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -37,10 +37,10 @@ import org.matsim.core.controler.listener.ShutdownListener; import org.matsim.core.router.util.TravelTime; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import jakarta.inject.Inject; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.*; /** @@ -51,7 +51,7 @@ final class LinkStatsControlerListener implements IterationEndsListener, Iterati @Inject private LinkStatsConfigGroup linkStatsConfigGroup; @Inject - private ControlerConfigGroup controlerConfigGroup; + private ControllerConfigGroup controllerConfigGroup; @Inject private CalcLinkStats linkStats; @Inject @@ -71,7 +71,7 @@ final class LinkStatsControlerListener implements IterationEndsListener, Iterati public void notifyIterationEnds(IterationEndsEvent event) { int iteration = event.getIteration(); - if (useVolumesOfIteration(iteration, controlerConfigGroup.getFirstIteration())) { + if (useVolumesOfIteration(iteration, controllerConfigGroup.getFirstIteration())) { this.iterationsUsed++; linkStats.addData(volumes, travelTime.get(TransportMode.car)); } diff --git a/matsim/src/main/java/org/matsim/analysis/ModeChoiceCoverageControlerListener.java b/matsim/src/main/java/org/matsim/analysis/ModeChoiceCoverageControlerListener.java index 1e79eb68ae1..ce1bd875272 100644 --- a/matsim/src/main/java/org/matsim/analysis/ModeChoiceCoverageControlerListener.java +++ b/matsim/src/main/java/org/matsim/analysis/ModeChoiceCoverageControlerListener.java @@ -6,8 +6,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.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.controler.events.ShutdownEvent; @@ -45,7 +45,7 @@ public class ModeChoiceCoverageControlerListener implements StartupListener, Ite private final Population population; private final String modeFileName; private final boolean createPNG; - private final ControlerConfigGroup controlerConfigGroup; + private final ControllerConfigGroup controllerConfigGroup; private final MainModeIdentifier mainModeIdentifier; private int minIteration = 0; @@ -64,10 +64,10 @@ public class ModeChoiceCoverageControlerListener implements StartupListener, Ite @Inject - ModeChoiceCoverageControlerListener(ControlerConfigGroup controlerConfigGroup, Population population1, OutputDirectoryHierarchy controlerIO, - PlanCalcScoreConfigGroup scoreConfig, AnalysisMainModeIdentifier mainModeIdentifier) { + ModeChoiceCoverageControlerListener(ControllerConfigGroup controllerConfigGroup, Population population1, OutputDirectoryHierarchy controlerIO, + ScoringConfigGroup scoreConfig, AnalysisMainModeIdentifier mainModeIdentifier) { - this.controlerConfigGroup = controlerConfigGroup; + this.controllerConfigGroup = controllerConfigGroup; this.population = population1; this.modeFileName = controlerIO.getOutputFilename(FILENAME_MODESTATS); // this.createPNG = controlerConfigGroup.isCreateGraphs(); @@ -81,7 +81,7 @@ public class ModeChoiceCoverageControlerListener implements StartupListener, Ite @Override public void notifyStartup(final StartupEvent event) { - this.minIteration = controlerConfigGroup.getFirstIteration(); + this.minIteration = controllerConfigGroup.getFirstIteration(); } @Override diff --git a/matsim/src/main/java/org/matsim/analysis/ModeStatsControlerListener.java b/matsim/src/main/java/org/matsim/analysis/ModeStatsControlerListener.java index df37ea197fd..c9f4ff89ce0 100644 --- a/matsim/src/main/java/org/matsim/analysis/ModeStatsControlerListener.java +++ b/matsim/src/main/java/org/matsim/analysis/ModeStatsControlerListener.java @@ -24,6 +24,7 @@ import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.*; import java.util.List; import java.util.Map.Entry; @@ -32,26 +33,19 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtils; import org.jfree.chart.JFreeChart; -import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; -import org.jfree.chart.renderer.xy.XYBarPainter; -import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.XYDataset; -import org.jfree.data.xy.XYSeries; 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.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.events.IterationEndsEvent; -import org.matsim.core.controler.events.ShutdownEvent; import org.matsim.core.controler.events.StartupEvent; import org.matsim.core.controler.listener.IterationEndsListener; -import org.matsim.core.controler.listener.ShutdownListener; import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.router.AnalysisMainModeIdentifier; import org.matsim.core.router.MainModeIdentifier; @@ -60,7 +54,6 @@ import org.matsim.core.utils.charts.StackedBarChart; import org.matsim.core.utils.charts.XYLineChart; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; /** @@ -73,19 +66,20 @@ */ public final class ModeStatsControlerListener implements StartupListener, IterationEndsListener { - public static final String FILENAME_MODESTATS = "modestats"; + private final static String FILENAME_MODESTATS = "modestats"; - final private Population population; + private final Population population; - final private String modeFileName ; + private final String modeFileName; + private final String delimiter; private final boolean createPNG; - private final ControlerConfigGroup controlerConfigGroup; + private final ControllerConfigGroup controllerConfigGroup; - Map> modeHistories = new HashMap<>() ; + Map> modeHistories = new HashMap<>(); private int minIteration = 0; private MainModeIdentifier mainModeIdentifier; - private Map modeCnt = new TreeMap<>() ; + private Map modeCnt = new TreeMap<>(); private int firstIteration = -1; // Keep all modes encountered so far in a sorted set to ensure output is written for modes sorted by mode. @@ -94,18 +88,19 @@ public final class ModeStatsControlerListener implements StartupListener, Iterat private final static Logger log = LogManager.getLogger(ModeStatsControlerListener.class); @Inject - ModeStatsControlerListener(ControlerConfigGroup controlerConfigGroup, Population population1, OutputDirectoryHierarchy controlerIO, - PlanCalcScoreConfigGroup scoreConfig, AnalysisMainModeIdentifier mainModeIdentifier) { - this.controlerConfigGroup = controlerConfigGroup; + ModeStatsControlerListener(ControllerConfigGroup controllerConfigGroup, Population population1, OutputDirectoryHierarchy controlerIO, + GlobalConfigGroup globalConfigGroup, AnalysisMainModeIdentifier mainModeIdentifier) { + this.controllerConfigGroup = controllerConfigGroup; this.population = population1; - this.modeFileName = controlerIO.getOutputFilename( FILENAME_MODESTATS ) ; - this.createPNG = controlerConfigGroup.isCreateGraphs(); + this.modeFileName = controlerIO.getOutputFilename(FILENAME_MODESTATS); + this.delimiter = globalConfigGroup.getDefaultDelimiter(); + this.createPNG = controllerConfigGroup.isCreateGraphs(); this.mainModeIdentifier = mainModeIdentifier; } @Override public void notifyStartup(final StartupEvent event) { - this.minIteration = controlerConfigGroup.getFirstIteration(); + this.minIteration = this.controllerConfigGroup.getFirstIteration(); } @Override @@ -118,18 +113,18 @@ private void collectModeShareInfo(final IterationEndsEvent event) { firstIteration = event.getIteration(); } for (Person person : this.population.getPersons().values()) { - Plan plan = person.getSelectedPlan() ; - List trips = TripStructureUtils.getTrips(plan) ; + Plan plan = person.getSelectedPlan(); + List trips = TripStructureUtils.getTrips(plan); for ( Trip trip : trips ) { - String mode = this.mainModeIdentifier.identifyMainMode( trip.getTripElements() ) ; + String mode = this.mainModeIdentifier.identifyMainMode(trip.getTripElements()); // yy as stated elsewhere, the "computer science" mode identification may not be the same as the "transport planning" // mode identification. Maybe revise. kai, nov'16 Double cnt = this.modeCnt.get( mode ); - if ( cnt==null ) { - cnt = 0. ; + if (cnt == null) { + cnt = 0.; } - this.modeCnt.put( mode, cnt + 1 ) ; + this.modeCnt.put( mode, cnt + 1 ); } } @@ -162,22 +157,21 @@ private void collectModeShareInfo(final IterationEndsEvent event) { modeHistory.put( event.getIteration(), share ) ; } - BufferedWriter modeOut = IOUtils.getBufferedWriter(this.modeFileName + ".txt"); - try { - modeOut.write("Iteration"); + try (BufferedWriter modeOut = IOUtils.getBufferedWriter(this.modeFileName + ".csv")) { + modeOut.write("iteration"); for ( String mode : modes ) { - modeOut.write("\t" + mode); + modeOut.write(this.delimiter); + modeOut.write(mode); } modeOut.write("\n"); for (int iter = firstIteration; iter <= event.getIteration(); iter++) { modeOut.write( String.valueOf(iter) ) ; for ( String mode : modes ) { - modeOut.write( "\t" + modeHistories.get(mode).get(iter)) ; + modeOut.write(this.delimiter + modeHistories.get(mode).get(iter)); } modeOut.write( "\n" ) ; } modeOut.flush(); - modeOut.close(); } catch (IOException e) { e.printStackTrace(); throw new UncheckedIOException(e); diff --git a/matsim/src/main/java/org/matsim/analysis/PHbyModeCalculator.java b/matsim/src/main/java/org/matsim/analysis/PHbyModeCalculator.java index 6c9f11f0d8f..b4663b50388 100644 --- a/matsim/src/main/java/org/matsim/analysis/PHbyModeCalculator.java +++ b/matsim/src/main/java/org/matsim/analysis/PHbyModeCalculator.java @@ -32,14 +32,14 @@ import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.jfree.chart.axis.CategoryLabelPositions; import org.matsim.api.core.v01.IdMap; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.router.StageActivityTypeIdentifier; import org.matsim.core.scoring.EventsToLegs; @@ -53,8 +53,8 @@ public class PHbyModeCalculator { private final Map> phtPerIteration = new TreeMap<>(); private final boolean writePng; - private final OutputDirectoryHierarchy controlerIO; - private final static char DEL = '\t'; + private final OutputDirectoryHierarchy controllerIO; + private final String delimiter; private final static String FILENAME = "ph_modestats"; private static final String TRAVEL_TIME_SUFFIX = "_travel"; @@ -62,9 +62,10 @@ public class PHbyModeCalculator { private static final String STAGE_ACTIVITY = "stageActivity"; @Inject - PHbyModeCalculator(ControlerConfigGroup controlerConfigGroup, OutputDirectoryHierarchy controlerIO) { - writePng = controlerConfigGroup.isCreateGraphs(); - this.controlerIO = controlerIO; + PHbyModeCalculator(ControllerConfigGroup controllerConfigGroup, OutputDirectoryHierarchy controllerIO, GlobalConfigGroup globalConfig) { + this.writePng = controllerConfigGroup.isCreateGraphs(); + this.controllerIO = controllerIO; + this.delimiter = globalConfig.getDefaultDelimiter(); } void addIteration(int iteration, IdMap map) { @@ -123,7 +124,7 @@ private void writePHTText() { .flatMap(i->i.keySet().stream()) .collect(Collectors.toSet())); - try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(Paths.get(controlerIO.getOutputFilename( FILENAME+ ".txt"))), CSVFormat.DEFAULT.withDelimiter(DEL))) { + try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(Paths.get(controllerIO.getOutputFilename( FILENAME+ ".csv"))), CSVFormat.DEFAULT.withDelimiter(this.delimiter.charAt(0)))) { csvPrinter.print("Iteration"); for (String mode: allModes) { csvPrinter.print(mode + TRAVEL_TIME_SUFFIX); @@ -167,7 +168,7 @@ private void writePHTText() { chart.addSeries(mode + WAIT_TIME_SUFFIX, valueWaitTime); } chart.addMatsimLogo(); - chart.saveAsPng(controlerIO.getOutputFilename(FILENAME+ ".png"), 1024, 768); + chart.saveAsPng(controllerIO.getOutputFilename(FILENAME+ ".png"), 1024, 768); } diff --git a/matsim/src/main/java/org/matsim/analysis/PKMbyModeCalculator.java b/matsim/src/main/java/org/matsim/analysis/PKMbyModeCalculator.java index 831bf1a2c4e..1b05fccdb2f 100644 --- a/matsim/src/main/java/org/matsim/analysis/PKMbyModeCalculator.java +++ b/matsim/src/main/java/org/matsim/analysis/PKMbyModeCalculator.java @@ -32,13 +32,13 @@ import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.jfree.chart.axis.CategoryLabelPositions; import org.matsim.api.core.v01.IdMap; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.utils.charts.StackedBarChart; @@ -50,15 +50,15 @@ public class PKMbyModeCalculator { private final Map> pmtPerIteration = new TreeMap<>(); private final boolean writePng; - private final OutputDirectoryHierarchy controlerIO; - private final static char DEL = '\t'; + private final OutputDirectoryHierarchy controllerIO; + private final String delimiter; private final static String FILENAME = "pkm_modestats"; - @Inject - PKMbyModeCalculator(ControlerConfigGroup controlerConfigGroup, OutputDirectoryHierarchy controlerIO) { - writePng = controlerConfigGroup.isCreateGraphs(); - this.controlerIO = controlerIO; + PKMbyModeCalculator(ControllerConfigGroup controllerConfigGroup, OutputDirectoryHierarchy controllerIO, GlobalConfigGroup globalConfig) { + writePng = controllerConfigGroup.isCreateGraphs(); + this.controllerIO = controllerIO; + this.delimiter = globalConfig.getDefaultDelimiter(); } void addIteration(int iteration, IdMap map) { @@ -89,7 +89,7 @@ private void writeVKTText() { .flatMap(i->i.keySet().stream()) .collect(Collectors.toSet())); - try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(Paths.get(controlerIO.getOutputFilename( FILENAME+ ".txt"))), CSVFormat.DEFAULT.withDelimiter(DEL))) { + try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(Paths.get(controllerIO.getOutputFilename( FILENAME+ ".csv"))), CSVFormat.DEFAULT.withDelimiter(this.delimiter.charAt(0)))) { csvPrinter.print("Iteration"); csvPrinter.printRecord(allModes); @@ -123,7 +123,7 @@ private void writeVKTText() { chart.addSeries(mode, value); } chart.addMatsimLogo(); - chart.saveAsPng(controlerIO.getOutputFilename(FILENAME+ ".png"), 1024, 768); + chart.saveAsPng(controllerIO.getOutputFilename(FILENAME+ ".png"), 1024, 768); } diff --git a/matsim/src/main/java/org/matsim/analysis/ScoreStatsControlerListener.java b/matsim/src/main/java/org/matsim/analysis/ScoreStatsControlerListener.java index 50d09d51a63..1593cec5243 100644 --- a/matsim/src/main/java/org/matsim/analysis/ScoreStatsControlerListener.java +++ b/matsim/src/main/java/org/matsim/analysis/ScoreStatsControlerListener.java @@ -22,19 +22,18 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.*; import java.util.stream.Collectors; import jakarta.inject.Inject; -import jakarta.inject.Provider; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.controler.events.ShutdownEvent; @@ -44,10 +43,8 @@ import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; -import org.matsim.core.router.TripRouter; import org.matsim.core.utils.charts.XYLineChart; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; /** * Calculates at the end of each iteration the following statistics: @@ -65,16 +62,15 @@ */ public class ScoreStatsControlerListener implements StartupListener, IterationEndsListener, ShutdownListener, ScoreStats { - public static final String FILENAME_SCORESTATS = "scorestats"; - - public static enum ScoreItem { worst, best, average, executed } ; + public enum ScoreItem { worst, best, average, executed }; - final private Population population; - final private BufferedWriter out; - final private String fileName; + private final Population population; + private final OutputDirectoryHierarchy controllerIO; + private final String delimiter; + private final BufferedWriter out; private final boolean createPNG; - private final ControlerConfigGroup controlerConfigGroup; + private final ControllerConfigGroup controllerConfigGroup; private final Map> scoreHistory = new HashMap<>(); @@ -85,14 +81,14 @@ public static enum ScoreItem { worst, best, average, executed } ; private final static Logger log = LogManager.getLogger(ScoreStatsControlerListener.class); @Inject - ScoreStatsControlerListener(ControlerConfigGroup controlerConfigGroup, Population population, OutputDirectoryHierarchy controlerIO, - PlanCalcScoreConfigGroup scoreConfig, Provider tripRouterFactory ) { - - this.controlerConfigGroup = controlerConfigGroup; + ScoreStatsControlerListener(ControllerConfigGroup controllerConfigGroup, Population population, OutputDirectoryHierarchy controllerIO, + GlobalConfigGroup globalConfig ) { + this.controllerConfigGroup = controllerConfigGroup; this.population = population; - this.fileName = controlerIO.getOutputFilename(FILENAME_SCORESTATS); - this.createPNG = controlerConfigGroup.isCreateGraphs(); - this.out = IOUtils.getBufferedWriter(this.fileName + ".txt"); + this.controllerIO = controllerIO; + this.delimiter = globalConfig.getDefaultDelimiter(); + this.createPNG = controllerConfigGroup.isCreateGraphs(); + this.out = IOUtils.getBufferedWriter(controllerIO.getOutputFilename("scorestats.csv")); Set subpopulations = population.getPersons().values().stream() .map(PopulationUtils::getSubpopulation) @@ -100,13 +96,15 @@ public static enum ScoreItem { worst, best, average, executed } ; .collect(Collectors.toSet()); for (String sub : subpopulations) { - perSubpop.put(sub, new ScoreHist(new HashMap<>(), IOUtils.getBufferedWriter(this.fileName + "_" + sub + ".txt"))); + this.perSubpop.put(sub, new ScoreHist(new HashMap<>(), IOUtils.getBufferedWriter(controllerIO.getOutputFilename("scorestats_" + sub + ".csv")))); } try { - this.out.write("ITERATION\tavg. EXECUTED\tavg. WORST\tavg. AVG\tavg. BEST\n"); - for (Map.Entry e : perSubpop.entrySet()) { - e.getValue().out.write("ITERATION\tavg. EXECUTED\tavg. WORST\tavg. AVG\tavg. BEST\n"); + this.out.write("iteration" + this.delimiter + "avg_executed" + this.delimiter + + "avg_worst" + this.delimiter + "avg_average" + this.delimiter + "avg_best\n"); + for (Map.Entry e : this.perSubpop.entrySet()) { + e.getValue().out.write("iteration" + this.delimiter + "avg_executed" + this.delimiter + + "avg_worst" + this.delimiter + "avg_average" + this.delimiter + "avg_best\n"); } } catch (IOException e) { @@ -116,13 +114,13 @@ public static enum ScoreItem { worst, best, average, executed } ; @Override public void notifyStartup(final StartupEvent event) { - this.minIteration = controlerConfigGroup.getFirstIteration(); + this.minIteration = this.controllerConfigGroup.getFirstIteration(); // int maxIter = controlerConfigGroup.getLastIteration(); // int iterations = maxIter - this.minIteration; // if (iterations > 5000) iterations = 5000; // limit the history size for ( ScoreItem item : ScoreItem.values() ) { - scoreHistory.put( item, new TreeMap<>() ) ; - perSubpop.forEach((s, data) -> data.hist.put(item, new TreeMap<>())); + this.scoreHistory.put( item, new TreeMap<>() ) ; + this.perSubpop.forEach((s, data) -> data.hist.put(item, new TreeMap<>())); } } @@ -152,9 +150,9 @@ private void collectScoreInfo(final IterationEndsEvent event) { log.info("-- avg. score of the best plan of each agent: " + (info.sumScoreBest / info.nofScoreBest)); try { - info.write(event.getIteration(), this.out); + info.write(event.getIteration(), this.out, this.delimiter); for (Map.Entry e : this.perSubpop.entrySet()) { - perSubpop.get(e.getKey()).write(event.getIteration(), e.getValue().out); + perSubpop.get(e.getKey()).write(event.getIteration(), e.getValue().out, this.delimiter); } } catch (IOException e) { @@ -180,7 +178,7 @@ private void collectScoreInfo(final IterationEndsEvent event) { chart.addSeries("avg. of plans' average score", this.scoreHistory.get( ScoreItem.average) ); chart.addSeries("avg. executed score", this.scoreHistory.get( ScoreItem.executed ) ); chart.addMatsimLogo(); - chart.saveAsPng(this.fileName + ".png", 800, 600); + chart.saveAsPng(this.controllerIO.getOutputFilename("scorestats.png"), 800, 600); } } @@ -188,13 +186,12 @@ private void collectScoreInfo(final IterationEndsEvent event) { public void notifyShutdown(final ShutdownEvent controlerShudownEvent) { try { this.out.close(); - for (ScoreHist data : perSubpop.values()) { + for (ScoreHist data : this.perSubpop.values()) { data.out.close(); } } catch (IOException e) { - e.printStackTrace(); + log.error(e.getMessage(), e); } - } @Override @@ -252,28 +249,31 @@ private void update(Person person) { // executed plan? if (PersonUtils.isSelected(plan)) { - sumExecutedScores += score; - nofExecutedScores++; + this.sumExecutedScores += score; + this.nofExecutedScores++; } } if (worstPlan != null) { - nofScoreWorst++; - sumScoreWorst += worstScore; + this.nofScoreWorst++; + this.sumScoreWorst += worstScore; } if (bestPlan != null) { - nofScoreBest++; - sumScoreBest += bestScore; + this.nofScoreBest++; + this.sumScoreBest += bestScore; } if (cntScores > 0) { - sumAvgScores += (sumScores / cntScores); - nofAvgScores++; + this.sumAvgScores += (sumScores / cntScores); + this.nofAvgScores++; } } - private void write(int iteration, BufferedWriter out) throws IOException { - out.write(iteration + "\t" + (sumExecutedScores / nofExecutedScores) + "\t" + - (sumScoreWorst / nofScoreWorst) + "\t" + (sumAvgScores / nofAvgScores) + "\t" + (sumScoreBest / nofScoreBest) + "\n"); + private void write(int iteration, BufferedWriter out, String delimiter) throws IOException { + out.write(iteration + delimiter + + (this.sumExecutedScores / this.nofExecutedScores) + delimiter + + (this.sumScoreWorst / this.nofScoreWorst) + delimiter + + (this.sumAvgScores / this.nofAvgScores) + delimiter + + (this.sumScoreBest / this.nofScoreBest) + "\n"); out.flush(); } diff --git a/matsim/src/main/java/org/matsim/analysis/TravelDistanceStats.java b/matsim/src/main/java/org/matsim/analysis/TravelDistanceStats.java index c0ea8aeccb1..cc46e9434fd 100644 --- a/matsim/src/main/java/org/matsim/analysis/TravelDistanceStats.java +++ b/matsim/src/main/java/org/matsim/analysis/TravelDistanceStats.java @@ -27,17 +27,18 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; 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.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.router.TripStructureUtils.Trip; import org.matsim.core.utils.charts.XYLineChart; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import jakarta.inject.Inject; import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.DoubleSummaryStatistics; import java.util.Locale; import java.util.stream.Collectors; @@ -58,10 +59,11 @@ public class TravelDistanceStats { - private final ControlerConfigGroup controlerConfigGroup; - final private BufferedWriter out; - final private String legStatsPngName; - final private String tripStatsPngName; + private final ControllerConfigGroup controllerConfigGroup; + private final BufferedWriter out; + private final String legStatsPngName; + private final String tripStatsPngName; + private final String delimiter; private double[] legStatsHistory = null; private double[] tripStatsHistory = null; @@ -69,10 +71,12 @@ public class TravelDistanceStats { private final static Logger log = LogManager.getLogger(TravelDistanceStats.class); @Inject - TravelDistanceStats(ControlerConfigGroup controlerConfigGroup, OutputDirectoryHierarchy controlerIO) { - this(controlerConfigGroup, controlerIO.getOutputFilename("traveldistancestats"), + TravelDistanceStats(ControllerConfigGroup controllerConfigGroup, OutputDirectoryHierarchy controlerIO, GlobalConfigGroup globalConfig) { + this(controllerConfigGroup, controlerIO.getOutputFilename("traveldistancestats"), controlerIO.getOutputFilename("traveldistancestats") + "legs", - controlerIO.getOutputFilename("traveldistancestats") + "trips", controlerConfigGroup.isCreateGraphs()); + controlerIO.getOutputFilename("traveldistancestats") + "trips", + controllerConfigGroup.isCreateGraphs(), + globalConfig.getDefaultDelimiter()); } /** @@ -80,30 +84,31 @@ public class TravelDistanceStats { * @param createPNG true if in every iteration, the distance statistics should be visualized in a graph and written to disk. * @throws UncheckedIOException */ - public TravelDistanceStats(final Config config, final String filename, final boolean createPNG) throws UncheckedIOException { - this(config.controler(), filename, filename + "legs", filename + "trips", createPNG); + public TravelDistanceStats(final Config config, final String filename, final boolean createPNG, final String delimiter) throws UncheckedIOException { + this(config.controller(), filename, filename + "legs", filename + "trips", createPNG, delimiter); } - private TravelDistanceStats(ControlerConfigGroup controlerConfigGroup, String travelDistanceStatsFileName, - String legStatsPngName, String tripStatsPngName, boolean createPNG) { - this.controlerConfigGroup = controlerConfigGroup; + private TravelDistanceStats(ControllerConfigGroup controllerConfigGroup, String travelDistanceStatsFileName, + String legStatsPngName, String tripStatsPngName, boolean createPNG, String delimiter) { + this.controllerConfigGroup = controllerConfigGroup; this.legStatsPngName = legStatsPngName; this.tripStatsPngName = tripStatsPngName; + this.delimiter = delimiter; if (createPNG) { - int iterations = controlerConfigGroup.getLastIteration() - controlerConfigGroup.getFirstIteration(); + int iterations = controllerConfigGroup.getLastIteration() - controllerConfigGroup.getFirstIteration(); if (iterations > 5000) { iterations = 5000; // limit the history size } this.legStatsHistory = new double[iterations+1]; this.tripStatsHistory = new double[iterations+1]; } - if (travelDistanceStatsFileName.toLowerCase(Locale.ROOT).endsWith(".txt")) { + if (travelDistanceStatsFileName.toLowerCase(Locale.ROOT).endsWith(".csv")) { this.out = IOUtils.getBufferedWriter(travelDistanceStatsFileName); } else { - this.out = IOUtils.getBufferedWriter(travelDistanceStatsFileName + ".txt"); + this.out = IOUtils.getBufferedWriter(travelDistanceStatsFileName + ".csv"); } try { - this.out.write("ITERATION\tavg. Average Leg distance\tavg. Average Trip distance\n"); + this.out.write("ITERATION" + this.delimiter + "avg. Average Leg distance" + this.delimiter + "avg. Average Trip distance\n"); } catch (IOException e) { throw new UncheckedIOException(e); } @@ -149,22 +154,22 @@ public void addIteration(int iteration, IdMap map) { log.info("(and teleported legs whose route contains a distance.)");// TODO: still valid? try { - this.out.write(iteration + "\t" + legStats.getAverage() + "\t" + tripStats.getAverage() + "\t" + "\n"); + this.out.write(iteration + this.delimiter + legStats.getAverage() + this.delimiter + tripStats.getAverage() + "\n"); this.out.flush(); } catch (IOException e) { e.printStackTrace(); } if (this.legStatsHistory != null) { - int index = iteration - controlerConfigGroup.getFirstIteration(); + int index = iteration - controllerConfigGroup.getFirstIteration(); this.legStatsHistory[index] = legStats.getAverage(); - if (iteration != controlerConfigGroup.getFirstIteration()) { + if (iteration != controllerConfigGroup.getFirstIteration()) { // create chart when data of more than one iteration is available. XYLineChart chart = new XYLineChart("Leg Travel Distance Statistics", "iteration", "average of the average leg distance per plan "); double[] iterations = new double[index + 1]; for (int i = 0; i <= index; i++) { - iterations[i] = i + controlerConfigGroup.getFirstIteration(); + iterations[i] = i + controllerConfigGroup.getFirstIteration(); } double[] values = new double[index + 1]; System.arraycopy(this.legStatsHistory, 0, values, 0, index + 1); @@ -179,15 +184,15 @@ public void addIteration(int iteration, IdMap map) { } if (this.tripStatsHistory != null) { - int index = iteration - controlerConfigGroup.getFirstIteration(); + int index = iteration - controllerConfigGroup.getFirstIteration(); this.tripStatsHistory[index] = tripStats.getAverage(); - if (iteration != controlerConfigGroup.getFirstIteration()) { + if (iteration != controllerConfigGroup.getFirstIteration()) { // create chart when data of more than one iteration is available. XYLineChart chart = new XYLineChart("Trip Travel Distance Statistics", "iteration", "average of the average trip distance per plan "); double[] iterations = new double[index + 1]; for (int i = 0; i <= index; i++) { - iterations[i] = i + controlerConfigGroup.getFirstIteration(); + iterations[i] = i + controllerConfigGroup.getFirstIteration(); } double[] values = new double[index + 1]; System.arraycopy(this.tripStatsHistory, 0, values, 0, index + 1); diff --git a/matsim/src/main/java/org/matsim/api/core/v01/IdAnnotations.java b/matsim/src/main/java/org/matsim/api/core/v01/IdAnnotations.java index c7787f12d41..8ad52b4e7ee 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/IdAnnotations.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/IdAnnotations.java @@ -23,19 +23,23 @@ import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; - -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; +import java.util.HashMap; +import java.util.Map; import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; +import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.ContextualDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; @@ -43,129 +47,91 @@ public interface IdAnnotations { @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotationsInside - @JsonSerialize(using = JsonPersonId.PersonIdSerializer.class) - @JsonDeserialize(using = JsonPersonId.PersonIdDeserializer.class) - public @interface JsonPersonId { - - static class PersonIdSerializer extends StdSerializer> { + @JsonSerialize(using = JsonIdSerializer.class) + @JsonDeserialize(using = JsonIdContextualDeserializer.class) + public @interface JsonId { - protected PersonIdSerializer() { - this(null); - } - - protected PersonIdSerializer(Class> vc) { - super(vc); - } + } - @Override - public void serialize(Id value, JsonGenerator gen, SerializerProvider provider) throws IOException { - gen.writeString(value.toString()); - } + class JsonIdSerializer extends StdSerializer { + protected JsonIdSerializer() { + this(null); } - static class PersonIdDeserializer extends StdDeserializer> { - - protected PersonIdDeserializer() { - this(null); - } - - protected PersonIdDeserializer(Class vc) { - super(vc); - } - - @Override - public Id deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { - JsonNode node = jp.getCodec().readTree(jp); - return Id.createPersonId(node.asText()); - } + protected JsonIdSerializer(Class vc) { + super(vc); + } + @Override + public void serialize(T value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.writeString(value.toString()); } } - @Retention(RetentionPolicy.RUNTIME) - @JacksonAnnotationsInside - @JsonSerialize(using = JsonLinkId.LinkIdSerializer.class) - @JsonDeserialize(using = JsonLinkId.LinkIdDeserializer.class) - public @interface JsonLinkId { - - static class LinkIdSerializer extends StdSerializer> { - - protected LinkIdSerializer() { - this(null); - } - - protected LinkIdSerializer(Class> vc) { - super(vc); - } + class JsonIdContextualDeserializer extends StdDeserializer> implements ContextualDeserializer { - @Override - public void serialize(Id value, JsonGenerator gen, SerializerProvider provider) throws IOException { - gen.writeString(value.toString()); - } + private Class idClass; + protected JsonIdContextualDeserializer() { + this(null); } - static class LinkIdDeserializer extends StdDeserializer> { + protected JsonIdContextualDeserializer(Class idClass) { + super(Object.class); + this.idClass = idClass; + } - protected LinkIdDeserializer() { - this(null); - } + @Override + public JsonDeserializer createContextual(DeserializationContext ctxt, BeanProperty property) + throws JsonMappingException { - protected LinkIdDeserializer(Class vc) { - super(vc); + final Class idClass; + { + final JavaType type; + if (property != null) + type = property.getType(); + else { + type = ctxt.getContextualType(); + } + idClass = type.containedType(0).getRawClass(); } - @Override - public Id deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { - JsonNode node = jp.getCodec().readTree(jp); - return Id.createLinkId(node.asText()); - } + return JsonIdDeserializer.getInstance(idClass); + } + @Override + public Id deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JacksonException { + JsonNode node = jp.getCodec().readTree(jp); + return Id.create(node.asText(), idClass); } } - @Retention(RetentionPolicy.RUNTIME) - @JacksonAnnotationsInside - @JsonSerialize(using = JsonNodeId.NodeIdSerializer.class) - @JsonDeserialize(using = JsonNodeId.NodeIdDeserializer.class) - public @interface JsonNodeId { - - static class NodeIdSerializer extends StdSerializer> { - - protected NodeIdSerializer() { - this(null); - } + class JsonIdDeserializer extends StdDeserializer> { - protected NodeIdSerializer(Class> vc) { - super(vc); - } - - @Override - public void serialize(Id value, JsonGenerator gen, SerializerProvider provider) throws IOException { - gen.writeString(value.toString()); - } + private static final Map, JsonIdDeserializer> CACHE = new HashMap<>(); + public static JsonIdDeserializer getInstance(Class clazz) { + return CACHE.computeIfAbsent(clazz, k -> new JsonIdDeserializer<>(k)); } - static class NodeIdDeserializer extends StdDeserializer> { - - protected NodeIdDeserializer() { - this(null); - } + private final Class idClass; - protected NodeIdDeserializer(Class vc) { - super(vc); - } + private JsonIdDeserializer() { + this(null); + } - @Override - public Id deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { - JsonNode node = jp.getCodec().readTree(jp); - return Id.createNodeId(node.asText()); - } + private JsonIdDeserializer(Class idClass) { + super(Object.class); + this.idClass = idClass; + } + @Override + public Id deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { + JsonNode node = jp.getCodec().readTree(jp); + return Id.create(node.asText(), idClass); } } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/IdDeSerializationModule.java b/matsim/src/main/java/org/matsim/api/core/v01/IdDeSerializationModule.java new file mode 100644 index 00000000000..c25470b8169 --- /dev/null +++ b/matsim/src/main/java/org/matsim/api/core/v01/IdDeSerializationModule.java @@ -0,0 +1,114 @@ +package org.matsim.api.core.v01; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.core.Version; +import com.fasterxml.jackson.databind.BeanDescription; +import com.fasterxml.jackson.databind.DeserializationConfig; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.KeyDeserializer; +import com.fasterxml.jackson.databind.Module; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationConfig; +import com.fasterxml.jackson.databind.deser.Deserializers; +import com.fasterxml.jackson.databind.deser.KeyDeserializers; +import com.fasterxml.jackson.databind.ser.Serializers; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; + +/** + * Use as follows with your {@link ObjectMapper} instance: + * + * {@code objectMapper.registerModule(IdDeSerializationModule.getInstance());} + */ +public class IdDeSerializationModule extends Module { + + private static final String NAME = IdDeSerializationModule.class.getSimpleName(); + private static final Version VERSION = new Version(0, 1, 0, null, "org.matsim", "api.core.v01"); + + private static Module instance = null; + + private IdDeSerializationModule() { + // nothing to do here + } + + public static Module getInstance() { + if (instance == null) { + instance = new IdDeSerializationModule(); + } + return instance; + } + + @Override + public String getModuleName() { + return NAME; + } + + @Override + public Version version() { + return VERSION; + } + + @Override + public void setupModule(SetupContext context) { + context.addSerializers(new IdSerializers()); + context.addDeserializers(new IdDeserializers()); + context.addKeyDeserializers(new IdKeyDeserializers()); + } + + private static final StdSerializer SERIALIZER = new IdAnnotations.JsonIdSerializer<>(Id.class); + private static final Map, KeyDeserializer> KEY_DESERIALIZER_CACHE = new HashMap<>(); + + private static final class IdSerializers extends Serializers.Base { + + @Override + public JsonSerializer findSerializer(SerializationConfig config, JavaType type, + BeanDescription beanDesc) { + if (type.getRawClass().equals(Id.class) && type.containedTypeCount() == 1) { + return SERIALIZER; + } + return null; + } + + } + + private static final class IdDeserializers extends Deserializers.Base { + + @Override + public JsonDeserializer findBeanDeserializer(JavaType type, DeserializationConfig config, + BeanDescription beanDesc) throws JsonMappingException { + if (type.getRawClass().equals(Id.class) && type.containedTypeCount() == 1) { + return IdAnnotations.JsonIdDeserializer.getInstance(type.containedType(0).getRawClass()); + } + return null; + } + + } + + private static final class IdKeyDeserializers implements KeyDeserializers { + + @Override + public KeyDeserializer findKeyDeserializer(JavaType type, DeserializationConfig config, + BeanDescription beanDesc) throws JsonMappingException { + if (type.getRawClass().equals(Id.class) && type.containedTypeCount() == 1) { + return KEY_DESERIALIZER_CACHE.computeIfAbsent(type.containedType(0).getRawClass(), + k -> new KeyDeserializer() { + + @Override + public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { + return Id.create(key, k); + } + + }); + } + return null; + } + + } + +} \ No newline at end of file diff --git a/matsim/src/main/java/org/matsim/api/core/v01/population/Plan.java b/matsim/src/main/java/org/matsim/api/core/v01/population/Plan.java index e06412da59e..6329b62a626 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/population/Plan.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/population/Plan.java @@ -23,6 +23,8 @@ import java.util.List; import org.matsim.api.core.v01.Customizable; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.Identifiable; import org.matsim.core.api.internal.MatsimPopulationObject; import org.matsim.utils.objectattributes.attributable.Attributable; @@ -34,7 +36,7 @@ * The only thing which is not "expected" in the same sense is the score. * */ -public interface Plan extends MatsimPopulationObject, Customizable, BasicPlan, Attributable { +public interface Plan extends MatsimPopulationObject, Customizable, BasicPlan, Attributable, Identifiable { public abstract List getPlanElements(); @@ -49,6 +51,18 @@ public interface Plan extends MatsimPopulationObject, Customizable, BasicPlan, A public abstract String getType(); public abstract void setType(final String type); + + public abstract void setPlanId(Id planId); + + public abstract Id getId(); + + public abstract int getIterationCreated(); + + public abstract void setIterationCreated(int iteration); + + public abstract String getPlanMutator(); + + public abstract void setPlanMutator(String planMutator); public abstract Person getPerson(); @@ -59,5 +73,6 @@ public interface Plan extends MatsimPopulationObject, Customizable, BasicPlan, A * you are using this method!. */ public abstract void setPerson(Person person); + } diff --git a/matsim/src/main/java/org/matsim/core/config/CommandLine.java b/matsim/src/main/java/org/matsim/core/config/CommandLine.java index a4c043e17d2..f23de634e65 100644 --- a/matsim/src/main/java/org/matsim/core/config/CommandLine.java +++ b/matsim/src/main/java/org/matsim/core/config/CommandLine.java @@ -21,6 +21,7 @@ package org.matsim.core.config; +import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -35,7 +36,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ScoringParameterSet; +import org.matsim.core.config.groups.ScoringConfigGroup.ScoringParameterSet; /** *

      @@ -44,63 +45,63 @@ * application in itself, it provides advanced functionality to directly modify * the MATSim {@link Config} object. *

      - * + * *

      General usage

      - * + * *

      * The command line interpreter is set up using the {@link CommandLine.Builder}: *

      - * + * *
        * CommandLine cmd = new CommandLine.Builder(args) //
        * 		.allowOptions("optionA", "optionB") //
        * 		.requireOptions("outputPath") //
        * 		.allowPositionalArguments(false).build();
        * 
      - * + * *

      * The command line option can be accessed via safe getters, which return * {@link Optional}s, or strict getters, which raise exceptions: *

      - * + * *
        * int numberOfThreads = cmd.getOption("threads").map(Integer::parseInt).orElse(4);
        * int numberOfThreads = Integer.parseInt(cmd.getOptionStrict("threads"));
        * 
      - * + * *

      * As can be seen, options are always returned as strings. It is the task of the * user to convert the arguments to the expected data types. They are given in * one of the following ways: *

      - * + * *
        *
      • Value following the option name: --threads 20
      • *
      • With equals sign between: --threads=20
      • *
      - * + * *

      MATSim usage

      - * + * *

      * In order to configure MATSim with the command line, one needs to tell the * interpreter to apply the command line options to the MATSim {@link Config}: *

      - * + * *
        * CommandLine cmd = new CommandLine.Builder(args) //
        * 		.allowPositionalArguments(false)//
        * 		.build();
      - * 
      + *
        * Config config = ConfigUtils.createConfig();
        * cmd.applyConfiguration(config);
        * 
      - * + * *

      * This will interpret all command line options of the form * config:* as options that are supposed to be inserted into the * MATSim config. The rules are as follows: *

      - * + * *
        *
      • --config:MODULE.PARAM VALUE sets a certain parameter with * name PARAM in the module MODULE to the value @@ -113,15 +114,15 @@ *
      • --config:MODULE.SET_TYPE[*=*].PARAM VALUE sets a value in * all parameter sets of SET_TYPE
      • *
      - * + * * Some examples: - * + * *
        *
      • --config:global.numberOfThreads 48
      • *
      • --config:strategy.strategysettings[strategyName=ReRoute].weight 0.0
      • *
      • --config:planCalcScore.scoringParameters[subpopulation=null].modeParams[mode=car].constant -3.5
      • *
      - * + * * @author Sebastian Hörl */ public class CommandLine { @@ -140,6 +141,8 @@ public class CommandLine { final private boolean positionalArgumentsAllowed; final private boolean allowAnyOption; + private final ConfigAliases configAliases = new ConfigAliases(); + // Configuration part /** @@ -157,7 +160,7 @@ static public class Builder { /** * Creates a builder instance. - * + * * @param args The command line arguments passed to the Java application. */ public Builder(String[] args) { @@ -247,7 +250,7 @@ public Builder allowPrefixes(String... prefixes) { * Builds the command line interpreter with the given configuration. An * {@link ConfigurationException} may be thrown directly in one of the following * cases: - * + * *
        *
      • An unnamed (positional) command line argument is passed, although it is * forbidden (see {{@link #allowPositionalArguments(boolean)})
      • @@ -260,7 +263,7 @@ public Builder allowPrefixes(String... prefixes) { *
      • Some command line options have been defined as required (see * {@link #requireOptions(Collection)}), but are not present.
      • *
      - * + * * @throws ConfigurationException */ public CommandLine build() throws ConfigurationException { @@ -348,7 +351,7 @@ public Optional getOption(String option) { /** * Returns a named command line option if it is present, raises a * {@link ConfigurationException} otherwise. - * + * * @throws ConfigurationException */ public String getOptionStrict(String option) throws ConfigurationException { @@ -364,7 +367,7 @@ public String getOptionStrict(String option) throws ConfigurationException { /** * Processes a list of raw command line arguments. - * + * * @throws ConfigurationException */ private void process(List args) throws ConfigurationException { @@ -401,13 +404,13 @@ private void process(List args) throws ConfigurationException { /** * Flattens a list of raw command line arguments: - * + * *
        *
      • Splits ["param=value"] into ["param", "value"], *
      • *
      • but makes sure that ["param[key=value]"] is preserved
      • *
      - * + * * @param args * @return */ @@ -435,7 +438,7 @@ private List flattenArguments(List args) { /** * Adds a positional argument and checks if this is allowed by configuration. - * + * * @throws ConfigurationException */ private void addPositionalArgument(String value) throws ConfigurationException { @@ -448,7 +451,7 @@ private void addPositionalArgument(String value) throws ConfigurationException { /** * Adds a named option and checks whether it is allowed by configuration. - * + * * @throws ConfigurationException */ private void addOption(String option, String value) throws ConfigurationException { @@ -465,7 +468,7 @@ private void addOption(String option, String value) throws ConfigurationExceptio /** * Checks that are required options are present. - * + * * @throws ConfigurationException */ private void checkRequiredOptions() throws ConfigurationException { @@ -488,7 +491,7 @@ private void checkRequiredOptions() throws ConfigurationException { /** * Applies the command line configuration to a MATSim {@link Config} instance. * See {@link CommandLine} for more information on the syntax. - * + * * @throws ConfigurationException */ public void applyConfiguration(Config config) throws ConfigurationException { @@ -555,6 +558,8 @@ private void processConfigOption(Config config, String option, String remainder) String module = remainder.substring(0, separatorIndex); String newRemainder = remainder.substring(separatorIndex + 1); + module = this.configAliases.resolveAlias(module, new ArrayDeque<>()); + if (config.getModules().containsKey(module)) { processParameter(option, module, config.getModules().get(module), newRemainder); } else { @@ -606,13 +611,13 @@ private void processParameter(String option, String path, ConfigGroup configGrou return; } } - + // allow for the case subpopulation = 'null' in the scoring parameters if (parameterSetType.equals(ScoringParameterSet.SET_TYPE) && selectionParameter.equals("subpopulation") && selectionValue.equals("null")) { processParameter(option, newPath, parameterSet, newRemainder); return; } - + } } diff --git a/matsim/src/main/java/org/matsim/core/config/Config.java b/matsim/src/main/java/org/matsim/core/config/Config.java index 45b2a8c74d6..e6ee24c19be 100644 --- a/matsim/src/main/java/org/matsim/core/config/Config.java +++ b/matsim/src/main/java/org/matsim/core/config/Config.java @@ -37,21 +37,20 @@ import org.matsim.core.config.consistency.VspConfigConsistencyCheckerImpl; import org.matsim.core.config.groups.ChangeLegModeConfigGroup; import org.matsim.core.config.groups.ChangeModeConfigGroup; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.CountsConfigGroup; +import org.matsim.core.config.groups.EventsManagerConfigGroup; import org.matsim.core.config.groups.FacilitiesConfigGroup; import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.config.groups.HouseholdsConfigGroup; import org.matsim.core.config.groups.LinkStatsConfigGroup; import org.matsim.core.config.groups.NetworkConfigGroup; -import org.matsim.core.config.groups.ParallelEventHandlingConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; -import org.matsim.core.config.groups.PlansConfigGroup; -import org.matsim.core.config.groups.PtCountsConfigGroup; +import org.matsim.core.config.groups.PlanInheritanceConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup;import org.matsim.core.config.groups.PlansConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.config.groups.ScenarioConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; import org.matsim.core.config.groups.SubtourModeChoiceConfigGroup; import org.matsim.core.config.groups.TimeAllocationMutatorConfigGroup; import org.matsim.core.config.groups.TravelTimeCalculatorConfigGroup; @@ -67,7 +66,7 @@ /** * Stores all configuration settings specified in a configuration file and * provides access to the settings at runtime. - * + * * @see CreateFullConfig * * @author mrieser @@ -119,13 +118,12 @@ public Config() { public void addCoreModules() { this.modules.put(GlobalConfigGroup.GROUP_NAME, new GlobalConfigGroup()); - this.modules.put(ControlerConfigGroup.GROUP_NAME, new ControlerConfigGroup()); + this.modules.put(ControllerConfigGroup.GROUP_NAME, new ControllerConfigGroup()); this.modules.put(QSimConfigGroup.GROUP_NAME, new QSimConfigGroup()); this.modules.put(CountsConfigGroup.GROUP_NAME, new CountsConfigGroup()); - - this.modules.put(PlanCalcScoreConfigGroup.GROUP_NAME, new PlanCalcScoreConfigGroup()); + this.modules.put(ScoringConfigGroup.GROUP_NAME, new ScoringConfigGroup()); this.modules.put(NetworkConfigGroup.GROUP_NAME, new NetworkConfigGroup()); @@ -133,32 +131,31 @@ public void addCoreModules() { this.modules.put(HouseholdsConfigGroup.GROUP_NAME, new HouseholdsConfigGroup()); - this.modules.put(ParallelEventHandlingConfigGroup.GROUP_NAME, new ParallelEventHandlingConfigGroup() ); + this.modules.put(EventsManagerConfigGroup.GROUP_NAME, new EventsManagerConfigGroup() ); this.modules.put(FacilitiesConfigGroup.GROUP_NAME, new FacilitiesConfigGroup()); - this.modules.put(StrategyConfigGroup.GROUP_NAME, new StrategyConfigGroup()); + this.modules.put(ReplanningConfigGroup.GROUP_NAME, new ReplanningConfigGroup()); this.modules.put(TravelTimeCalculatorConfigGroup.GROUPNAME, new TravelTimeCalculatorConfigGroup()); this.modules.put(ScenarioConfigGroup.GROUP_NAME, new ScenarioConfigGroup()); - this.modules.put(PlansCalcRouteConfigGroup.GROUP_NAME, new PlansCalcRouteConfigGroup()); + this.modules.put(RoutingConfigGroup.GROUP_NAME, new RoutingConfigGroup()); this.modules.put(TimeAllocationMutatorConfigGroup.GROUP_NAME, new TimeAllocationMutatorConfigGroup()); this.modules.put(VspExperimentalConfigGroup.GROUP_NAME, new VspExperimentalConfigGroup()); - this.modules.put(PtCountsConfigGroup.GROUP_NAME, new PtCountsConfigGroup()); this.modules.put(TransitConfigGroup.GROUP_NAME, new TransitConfigGroup()); this.modules.put(LinkStatsConfigGroup.GROUP_NAME, new LinkStatsConfigGroup()); this.modules.put(TransitRouterConfigGroup.GROUP_NAME, new TransitRouterConfigGroup()); - + this.modules.put( SubtourModeChoiceConfigGroup.GROUP_NAME , new SubtourModeChoiceConfigGroup() ); - + this.modules.put( VehiclesConfigGroup.GROUP_NAME , new VehiclesConfigGroup() ) ; this.modules.put(ChangeModeConfigGroup.CONFIG_MODULE, new ChangeModeConfigGroup()); @@ -171,6 +168,8 @@ public void addCoreModules() { this.modules.put(HermesConfigGroup.NAME, new HermesConfigGroup()); this.modules.put(ReplanningAnnealerConfigGroup.GROUP_NAME, new ReplanningAnnealerConfigGroup()); + + this.modules.put(PlanInheritanceConfigGroup.GROUP_NAME, new PlanInheritanceConfigGroup()); this.addConfigConsistencyChecker(new VspConfigConsistencyCheckerImpl()); this.addConfigConsistencyChecker(new UnmaterializedConfigGroupChecker()); @@ -400,16 +399,16 @@ public final GlobalConfigGroup global() { return (GlobalConfigGroup) this.getModule(GlobalConfigGroup.GROUP_NAME); } - public final ControlerConfigGroup controler() { - return (ControlerConfigGroup) this.getModule(ControlerConfigGroup.GROUP_NAME); + public final ControllerConfigGroup controller() { + return (ControllerConfigGroup) this.getModule(ControllerConfigGroup.GROUP_NAME); } public final CountsConfigGroup counts() { return (CountsConfigGroup) this.getModule(CountsConfigGroup.GROUP_NAME); } - public final PlanCalcScoreConfigGroup planCalcScore() { - return (PlanCalcScoreConfigGroup) this.getModule(PlanCalcScoreConfigGroup.GROUP_NAME); + public final ScoringConfigGroup scoring() { + return (ScoringConfigGroup) this.getModule(ScoringConfigGroup.GROUP_NAME); } public final NetworkConfigGroup network() { @@ -428,8 +427,8 @@ public final FacilitiesConfigGroup facilities() { return (FacilitiesConfigGroup) this.getModule(FacilitiesConfigGroup.GROUP_NAME); } - public final StrategyConfigGroup strategy() { - return (StrategyConfigGroup) this.getModule(StrategyConfigGroup.GROUP_NAME); + public final ReplanningConfigGroup replanning() { + return (ReplanningConfigGroup) this.getModule(ReplanningConfigGroup.GROUP_NAME); } public TravelTimeCalculatorConfigGroup travelTimeCalculator() { @@ -440,8 +439,8 @@ public ScenarioConfigGroup scenario() { return (ScenarioConfigGroup) this.getModule(ScenarioConfigGroup.GROUP_NAME); } - public PlansCalcRouteConfigGroup plansCalcRoute() { - return (PlansCalcRouteConfigGroup) this.getModule(PlansCalcRouteConfigGroup.GROUP_NAME); + public RoutingConfigGroup routing() { + return (RoutingConfigGroup) this.getModule(RoutingConfigGroup.GROUP_NAME); } public VspExperimentalConfigGroup vspExperimental() { @@ -452,10 +451,6 @@ public QSimConfigGroup qsim() { return (QSimConfigGroup) this.getModule(QSimConfigGroup.GROUP_NAME); } - public PtCountsConfigGroup ptCounts() { - return (PtCountsConfigGroup) this.getModule(PtCountsConfigGroup.GROUP_NAME); - } - public TransitConfigGroup transit() { return (TransitConfigGroup) this.getModule(TransitConfigGroup.GROUP_NAME); } @@ -472,8 +467,8 @@ public TimeAllocationMutatorConfigGroup timeAllocationMutator() { return (TimeAllocationMutatorConfigGroup) this.getModule(TimeAllocationMutatorConfigGroup.GROUP_NAME); } - public ParallelEventHandlingConfigGroup parallelEventHandling() { - return (ParallelEventHandlingConfigGroup) this.getModule(ParallelEventHandlingConfigGroup.GROUP_NAME); + public EventsManagerConfigGroup eventsManager() { + return (EventsManagerConfigGroup) this.getModule(EventsManagerConfigGroup.GROUP_NAME); } public SubtourModeChoiceConfigGroup subtourModeChoice() { @@ -495,6 +490,10 @@ public HermesConfigGroup hermes() { public ReplanningAnnealerConfigGroup replanningAnnealer() { return (ReplanningAnnealerConfigGroup) this.getModule(ReplanningAnnealerConfigGroup.GROUP_NAME); } + + public PlanInheritanceConfigGroup planInheritance() { + return (PlanInheritanceConfigGroup) this.getModule(PlanInheritanceConfigGroup.GROUP_NAME); + } // other: @@ -545,7 +544,7 @@ private void checkIfLocked() { public final VehiclesConfigGroup vehicles() { return (VehiclesConfigGroup) this.getModule(VehiclesConfigGroup.GROUP_NAME); } - + public void setContext(URL context) { if ( this.context==null || !(context.toString().equals( this.context.toString() ) ) ) { log.info("setting context to [" + context + "]"); diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigAliases.java b/matsim/src/main/java/org/matsim/core/config/ConfigAliases.java new file mode 100644 index 00000000000..a95ce30372e --- /dev/null +++ b/matsim/src/main/java/org/matsim/core/config/ConfigAliases.java @@ -0,0 +1,86 @@ +package org.matsim.core.config; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.Deque; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Stack; +import java.util.stream.Collectors; + +public final class ConfigAliases { + + private final static Logger LOG = LogManager.getLogger(ConfigAliases.class); + + private final Map> aliases = new HashMap<>(); + + public ConfigAliases() { + this.addDefaultAliases(); + } + + public void addDefaultAliases() { + this.addAlias("ReplanningAnnealer", "replanningAnnealer"); + this.addAlias("TimeAllocationMutator", "timeAllocationMutator"); + this.addAlias("JDEQSim", "jdeqsim"); + this.addAlias("controler", "controller"); + this.addAlias("planCalcScore", "scoring"); + this.addAlias("planscalcroute", "routing"); + this.addAlias("strategy", "replanning"); + this.addAlias("parallelEventHandling", "eventsManager"); + this.addAlias("freight", "freightCarriers"); + + this.addAlias("BrainExpBeta", "brainExpBeta", "scoring"); + this.addAlias("PathSizeLogitBeta", "pathSizeLogitBeta", "scoring"); + } + + public void addAlias(String oldName, String newName, String... path) { + this.aliases.computeIfAbsent(oldName, k -> new ArrayList<>(2)).add(new ConfigAlias(oldName, newName, path)); + } + + public void clearAliases() { + this.aliases.clear(); + } + + public String resolveAlias(String oldName, Deque pathStack) { + List definedAliases = this.aliases.get(oldName); + if (definedAliases == null || definedAliases.isEmpty()) { + return oldName; + } + for (ConfigAlias alias: definedAliases) { + boolean matches = true; + + if (alias.path.length > pathStack.size()) { + matches = false; + } else { + Iterator iter = pathStack.iterator(); + for (int i = alias.path.length - 1; i >= 0; i--) { + if (iter.hasNext()) { + String name = iter.next(); + if (!name.equals(alias.path[i])) { + matches = false; + break; + } + } else { + matches = false; + break; + } + } + } + + if (matches) { + String stack = pathStack.stream().collect(Collectors.joining(" < ", oldName + " < ", " /")); + LOG.warn("Config name '{}' is deprecated, please use '{}' instead. Config path: {}", oldName, alias.newName, stack); + return alias.newName; + } + } + return oldName; + } + + public record ConfigAlias(String oldName, String newName, String[] path) { + } + +} diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigReader.java b/matsim/src/main/java/org/matsim/core/config/ConfigReader.java index 319f1b65461..f35d8adc593 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigReader.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigReader.java @@ -20,17 +20,13 @@ package org.matsim.core.config; -import java.io.File; -import java.io.InputStream; +import java.io.UncheckedIOException; import java.util.Stack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.core.api.internal.MatsimSomeReader; import org.matsim.core.utils.io.MatsimXmlParser; -import org.matsim.core.utils.io.UncheckedIOException; import org.xml.sax.Attributes; -import org.xml.sax.InputSource; /** * A reader for config-files of MATSim. This reader recognizes the format of the config-file and uses @@ -45,6 +41,7 @@ public final class ConfigReader extends MatsimXmlParser { private final static String CONFIG_V1 = "config_v1.dtd"; private final static String CONFIG_V2 = "config_v2.dtd"; + private final ConfigAliases aliases = new ConfigAliases(); private final Config config; private MatsimXmlParser delegate = null; @@ -64,6 +61,10 @@ public ConfigReader(final Config config) { this.config = config; } + public ConfigAliases getConfigAliases() { + return this.aliases; + } + @Override public void startTag(final String name, final Attributes atts, final Stack context) { this.delegate.startTag(name, atts, context); diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV1.java b/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV1.java index b3b9f9d9ae7..7d5c829d670 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV1.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV1.java @@ -28,8 +28,12 @@ import org.matsim.core.utils.io.MatsimXmlParser; import org.xml.sax.Attributes; +import java.util.ArrayDeque; +import java.util.Deque; import java.util.Stack; +import static org.matsim.core.config.ConfigV2XmlNames.NAME; + /** * A reader for config-files of MATSim according to config_v1.dtd. * @@ -46,10 +50,12 @@ class ConfigReaderMatsimV1 extends MatsimXmlParser { private static final String msg = "using deprecated config version; please switch to config v2; your output_config.xml " + "will be in the correct version; v1 will fail eventually, since we want to reduce the " + "workload on keeping everything between v1 and v2 consistent (look into " + - "PlanCalcScoreConfigGroup or PlanCalcRouteConfigGroup if you want to know what we mean)."; + "ScoringConfigGroup or RoutingConfigGroup if you want to know what we mean)."; private final Config config; + private final ConfigAliases aliases; + private final Deque pathStack = new ArrayDeque<>(); private ConfigGroup currmodule = null; private String localDtd; @@ -57,6 +63,14 @@ class ConfigReaderMatsimV1 extends MatsimXmlParser { public ConfigReaderMatsimV1(final Config config) { super(ValidationType.DTD_ONLY); this.config = config; + this.aliases = new ConfigAliases(); + log.warn(msg); + } + + public ConfigReaderMatsimV1(final Config config, final ConfigAliases aliases) { + super(ValidationType.DTD_ONLY); + this.config = config; + this.aliases = aliases; log.warn(msg); } @@ -86,11 +100,12 @@ public void endTag(final String name, final String content, final Stack // :-( kai, aug'18 this.currmodule = null; + this.pathStack.removeFirst(); } } private void startModule(final Attributes atts) { - String name = atts.getValue("name"); + String name = this.aliases.resolveAlias(atts.getValue(NAME), this.pathStack); this.currmodule = this.config.getModule(name); if (this.currmodule == null) { @@ -106,10 +121,12 @@ private void startModule(final Attributes atts) { this.currmodule = this.config.createModule(atts.getValue("name")); } } + this.pathStack.addFirst(name); } - private void startParam(final Attributes meta) { - this.currmodule.addParam(meta.getValue("name"), meta.getValue("value")); + private void startParam(final Attributes atts) { + String name = this.aliases.resolveAlias(atts.getValue(NAME), this.pathStack); + this.currmodule.addParam(name, atts.getValue("value")); } /** diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV2.java b/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV2.java index 755fb36341e..02fcde5d57e 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV2.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV2.java @@ -38,6 +38,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.checkerframework.checker.units.qual.C; import org.matsim.core.utils.io.MatsimXmlParser; import org.xml.sax.Attributes; @@ -50,63 +51,24 @@ class ConfigReaderMatsimV2 extends MatsimXmlParser { private final Config config; - private final Map> aliases = new HashMap<>(); + private final ConfigAliases aliases; private final Deque moduleStack = new ArrayDeque<>(); + private final Deque pathStack = new ArrayDeque<>(); ConfigReaderMatsimV2(final Config config) { super(ValidationType.DTD_ONLY); this.config = config; - this.addDefaultAliases(); + this.aliases = new ConfigAliases(); } - public void addDefaultAliases() { - // when renaming config modules and parameter names, add them here as aliases: -// this.addAlias("controler", "controller"); -// this.addAlias("planCalcScore", "scoring"); -// this.addAlias("planscalcroute", "routing"); - } - - public void addAlias(String oldName, String newName, String... path) { - this.aliases.computeIfAbsent(oldName, k -> new ArrayList<>(2)).add(new ConfigAlias(oldName, newName, path)); + ConfigReaderMatsimV2(final Config config, final ConfigAliases aliases) { + super(ValidationType.DTD_ONLY); + this.config = config; + this.aliases = aliases; } - public void clearAliases() { - this.aliases.clear(); - } - - private String resolveAlias(String oldName) { - List definedAliases = this.aliases.get(oldName); - if (definedAliases == null || definedAliases.isEmpty()) { - return oldName; - } - for (ConfigAlias alias: definedAliases) { - boolean matches = true; - - if (alias.path.length > this.moduleStack.size()) { - matches = false; - } else { - Iterator iter = this.moduleStack.iterator(); - for (int i = alias.path.length - 1; i >= 0; i--) { - if (iter.hasNext()) { - String name = iter.next().getName(); - if (!name.equals(alias.path[i])) { - matches = false; - break; - } - } else { - matches = false; - break; - } - } - } - - if (matches) { - String stack = this.moduleStack.stream().map(c -> c.getName()).collect(Collectors.joining(" < ", oldName + " < ", " /")); - LOG.warn("Config name '{}' is deprecated, please use '{}' instead. Config path: {}", oldName, alias.newName, stack); - return alias.newName; - } - } - return oldName; + public ConfigAliases getConfigAliases() { + return this.aliases; } @Override @@ -132,25 +94,27 @@ else if ( !name.equals( "config" ) ) { } private void startParameter(final Attributes atts) { - String name = resolveAlias(atts.getValue(NAME)); - moduleStack.getFirst().addParam( + String name = this.aliases.resolveAlias(atts.getValue(NAME), this.pathStack); + this.moduleStack.getFirst().addParam( name, atts.getValue( VALUE ) ); } private void startParameterSet(final Attributes atts) { - String type = resolveAlias(atts.getValue(TYPE)); - final ConfigGroup m = moduleStack.getFirst().createParameterSet( type ); - moduleStack.addFirst( m ); + String type = this.aliases.resolveAlias(atts.getValue(TYPE), this.pathStack); + final ConfigGroup m = this.moduleStack.getFirst().createParameterSet( type ); + this.moduleStack.addFirst(m); + this.pathStack.addFirst(m.getName()); } private void startModule(final Attributes atts) { - String name = resolveAlias(atts.getValue(NAME)); - final ConfigGroup m = config.getModule(name); - moduleStack.addFirst( - m == null ? - config.createModule(name) : - m ); + String name = this.aliases.resolveAlias(atts.getValue(NAME), this.pathStack); + ConfigGroup m = this.config.getModule(name); + if (m == null) { + m = this.config.createModule(name); + } + this.moduleStack.addFirst(m); + this.pathStack.addFirst(m.getName()); } @Override @@ -159,14 +123,12 @@ public void endTag( final String content, final Stack context) { if ( name.equals( MODULE ) || name.equals( PARAMETER_SET ) ) { - final ConfigGroup head = moduleStack.removeFirst(); + final ConfigGroup head = this.moduleStack.removeFirst(); + this.pathStack.removeFirst(); - if ( !moduleStack.isEmpty() ) moduleStack.getFirst().addParameterSet( head ); + if ( !this.moduleStack.isEmpty() ) this.moduleStack.getFirst().addParameterSet( head ); } } - public record ConfigAlias(String oldName, String newName, String[] path) { - } - } diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigUtils.java b/matsim/src/main/java/org/matsim/core/config/ConfigUtils.java index 3022bc62bc4..df396f15b1a 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigUtils.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigUtils.java @@ -23,21 +23,18 @@ import org.matsim.core.api.internal.MatsimExtensionPoint; import org.matsim.core.config.ConfigWriter.Verbosity; import org.matsim.core.config.groups.PlansConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.config.groups.VspExperimentalConfigGroup.VspDefaultsCheckingLevel; import org.matsim.core.gbl.Gbl; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import java.io.File; +import java.io.UncheckedIOException; import java.net.URL; import java.util.Arrays; -import java.util.Iterator; /** * @author mrieser - */ -/** * @author nagel * */ @@ -237,7 +234,7 @@ public static void modifyFilePaths(final Config config, final String pathPrefix) if (!prefix.endsWith("/") && !prefix.endsWith(File.separator)) { prefix = prefix + File.separator; } - config.controler().setOutputDirectory(getAbsolutePath(prefix, config.controler().getOutputDirectory())); + config.controller().setOutputDirectory(getAbsolutePath(prefix, config.controller().getOutputDirectory())); config.network().setInputFile(getAbsolutePath(prefix, config.network().getInputFile())); config.plans().setInputFile(getAbsolutePath(prefix, config.plans().getInputFile())); config.facilities().setInputFile(getAbsolutePath(prefix, config.facilities().getInputFile())); @@ -264,7 +261,7 @@ private static String getAbsolutePath(final String prefix, final String path) { // (Had the problem in RandomizingTransitRotuerIT.) kai, dec'19 public static Id createAvailableStrategyId(Config config) { long maxStrategyId = 0; - for( StrategySettings strategySettings : config.strategy().getStrategySettings() ){ + for( StrategySettings strategySettings : config.replanning().getStrategySettings() ){ maxStrategyId = Math.max( maxStrategyId , Long.parseLong( strategySettings.getId().toString() ) ); } return Id.create(maxStrategyId + 1, StrategySettings.class); diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigWriter.java b/matsim/src/main/java/org/matsim/core/config/ConfigWriter.java index 5be496a65e4..257775fb139 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigWriter.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigWriter.java @@ -22,15 +22,14 @@ import java.io.BufferedWriter; import java.io.IOException; -import java.util.Iterator; +import java.io.UncheckedIOException; import org.matsim.core.api.internal.MatsimWriter; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; public final class ConfigWriter extends MatsimXmlWriter implements MatsimWriter { - - public static enum Verbosity {all, minimal } + + public static enum Verbosity {all, minimal } ////////////////////////////////////////////////////////////////////// // member variables @@ -93,7 +92,7 @@ public final void writeFileV1(final String filename) { this.handler = new ConfigWriterHandlerImplV1(); write( filename ); } - + public final void writeFileV2(final String filename) { this.dtd = "http://www.matsim.org/files/dtd/config_v2.dtd"; this.handler = new ConfigWriterHandlerImplV2(Verbosity.all); diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV1.java b/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV1.java index f786998a614..53813b54e4b 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV1.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV1.java @@ -22,10 +22,9 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.Map; -import org.matsim.core.utils.io.UncheckedIOException; - /*package*/ class ConfigWriterHandlerImplV1 extends ConfigWriterHandler { private String newline = "\n"; @@ -75,9 +74,9 @@ void writeModule(final ConfigGroup module, final BufferedWriter out) throws Unch out.write("\t"); out.write(this.newline); - + boolean lastHadComment = false; - + for (Map.Entry entry : params.entrySet()) { if (comments.get(entry.getKey()) != null) { out.write(this.newline); diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV2.java b/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV2.java index 91f98383c62..c511b1952da 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV2.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV2.java @@ -22,16 +22,16 @@ import org.apache.logging.log4j.LogManager; import org.matsim.core.config.ConfigWriter.Verbosity; import org.matsim.core.config.groups.ChangeLegModeConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ScoringParameterSet; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; -import org.matsim.core.utils.io.UncheckedIOException; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ScoringParameterSet; +import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -55,16 +55,16 @@ class ConfigWriterHandlerImplV2 extends ConfigWriterHandler { // paths. If someone feels like doing that, please go ahead. kai, jun'18 private String newline = "\n"; - + /** * So we can write only what deviates from the default. * Implementation of this functionality unfortunately became quite messy. * kai, may'18 */ private final Verbosity verbosity; - + private final Set commentsAlreadyWritten = new HashSet<>() ; - + ConfigWriterHandlerImplV2( Verbosity verbosity ) { this.verbosity = verbosity ; } @@ -81,10 +81,10 @@ private void writeModule( Map comments = module.getComments(); try { - + // first write the regular config entries (key,value pairs) boolean headerHasBeenWritten = writeRegularEntries(writer, indent, moduleTag, moduleNameAtt, moduleName, comparisonModule, params, comments); - + // can't say what this is for: if ( moduleName.equals("thisAintNoFlat") ) { LogManager.getLogger(this.getClass()).warn("here") ; @@ -92,7 +92,7 @@ private void writeModule( // then process the parameter sets (which will recursively call the current method again): headerHasBeenWritten = processParameterSets(writer, indent, moduleTag, moduleNameAtt, moduleName, module, comparisonModule, headerHasBeenWritten); - + if ( headerHasBeenWritten ) { writer.write(indent); writer.write("\t"); @@ -103,7 +103,7 @@ private void writeModule( throw new UncheckedIOException(e); } } - + private Boolean processParameterSets(BufferedWriter writer, String indent, String moduleTag, String moduleNameAtt, String moduleName, ConfigGroup module, ConfigGroup comparisonModule, Boolean headerHasBeenWritten) throws IOException { for ( Entry> entry : module.getParameterSets().entrySet() ) { @@ -125,13 +125,13 @@ private Boolean processParameterSets(BufferedWriter writer, String indent, Strin // } if ( verbosity== Verbosity.minimal && comparisonPSet==null ) { if ( pSet instanceof ScoringParameterSet) { - comparisonPSet = ((PlanCalcScoreConfigGroup) comparisonModule).getOrCreateScoringParameters(((ScoringParameterSet) pSet).getSubpopulation()); + comparisonPSet = ((ScoringConfigGroup) comparisonModule).getOrCreateScoringParameters(((ScoringParameterSet) pSet).getSubpopulation()); } else if ( pSet instanceof ModeParams ) { comparisonPSet = ((ScoringParameterSet) comparisonModule).getOrCreateModeParams(((ModeParams) pSet).getMode()); } else if ( pSet instanceof ActivityParams ) { comparisonPSet = ((ScoringParameterSet) comparisonModule).getOrCreateActivityParams(((ActivityParams) pSet).getActivityType()); - } else if ( pSet instanceof PlansCalcRouteConfigGroup.TeleportedModeParams ) { - comparisonPSet = ((PlansCalcRouteConfigGroup) comparisonModule).getOrCreateModeRoutingParams(((PlansCalcRouteConfigGroup.TeleportedModeParams) pSet).getMode() ) ; + } else if ( pSet instanceof RoutingConfigGroup.TeleportedModeParams ) { + comparisonPSet = ((RoutingConfigGroup) comparisonModule).getOrCreateModeRoutingParams(((RoutingConfigGroup.TeleportedModeParams) pSet).getMode() ) ; } else { try { comparisonPSet = pSet.getClass().newInstance(); @@ -155,13 +155,13 @@ private Boolean processParameterSets(BufferedWriter writer, String indent, Strin } return headerHasBeenWritten; } - + private Boolean writeRegularEntries(BufferedWriter writer, String indent, String moduleTag, String moduleNameAtt, String moduleName, ConfigGroup comparisonModule, Map params, Map comments) throws IOException { boolean headerHasBeenWritten = false ; for (Entry entry : params.entrySet()) { - + final String actual = entry.getValue(); if ( verbosity== Verbosity.minimal ) { if ( comparisonModule!=null ) { @@ -188,7 +188,7 @@ private Boolean writeRegularEntries(BufferedWriter writer, String indent, String // } } } - + if ( !headerHasBeenWritten ) { headerHasBeenWritten = true ; writeHeader(writer, indent, moduleTag, moduleNameAtt, moduleName, newline); @@ -215,7 +215,7 @@ private Boolean writeRegularEntries(BufferedWriter writer, String indent, String } return headerHasBeenWritten; } - + private static void writeHeader(BufferedWriter writer, String indent, String moduleTag, String moduleNameAtt, String moduleName, String newline) throws IOException { // writer.write( this.newline ); writer.write( indent ); @@ -223,14 +223,14 @@ private static void writeHeader(BufferedWriter writer, String indent, String mod writer.write(" "+moduleNameAtt+"=\"" + moduleName + "\" >"); writer.write( newline ); } - + private static boolean sameType(ConfigGroup pSet, ConfigGroup cg) { if ( ! ( pSet.getName().equals( cg.getName() ) ) ) { return false; } - if ( pSet instanceof PlansCalcRouteConfigGroup.TeleportedModeParams ) { + if ( pSet instanceof RoutingConfigGroup.TeleportedModeParams ) { // (these are the "teleportedRouteParameters" in config.xml) - if ( ((PlansCalcRouteConfigGroup.TeleportedModeParams)pSet).getMode().equals( ((PlansCalcRouteConfigGroup.TeleportedModeParams)cg).getMode() ) ) { + if ( ((RoutingConfigGroup.TeleportedModeParams)pSet).getMode().equals( ((RoutingConfigGroup.TeleportedModeParams)cg).getMode() ) ) { return true ; } } @@ -253,7 +253,7 @@ private static boolean sameType(ConfigGroup pSet, ConfigGroup cg) { } return false ; } - + @Override void startConfig( final Config config, @@ -264,7 +264,7 @@ void startConfig( } catch (IOException e) { throw new UncheckedIOException(e); } - + } @Override @@ -276,7 +276,7 @@ void endConfig( out.write( this.newline ); } catch (IOException e) { throw new UncheckedIOException(e); - } + } } @Override @@ -285,14 +285,14 @@ void writeModule( final BufferedWriter out) { if ( ! (module instanceof ChangeLegModeConfigGroup) ) { // yyyy special case to provide error message; may be removed eventually. kai, may'16 - - + + ConfigGroup comparisonConfig = null ; if ( verbosity==Verbosity.minimal) { comparisonConfig = ConfigUtils.createConfig().getModules().get(module.getName()); // preference to generate this here multiple times to avoid having it as a field. kai, may'18 } - + writeModule( out, "", diff --git a/matsim/src/main/java/org/matsim/core/config/ReflectiveConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/ReflectiveConfigGroup.java index 8181560dd17..1301c6daeb1 100644 --- a/matsim/src/main/java/org/matsim/core/config/ReflectiveConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/ReflectiveConfigGroup.java @@ -32,6 +32,9 @@ import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -234,10 +237,11 @@ private static void checkParamFieldValidity(Field field) { private static final Set> ALLOWED_PARAMETER_TYPES = Set.of(String.class, Float.class, Double.class, Integer.class, Long.class, Boolean.class, Character.class, Byte.class, Short.class, Float.TYPE, Double.TYPE, - Integer.TYPE, Long.TYPE, Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE); + Integer.TYPE, Long.TYPE, Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, LocalTime.class, + LocalDate.class, LocalDateTime.class); private static final String HINT = " Valid types are String, primitive types and their wrapper classes," - + " enumerations, List and Set." + + " enumerations, List and Set, LocalTime, LocalDate, LocalDateTime" + " Other types are fine as parameters, but you will need to implement conversion strategies" + " in corresponding StringGetters andStringSetters."; @@ -342,6 +346,12 @@ private Object fromString(String value, Class type, @Nullable Field paramFiel return null; } else if (type.equals(String.class)) { return value; + } else if (type.equals(LocalTime.class)) { + return LocalTime.parse(value); + } else if (type.equals(LocalDate.class)) { + return LocalDate.parse(value); + } else if (type.equals(LocalDateTime.class)) { + return LocalDateTime.parse(value); } else if (type.equals(Float.class) || type.equals(Float.TYPE)) { return Float.parseFloat(value); } else if (type.equals(Double.class) || type.equals(Double.TYPE)) { diff --git a/matsim/src/main/java/org/matsim/core/config/consistency/ConfigConsistencyCheckerImpl.java b/matsim/src/main/java/org/matsim/core/config/consistency/ConfigConsistencyCheckerImpl.java index ace3b44225b..f00ec94def2 100644 --- a/matsim/src/main/java/org/matsim/core/config/consistency/ConfigConsistencyCheckerImpl.java +++ b/matsim/src/main/java/org/matsim/core/config/consistency/ConfigConsistencyCheckerImpl.java @@ -23,11 +23,11 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.TransportMode; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup.EventsFileFormat; -import org.matsim.core.config.groups.ControlerConfigGroup.RoutingAlgorithmType; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; +import org.matsim.core.config.groups.ControllerConfigGroup.EventsFileFormat; +import org.matsim.core.config.groups.ControllerConfigGroup.RoutingAlgorithmType; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.pt.PtConstants; /** @@ -68,29 +68,29 @@ static boolean checkConsistencyBetweenRouterAndTravelTimeCalculator( final Confi } /*package because of test */ static void checkPlanCalcScore(final Config c) { - ModeParams ptModeParams = c.planCalcScore().getModes().get(TransportMode.pt); + ModeParams ptModeParams = c.scoring().getModes().get(TransportMode.pt); if (ptModeParams!=null && ptModeParams.getMarginalUtilityOfTraveling() > 0) { - log.warn(PlanCalcScoreConfigGroup.GROUP_NAME + ".travelingPt is > 0. This values specifies a utility. " + + log.warn(ScoringConfigGroup.GROUP_NAME + ".travelingPt is > 0. This values specifies a utility. " + "Typically, this should be a disutility, i.e. have a negative value."); } - ModeParams carModeParams = c.planCalcScore().getModes().get(TransportMode.car); + ModeParams carModeParams = c.scoring().getModes().get(TransportMode.car); if (carModeParams!=null && carModeParams.getMarginalUtilityOfTraveling() > 0) { - log.warn(PlanCalcScoreConfigGroup.GROUP_NAME + ".traveling is > 0. This values specifies a utility. " + + log.warn(ScoringConfigGroup.GROUP_NAME + ".traveling is > 0. This values specifies a utility. " + "Typically, this should be a disutility, i.e. have a negative value."); } - ModeParams bikeModeParams = c.planCalcScore().getModes().get(TransportMode.bike); + ModeParams bikeModeParams = c.scoring().getModes().get(TransportMode.bike); if (bikeModeParams!=null && bikeModeParams.getMarginalUtilityOfTraveling() > 0) { - log.warn(PlanCalcScoreConfigGroup.GROUP_NAME + ".travelingBike is > 0. This values specifies a utility. " + + log.warn(ScoringConfigGroup.GROUP_NAME + ".travelingBike is > 0. This values specifies a utility. " + "Typically, this should be a disutility, i.e. have a negative value."); } - ModeParams walkModeParams = c.planCalcScore().getModes().get(TransportMode.walk); + ModeParams walkModeParams = c.scoring().getModes().get(TransportMode.walk); if (walkModeParams!=null && walkModeParams.getMarginalUtilityOfTraveling() > 0) { - log.warn(PlanCalcScoreConfigGroup.GROUP_NAME + ".travelingWalk is > 0. This values specifies a utility. " + + log.warn(ScoringConfigGroup.GROUP_NAME + ".travelingWalk is > 0. This values specifies a utility. " + "Typically, this should be a disutility, i.e. have a negative value."); } - - - ActivityParams ptAct = c.planCalcScore().getActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE) ; + + + ActivityParams ptAct = c.scoring().getActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE) ; if ( ptAct != null ) { // if ( ptAct.getClosingTime()!=0. && ptAct.getClosingTime()!=Time.getUndefinedTime() ) { // if ( !c.vspExperimental().isAbleToOverwritePtInteractionParams()==true ) { @@ -105,12 +105,12 @@ static boolean checkConsistencyBetweenRouterAndTravelTimeCalculator( final Confi } } } - + } private static void checkEventsFormatLanesSignals(final Config c) { if (c.qsim().isUseLanes()) { - if (!c.controler().getEventsFileFormats().contains(EventsFileFormat.xml)){ + if (!c.controller().getEventsFileFormats().contains(EventsFileFormat.xml)){ log.error("Xml events are not enabled, but lanes and possibly signal systems" + "are enalbed. Events from this features will only be written to the xml format, consider" + "to add xml events in the controler config module"); @@ -119,7 +119,7 @@ private static void checkEventsFormatLanesSignals(final Config c) { } private static void checkScenarioFeaturesEnabled(final Config c) { - if (! ("qsim".equals(c.controler().getMobsim()) || c.qsim() != null)){ + if (! ("qsim".equals(c.controller().getMobsim()) || c.qsim() != null)){ log.warn("The signal system implementation is only supported by the org.matsim.ptproject.qsim mobility simulation that is not activated. Please make sure you are using the correct" + "mobility simulation. This warning can be ingored if a customized mobility simulation developed outside of org.matsim is used and set correctly."); } @@ -127,7 +127,7 @@ private static void checkScenarioFeaturesEnabled(final Config c) { private static void checkTravelTimeCalculationRoutingConfiguration(final Config config){ - if (config.controler().isLinkToLinkRoutingEnabled() && + if (config.controller().isLinkToLinkRoutingEnabled() && !config.travelTimeCalculator().isCalculateLinkToLinkTravelTimes()){ throw new IllegalStateException("LinkToLinkRouting is activated in config and" + " link to link traveltime calculation is not enabled but required!"); @@ -135,7 +135,7 @@ private static void checkTravelTimeCalculationRoutingConfiguration(final Config if (config.travelTimeCalculator().isCalculateLinkTravelTimes() && config.travelTimeCalculator().isCalculateLinkToLinkTravelTimes() && - !config.controler().isLinkToLinkRoutingEnabled()) { + !config.controller().isLinkToLinkRoutingEnabled()) { log.warn("Config enables link travel time calculation and link to link " + "travel time calculation. This requires at least twice as much memory as " + "if only one method is used, however it might be necessary to enable " + @@ -153,17 +153,17 @@ private static void checkTravelTimeCalculationRoutingConfiguration(final Config "available if using the remove stuck vehicles option!"); } - if ( config.controler().isLinkToLinkRoutingEnabled() && - config.controler().getRoutingAlgorithmType() != RoutingAlgorithmType.Dijkstra ) { + if ( config.controller().isLinkToLinkRoutingEnabled() && + config.controller().getRoutingAlgorithmType() != RoutingAlgorithmType.Dijkstra ) { log.warn("We don't know if non-Dijkstra routing works together with LinkToLink routing."); } - + } private static void checkLaneDefinitionRoutingConfiguration(final Config config) { if ((config.qsim().isUseLanes()) && - !config.controler().isLinkToLinkRoutingEnabled()){ + !config.controller().isLinkToLinkRoutingEnabled()){ log.warn("Using lanes without enabling linktolinkrouting might not lead to expected simulation results"); } } diff --git a/matsim/src/main/java/org/matsim/core/config/consistency/VspConfigConsistencyCheckerImpl.java b/matsim/src/main/java/org/matsim/core/config/consistency/VspConfigConsistencyCheckerImpl.java index 9fdd9cc0c70..901d5da4b5c 100644 --- a/matsim/src/main/java/org/matsim/core/config/consistency/VspConfigConsistencyCheckerImpl.java +++ b/matsim/src/main/java/org/matsim/core/config/consistency/VspConfigConsistencyCheckerImpl.java @@ -26,13 +26,12 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.core.config.Config; import org.matsim.core.config.groups.*; -import org.matsim.core.config.groups.ControlerConfigGroup.EventsFileFormat; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.TypicalDurationScoreComputation; +import org.matsim.core.config.groups.ControllerConfigGroup.EventsFileFormat; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.config.groups.QSimConfigGroup.TrafficDynamics; 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.config.groups.VspExperimentalConfigGroup.CheckingOfMarginalUtilityOfTravellng; import org.matsim.core.config.groups.VspExperimentalConfigGroup.VspDefaultsCheckingLevel; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule.DefaultStrategy; @@ -53,9 +52,9 @@ public final class VspConfigConsistencyCheckerImpl implements ConfigConsistencyC // VSP says that people < 18J should not use car, and implements that via car availability. How to handle that? - // + // private static final Logger log = LogManager.getLogger(VspConfigConsistencyCheckerImpl.class); - + public VspConfigConsistencyCheckerImpl() { // empty. only here to find out where it is called. } @@ -75,11 +74,11 @@ public void checkConsistency(Config config) { default -> throw new RuntimeException( "not implemented" ); } log.info("running checkConsistency ..."); - + boolean problem = false ; // ini - + // yy: sort the config groups alphabetically - + // === controler: problem = checkControlerConfigGroup( config, lvl, problem ); @@ -131,17 +130,17 @@ public void checkConsistency(Config config) { // === interaction between config groups: boolean containsModeChoice = false ; - for ( StrategySettings settings : config.strategy().getStrategySettings() ) { + for ( StrategySettings settings : config.replanning().getStrategySettings() ) { if ( settings.getStrategyName().contains("Mode") ) { containsModeChoice = true ; } } - + // added jun'16 - if ( config.qsim().getVehiclesSource()==VehiclesSource.fromVehiclesData - && config.qsim().getUsePersonIdForMissingVehicleId() - && containsModeChoice - && config.qsim().getMainModes().size() > 1 ) + if ( config.qsim().getVehiclesSource()==VehiclesSource.fromVehiclesData + && config.qsim().getUsePersonIdForMissingVehicleId() + && containsModeChoice + && config.qsim().getMainModes().size() > 1 ) { problem = true ; log.log( lvl, "You can't use more than one main (=vehicular) mode while using the agent ID as missing vehicle ID ... " @@ -149,14 +148,14 @@ public void checkConsistency(Config config) { } // === zzz: - + if ( problem && config.vspExperimental().getVspDefaultsCheckingLevel() == VspDefaultsCheckingLevel.abort ) { - String str = "found a situation that leads to vsp-abort. aborting ..." ; + String str = "found a situation that leads to vsp-abort. aborting ..." ; System.out.flush() ; - log.fatal( str ) ; + log.fatal( str ) ; throw new RuntimeException( str ) ; } - + } private boolean checkSubtourModeChoiceConfigGroup( Config config, Level lvl, boolean problem ){ if ( config.subtourModeChoice().considerCarAvailability() ) { @@ -190,7 +189,7 @@ private static void checkTravelTimeCalculatorConfigGroup( Config config, Level l } private static boolean checkStrategyConfigGroup( Config config, Level lvl, boolean problem ){ boolean found = false ; - Collection settingsColl = config.strategy().getStrategySettings(); + Collection settingsColl = config.replanning().getStrategySettings(); for ( StrategySettings settings : settingsColl ) { if ( settings.getStrategyName().equalsIgnoreCase("ChangeExpBeta") ) { found = true ; @@ -203,7 +202,7 @@ private static boolean checkStrategyConfigGroup( Config config, Level lvl, boole } // added may'16 - if ( config.strategy().getFractionOfIterationsToDisableInnovation()==Double.POSITIVE_INFINITY ) { + if ( config.replanning().getFractionOfIterationsToDisableInnovation()==Double.POSITIVE_INFINITY ) { problem = true ; System.out.flush() ; log.log( lvl, "You have not set fractionOfIterationsToDisableInnovation; vsp default is to set this to 0.8 or similar. Add the following config lines:" ) ; @@ -214,7 +213,7 @@ private static boolean checkStrategyConfigGroup( Config config, Level lvl, boole // added nov'15 boolean usingTimeMutator = false ; - for ( StrategySettings it : config.strategy().getStrategySettings() ) { + for ( StrategySettings it : config.replanning().getStrategySettings() ) { if ( DefaultStrategy.TimeAllocationMutator.equals( it.getName() ) ) { usingTimeMutator = true ; break ; @@ -244,7 +243,7 @@ private static boolean checkStrategyConfigGroup( Config config, Level lvl, boole // added jun'22 boolean usingSMC = false ; - for ( StrategySettings it : config.strategy().getStrategySettings() ) { + for ( StrategySettings it : config.replanning().getStrategySettings() ) { if ( DefaultStrategy.SubtourModeChoice.equals( it.getName() ) ) { usingSMC = true ; break ; @@ -340,7 +339,7 @@ private static boolean checkPlansConfigGroup( Config config, Level lvl, boolean } private static boolean checkPlanCalcScoreConfigGroup( Config config, Level lvl, boolean problem ){ // use beta_brain=1 // added as of nov'12 - if ( config.planCalcScore().getBrainExpBeta() != 1. ) { + if ( config.scoring().getBrainExpBeta() != 1. ) { problem = true ; System.out.flush() ; log.log( lvl, "You are using a brainExpBeta != 1; vsp default is 1. (Different values may cause conceptual " + @@ -351,14 +350,14 @@ private static boolean checkPlanCalcScoreConfigGroup( Config config, Level lvl, } // added aug'13: - if ( config.planCalcScore().getMarginalUtlOfWaiting_utils_hr() != 0. ) { + if ( config.scoring().getMarginalUtlOfWaiting_utils_hr() != 0. ) { problem = true ; System.out.flush() ; log.log( lvl, "found marginal utility of waiting != 0. vsp default is setting this to 0. " ) ; } - + // added apr'15: - for ( ActivityParams params : config.planCalcScore().getActivityParams() ) { + for ( ActivityParams params : config.scoring().getActivityParams() ) { if ( PtConstants.TRANSIT_ACTIVITY_TYPE.equals( params.getActivityType() ) ) { // they have typicalDurationScoreComputation==relative, but are not scored anyways. benjamin/kai, nov'15 continue ; @@ -374,7 +373,7 @@ private static boolean checkPlanCalcScoreConfigGroup( Config config, Level lvl, throw new RuntimeException("unexpected setting; aborting ... ") ; } } - for ( ModeParams params : config.planCalcScore().getModes().values() ) { + for ( ModeParams params : config.scoring().getModes().values() ) { if ( params.getMonetaryDistanceRate() > 0. ) { problem = true ; System.out.flush() ; @@ -386,28 +385,28 @@ private static boolean checkPlanCalcScoreConfigGroup( Config config, Level lvl, } } - if ( config.planCalcScore().getModes().get(TransportMode.car ) != null && config.planCalcScore().getModes().get(TransportMode.car ).getMonetaryDistanceRate() > 0 ) { + if ( config.scoring().getModes().get(TransportMode.car ) != null && config.scoring().getModes().get(TransportMode.car ).getMonetaryDistanceRate() > 0 ) { problem = true ; } - final ModeParams modeParamsPt = config.planCalcScore().getModes().get(TransportMode.pt ); + final ModeParams modeParamsPt = config.scoring().getModes().get(TransportMode.pt ); if ( modeParamsPt!=null && modeParamsPt.getMonetaryDistanceRate() > 0 ) { problem = true ; System.out.flush() ; log.error("found monetary distance rate pt > 0. You probably want a value < 0 here." ) ; } - if ( config.planCalcScore().getMarginalUtilityOfMoney() < 0. ) { + if ( config.scoring().getMarginalUtilityOfMoney() < 0. ) { problem = true ; System.out.flush() ; log.error("found marginal utility of money < 0. You almost certainly want a value > 0 here. " ) ; } // added feb'16 - if ( config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none ) ) { + if ( config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none ) ) { log.log( lvl, "found `PlansCalcRouteConfigGroup.AccessEgressType.none'; vsp should use `accessEgressModeToLink' or " + "some other value or talk to Kai." ) ; } // added oct'17: - if ( config.planCalcScore().getFractionOfIterationsToStartScoreMSA() == null || config.planCalcScore().getFractionOfIterationsToStartScoreMSA() >= 1. ) { + if ( config.scoring().getFractionOfIterationsToStartScoreMSA() == null || config.scoring().getFractionOfIterationsToStartScoreMSA() >= 1. ) { problem = true ; System.out.flush() ; log.log( lvl, "You are not setting fractionOfIterationsToStartScoreMSA; vsp default is to set this to something like 0.8. " + @@ -418,7 +417,7 @@ private static boolean checkPlanCalcScoreConfigGroup( Config config, Level lvl, } // added apr'21: - for( Map.Entry entry : config.planCalcScore().getScoringParametersPerSubpopulation().entrySet() ){ + for( Map.Entry entry : config.scoring().getScoringParametersPerSubpopulation().entrySet() ){ for( ActivityParams activityParam : entry.getValue().getActivityParams() ){ if( activityParam.getMinimalDuration().isDefined() ){ log.log( lvl, "Vsp default is to not define minimal duration. Activity type=" + activityParam.getActivityType() + "; subpopulation=" + entry.getKey() ); @@ -427,7 +426,7 @@ private static boolean checkPlanCalcScoreConfigGroup( Config config, Level lvl, } // added may'23 - for ( ModeParams params : config.planCalcScore().getModes().values() ){ + for ( ModeParams params : config.scoring().getModes().values() ){ if ( config.vspExperimental().getCheckingOfMarginalUtilityOfTravellng()== CheckingOfMarginalUtilityOfTravellng.allZero ){ if( params.getMarginalUtilityOfTraveling() != 0. ){ log.log( lvl, "You are setting the marginal utility of traveling with mode " + params.getMode() + " to " + params.getMarginalUtilityOfTraveling() @@ -479,7 +478,7 @@ private static boolean checkFacilitiesConfigGroup( Config config, Level lvl, boo return problem; } private static boolean checkControlerConfigGroup( Config config, Level lvl, boolean problem ){ - Set formats = config.controler().getEventsFileFormats(); + Set formats = config.controller().getEventsFileFormats(); if ( !formats.contains( EventsFileFormat.xml ) ) { problem = true ; System.out.flush() ; @@ -487,11 +486,9 @@ private static boolean checkControlerConfigGroup( Config config, Level lvl, bool } // may'21 - switch ( config.controler().getRoutingAlgorithmType() ) { + switch ( config.controller().getRoutingAlgorithmType() ) { case Dijkstra: case AStarLandmarks: - case FastDijkstra: - case FastAStarLandmarks: log.log( lvl, "you are not using SpeedyALT as routing algorithm. vsp default (since may'21) is to use SpeedeALT.") ; System.out.flush(); break; diff --git a/matsim/src/main/java/org/matsim/core/config/groups/ControlerConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/ControllerConfigGroup.java similarity index 95% rename from matsim/src/main/java/org/matsim/core/config/groups/ControlerConfigGroup.java rename to matsim/src/main/java/org/matsim/core/config/groups/ControllerConfigGroup.java index 343dda723fd..f1d8bae8b6a 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/ControlerConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/ControllerConfigGroup.java @@ -31,13 +31,13 @@ import java.util.*; -public final class ControlerConfigGroup extends ReflectiveConfigGroup { - private static final Logger log = LogManager.getLogger( ControlerConfigGroup.class ); +public final class ControllerConfigGroup extends ReflectiveConfigGroup { + private static final Logger log = LogManager.getLogger( ControllerConfigGroup.class ); + + public enum RoutingAlgorithmType {Dijkstra, AStarLandmarks, SpeedyALT} - public enum RoutingAlgorithmType {Dijkstra, AStarLandmarks, FastDijkstra, FastAStarLandmarks, SpeedyALT} - public enum EventTypeToCreateScoringFunctions {IterationStarts, BeforeMobsim} - + public enum EventsFileFormat {xml, pb, json} public enum CompressionType { @@ -58,7 +58,7 @@ public enum CleanIterations { delete, } - public static final String GROUP_NAME = "controler"; + public static final String GROUP_NAME = "controller"; private static final String OUTPUT_DIRECTORY = "outputDirectory"; private static final String FIRST_ITERATION = "firstIteration"; @@ -77,7 +77,7 @@ public enum CleanIterations { private static final String CLEAN_ITERS_AT_END = "cleanItersAtEnd"; private static final String COMPRESSION_TYPE = "compressionType"; private static final String EVENT_TYPE_TO_CREATE_SCORING_FUNCTIONS = "createScoringFunctionType"; - + /*package*/ static final String MOBSIM = "mobsim"; public enum MobsimType {qsim, JDEQSim, hermes} @@ -87,9 +87,9 @@ public enum MobsimType {qsim, JDEQSim, hermes} private String outputDirectory = "./output"; private int firstIteration = 0; private int lastIteration = 1000; - private RoutingAlgorithmType routingAlgorithmType = RoutingAlgorithmType.AStarLandmarks; + private RoutingAlgorithmType routingAlgorithmType = RoutingAlgorithmType.SpeedyALT; private EventTypeToCreateScoringFunctions eventTypeToCreateScoringFunctions = EventTypeToCreateScoringFunctions.IterationStarts; - + private boolean linkToLinkRoutingEnabled = false; private String runId = null; @@ -109,7 +109,7 @@ public enum MobsimType {qsim, JDEQSim, hermes} private CleanIterations cleanItersAtEnd = CleanIterations.keep; - public ControlerConfigGroup() { + public ControllerConfigGroup() { super(GROUP_NAME); } @@ -127,7 +127,7 @@ public final Map getComments() { map.put(WRITE_PLANS_INTERVAL, "iterationNumber % writePlansInterval == 0 defines (hopefully) in which iterations plans are " + "written to a file. `0' disables plans writing completely. Some plans in early iterations are always written"); map.put(LINKTOLINK_ROUTING_ENABLED, "Default=false. If enabled, the router takes travel times needed for turning moves into account." - + " Cannot be used if the (Fast)AStarLandmarks routing or TravelTimeCalculator.separateModes is enabled."); + + " Can only be used with Dijkstra routing. Cannot be used when TravelTimeCalculator.separateModes is enabled."); map.put(FIRST_ITERATION, "Default=0. First Iteration of a simulation."); map.put(LAST_ITERATION, "Default=1000. Last Iteration of a simulation."); @@ -136,16 +136,11 @@ public final Map getComments() { " but add a significant overhead in smaller runs or in test cases where the graphical output is not even requested." ); map.put(COMPRESSION_TYPE, "Compression algorithm to use when writing out data to files. Possible values: " + Arrays.toString(CompressionType.values())); map.put(EVENT_TYPE_TO_CREATE_SCORING_FUNCTIONS, "Defines when the scoring functions for the population are created. Default=IterationStarts. Possible values: " + Arrays.toString(EventTypeToCreateScoringFunctions.values())); - - StringBuilder mobsimTypes = new StringBuilder(); - for ( MobsimType mtype : MobsimType.values() ) { - mobsimTypes.append(mtype.toString()); - mobsimTypes.append(' '); - } - map.put(MOBSIM, "Defines which mobility simulation will be used. Currently supported: " + mobsimTypes + IOUtils.NATIVE_NEWLINE + "\t\t" + + + map.put(MOBSIM, "Defines which mobility simulation will be used. Currently supported: " + Arrays.toString(MobsimType.values()) + IOUtils.NATIVE_NEWLINE + "\t\t" + "Depending on the chosen mobsim, you'll have to add additional config modules to configure the corresponding mobsim." + IOUtils.NATIVE_NEWLINE + "\t\t" + "For 'qsim', add a module 'qsim' to the config."); - + map.put(SNAPSHOT_FORMAT, "Comma-separated list of visualizer output file formats. `transims' and `otfvis'."); map.put(WRITE_SNAPSHOTS_INTERVAL, "iterationNumber % " + WRITE_SNAPSHOTS_INTERVAL + " == 0 defines in which iterations snapshots are written " + "to a file. `0' disables snapshots writing completely"); @@ -347,12 +342,12 @@ public int getWritePlansInterval() { public void setWritePlansInterval(final int writePlansInterval) { this.writePlansInterval = writePlansInterval; } - + @StringGetter( WRITE_SNAPSHOTS_INTERVAL ) public int getWriteSnapshotsInterval() { return writeSnapshotsInterval; } - + @StringSetter( WRITE_SNAPSHOTS_INTERVAL ) public void setWriteSnapshotsInterval(int writeSnapshotsInterval) { this.writeSnapshotsInterval = writeSnapshotsInterval; @@ -433,9 +428,9 @@ public int getWriteEventsUntilIteration() { public void setWriteEventsUntilIteration(int val) { this.writeEventsUntilIteration = val ; } - @Override + @Override protected void checkConsistency(Config config) { - if ( config.controler().getOverwriteFileSetting() == OverwriteFileSetting.overwriteExistingFiles ) { + if ( config.controller().getOverwriteFileSetting() == OverwriteFileSetting.overwriteExistingFiles ) { log.warn( "setting overwriting behavior to "+overwriteFileSetting ); log.warn( "this is not recommended, as it might result in a directory containing output from several model runs" ); log.warn( "prefer the options "+OverwriteFileSetting.deleteDirectoryIfExists+" or "+OverwriteFileSetting.failIfDirectoryExists ); diff --git a/matsim/src/main/java/org/matsim/core/config/groups/ParallelEventHandlingConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/EventsManagerConfigGroup.java similarity index 95% rename from matsim/src/main/java/org/matsim/core/config/groups/ParallelEventHandlingConfigGroup.java rename to matsim/src/main/java/org/matsim/core/config/groups/EventsManagerConfigGroup.java index 3d38075a498..07a5f6c8469 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/ParallelEventHandlingConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/EventsManagerConfigGroup.java @@ -28,9 +28,9 @@ * @author nagel * */ -public final class ParallelEventHandlingConfigGroup extends ReflectiveConfigGroup { +public final class EventsManagerConfigGroup extends ReflectiveConfigGroup { - public static final String GROUP_NAME = "parallelEventHandling"; + public static final String GROUP_NAME = "eventsManager"; private final static String NUMBER_OF_THREADS = "numberOfThreads"; private Integer numberOfThreads = null; @@ -39,10 +39,10 @@ public final class ParallelEventHandlingConfigGroup extends ReflectiveConfigGrou private final static String ESTIMATED_NUMBER_OF_EVENTS = "estimatedNumberOfEvents"; private Long estimatedNumberOfEvents = null; - private final static String SYNCHRONIZE_ON_SIMSTEPS = "synchronizeOnSimSteps"; + private final static String SYNCHRONIZE_ON_SIMSTEPS = "synchronizeOnSimSteps"; private Boolean synchronizeOnSimSteps = true; - - private final static String ONE_THREAD_PER_HANDLER = "oneThreadPerHandler"; + + private final static String ONE_THREAD_PER_HANDLER = "oneThreadPerHandler"; private Boolean oneThreadPerHandler = false; private final static String EVENTS_QUEUE_SIZE = "eventsQueueSize"; @@ -53,7 +53,7 @@ public final class ParallelEventHandlingConfigGroup extends ReflectiveConfigGrou private boolean locked = false; - public ParallelEventHandlingConfigGroup() { + public EventsManagerConfigGroup() { super(GROUP_NAME); } @@ -80,7 +80,7 @@ public Integer getNumberOfThreads() { /** * {@value #NUMBER_OF_THREADS_COMMENT} - * + * * @param numberOfThreads */ @StringSetter( NUMBER_OF_THREADS ) @@ -143,8 +143,8 @@ public void setOneThreadPerHandler(Boolean oneThreadPerHandler) { throw new RuntimeException("it is too late in the control flow to modify this parameter"); } } - + public void makeLocked() { this.locked = true; } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataArrayFactory.java b/matsim/src/main/java/org/matsim/core/config/groups/PlanInheritanceConfigGroup.java similarity index 59% rename from matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataArrayFactory.java rename to matsim/src/main/java/org/matsim/core/config/groups/PlanInheritanceConfigGroup.java index db9b07a578c..b889df2fa15 100644 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataArrayFactory.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/PlanInheritanceConfigGroup.java @@ -1,10 +1,9 @@ /* *********************************************************************** * * project: org.matsim.* - * TravelTimeDataArrayFactory.java * * * *********************************************************************** * * * - * copyright : (C) 2009 by the members listed in the COPYING, * + * copyright : (C) 2011 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * @@ -18,25 +17,43 @@ * * * *********************************************************************** */ -package org.matsim.core.trafficmonitoring; +package org.matsim.core.config.groups; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; +import java.util.Map; -class TravelTimeDataArrayFactory implements TravelTimeDataFactory { +import org.matsim.core.config.ReflectiveConfigGroup; - private final Network network; - private final int numSlots; - - public TravelTimeDataArrayFactory(final Network network, final int numSlots) { - this.network = network; - this.numSlots = numSlots; +/** + * @author awagner + */ +public final class PlanInheritanceConfigGroup extends ReflectiveConfigGroup { + + public static final String GROUP_NAME = "planInheritance"; + + private static final String ENABLED = "enabled"; + + private boolean enabled = false; + + public PlanInheritanceConfigGroup() { + super(GROUP_NAME); } - + @Override - public TravelTimeData createTravelTimeData(Id linkId) { - return new TravelTimeDataArray(this.network.getLinks().get(linkId), this.numSlots); + public Map getComments() { + Map comments = super.getComments(); + comments.put(ENABLED, "Specifies whether or not PlanInheritance Information should be tracked."); + return comments; } + + @StringSetter( ENABLED ) + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + + @StringGetter( ENABLED ) + public boolean getEnabled() { + return this.enabled; + } } diff --git a/matsim/src/main/java/org/matsim/core/config/groups/StrategyConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/ReplanningConfigGroup.java similarity index 98% rename from matsim/src/main/java/org/matsim/core/config/groups/StrategyConfigGroup.java rename to matsim/src/main/java/org/matsim/core/config/groups/ReplanningConfigGroup.java index 8f2d2f8c8fb..4a9b0de4f20 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/StrategyConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/ReplanningConfigGroup.java @@ -41,10 +41,10 @@ * * @author mrieser */ -public final class StrategyConfigGroup extends ConfigGroup { +public final class ReplanningConfigGroup extends ConfigGroup { + + public static final String GROUP_NAME = "replanning"; - public static final String GROUP_NAME = "strategy"; - // in the following, it is still named "module", for the following reason: // the "right" side is the outside interface, used in the config files, which is left with the old keys for backwards compatibility. // kai/mz, dec'14 @@ -58,7 +58,7 @@ public final class StrategyConfigGroup extends ConfigGroup { // yy could you please describe why this indirect design was done? Was ist just because it made refactoring easier, or does it provide // an advantage or is even necessary? Thanks ... kai, oct'14 // To maintain backwards compatibility (underscored parameters), one needs to override the "getValue" and "add_param" methods, - // which are final in ReflectiveModule. However, using reflective module for the + // which are final in ReflectiveModule. However, using reflective module for the // rest of the parameters still made refactoring much easier. So let's call // this "necessary". td, apr'15 @@ -82,14 +82,14 @@ public StrategySettings(final Id id) { // this.strategyName = id.toString() ; // safety net, can be overridden by (also deprecated) setStrategyName(...). kai/mz, nov'15 // putting the above into the code fails at least one test. We would vote for removing that test ... } - + @Override public final Map getComments() { Map map = super.getComments(); // put comments only for the first strategy to improve readability // I think that the above comment is a todo, not a description of the code status. kai, feb'15 - + StringBuilder sels = new StringBuilder() ; sels.append( DefaultSelector.SelectRandom ) ; sels.append( ' ' ); @@ -102,7 +102,7 @@ public final Map getComments() { sels.append( DefaultSelector.SelectExpBeta ) ; sels.append( ' ' ); sels.append( DefaultSelector.SelectPathSizeLogit ) ; - + StringBuilder strats = new StringBuilder() ; strats.append( DefaultStrategy.ReRoute ) ; sels.append( ' ' ); @@ -115,7 +115,7 @@ public final Map getComments() { strats.append( DefaultStrategy.ChangeTripMode ) ; sels.append( ' ' ); strats.append( DefaultStrategy.SubtourModeChoice ) ; - + map.put( "strategyName", "strategyName of strategy. Possible default names: " + sels + " (selectors), " + strats + " (innovative strategies)." ); map.put( "weight", @@ -139,7 +139,7 @@ protected void checkConsistency(Config config) { throw new RuntimeException("Strategy strategyName is not set"); } if ( getWeight() < 0.0 ) { - throw new RuntimeException("Weight for strategy " + getStrategyName() + " must be >= 0.0" ); + throw new RuntimeException("Weight for strategy " + getStrategyName() + " must be >= 0.0" ); } } @@ -204,7 +204,7 @@ public String getSubpopulation() { } } - public StrategyConfigGroup() { + public ReplanningConfigGroup() { super(GROUP_NAME); } @@ -286,7 +286,7 @@ public final Map getComments() { + "Possible defaults: " + strb.toString() + ". The current default, WorstPlanSelector is not a good " + "choice from a discrete choice theoretical perspective. Alternatives, however, have not been systematically " + "tested. kai, feb'12") ; - + map.put(ReflectiveDelegate.EXTERNAL_EXE_CONFIG_TEMPLATE,"the external executable will be called with a config file as argument. This is the pathname to a possible " + "skeleton config, to which additional information will be added. Can be null."); map.put(ReflectiveDelegate.EXTERNAL_EXE_TMP_FILE_ROOT_DIR, "root directory for temporary files generated by the external executable. Provided as a service; " @@ -328,7 +328,7 @@ public ConfigGroup createParameterSet(final String type) { public void addStrategySettings(final StrategySettings stratSets) { addParameterSet( stratSets ); } - + public final void clearStrategySettings() { this.clearParameterSetsForType( StrategySettings.SET_NAME ) ; } @@ -391,7 +391,7 @@ public void setPlanSelectorForRemoval(String planSelectorForRemoval) { throw new RuntimeException("'ChangeExpBeta' was replaced by 'ChangeExpBetaForRemoval' in the plans removal setting" ) ; case "PathSizeLogitSelector" : throw new RuntimeException("'PathSizeLogitSelector' was replaced by 'PathSizeLogitSelectorForRemoval' in the plans removal setting" ) ; - default: + default: delegate.setPlanSelectorForRemoval(planSelectorForRemoval) ; } } @@ -423,13 +423,13 @@ private static class ReflectiveDelegate extends ReflectiveConfigGroup { private long externalExeTimeOut = 3600; private String planSelectorForRemoval = "WorstPlanSelector"; - + //--- private double fraction = Double.POSITIVE_INFINITY ; //--- public ReflectiveDelegate() { - super( StrategyConfigGroup.GROUP_NAME ); + super( ReplanningConfigGroup.GROUP_NAME ); } diff --git a/matsim/src/main/java/org/matsim/core/config/groups/PlansCalcRouteConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/RoutingConfigGroup.java similarity index 98% rename from matsim/src/main/java/org/matsim/core/config/groups/PlansCalcRouteConfigGroup.java rename to matsim/src/main/java/org/matsim/core/config/groups/RoutingConfigGroup.java index 638c1883455..a693d0c0297 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/PlansCalcRouteConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/RoutingConfigGroup.java @@ -40,12 +40,12 @@ * @author dgrether * @author mrieser */ -public final class PlansCalcRouteConfigGroup extends ConfigGroup { +public final class RoutingConfigGroup extends ConfigGroup { // yy There is a certain degree of messiness in this class because of retrofitting, e.g. making beelineDistance mode-specific while // being backwards compatible. This could eventually be cleaned up, maybe about a year after introducing it. kai, jun'15 - - public static final String GROUP_NAME = "planscalcroute"; - + + public static final String GROUP_NAME = "routing"; + private static final String BEELINE_DISTANCE_FACTOR = "beelineDistanceFactor"; private static final String NETWORK_MODES = "networkModes"; private static final String TELEPORTED_MODE_SPEEDS = "teleportedModeSpeed_"; @@ -53,7 +53,7 @@ public final class PlansCalcRouteConfigGroup extends ConfigGroup { public static final String UNDEFINED = "undefined"; - + // For config file backward compatibility. // These are just hardcoded versions of the options above. private static final String PT_SPEED_FACTOR = "ptSpeedFactor"; @@ -61,13 +61,13 @@ public final class PlansCalcRouteConfigGroup extends ConfigGroup { private static final String WALK_SPEED = "walkSpeed"; private static final String BIKE_SPEED = "bikeSpeed"; private static final String UNDEFINED_MODE_SPEED = "undefinedModeSpeed"; - - private static final Logger log = LogManager.getLogger(PlansCalcRouteConfigGroup.class) ; - + + private static final Logger log = LogManager.getLogger(RoutingConfigGroup.class) ; + private Collection networkModes = Collections.singletonList( TransportMode.car ); private boolean acceptModeParamsWithoutClearing; - + private Double beelineDistanceFactor = 1.3 ; public enum AccessEgressType { @@ -138,13 +138,13 @@ public static class TeleportedModeParams extends ReflectiveConfigGroup implement public static final String SET_TYPE = "teleportedModeParameters"; public static final String MODE = "mode"; public static final String TELEPORTED_MODE_FREESPEED_FACTOR = "teleportedModeFreespeedFactor"; - + private String mode = null; // beeline teleportation: private Double teleportedModeSpeed = null; private Double beelineDistanceFactorForMode = null ; - + // route computed on network: private Double teleportedModeFreespeedFactor = null; private Double teleportedModeFreespeedLimit = Double.POSITIVE_INFINITY ; @@ -153,7 +153,7 @@ public static class TeleportedModeParams extends ReflectiveConfigGroup implement "Travel time = teleportedModeFreespeedFactor * . Insert a line like this for every such mode. " + "Please do not set teleportedModeFreespeedFactor as well as teleportedModeSpeed for the same mode, but if you do, +" + "teleportedModeFreespeedFactor wins over teleportedModeSpeed."; - + private static final String TELEPORTED_MODE_FREESPEED_LIMIT_CMT = "When using freespeed factor, a speed limit on the free speed. " + "Link travel time will be $= factor * [ min( link_freespeed, freespeed_limit) ]" ; @@ -194,7 +194,7 @@ public Map getComments() { /** * Currently not in xml interface. - * + * * @return teleportedModeFreespeedLimit -- {@value #TELEPORTED_MODE_FREESPEED_LIMIT_CMT} */ public final Double getTeleportedModeFreespeedLimit() { @@ -203,7 +203,7 @@ public final Double getTeleportedModeFreespeedLimit() { /** * Currently not in xml interface. - * + * * @param teleportedModeFreespeedLimit -- {@value #TELEPORTED_MODE_FREESPEED_LIMIT_CMT} */ public TeleportedModeParams setTeleportedModeFreespeedLimit( Double teleportedModeFreespeedLimit ) { @@ -237,7 +237,7 @@ public TeleportedModeParams setTeleportedModeSpeed( Double teleportedModeSpeed ) this.teleportedModeSpeed = teleportedModeSpeed; return this; } - + /** * @return {@value #TELEPORTED_MODE_FREESPEED_FACTOR_CMT} */ @@ -245,7 +245,7 @@ public TeleportedModeParams setTeleportedModeSpeed( Double teleportedModeSpeed ) public Double getTeleportedModeFreespeedFactor() { return teleportedModeFreespeedFactor; } - + /** * @param teleportedModeFreespeedFactor -- {@value #TELEPORTED_MODE_FREESPEED_FACTOR_CMT} */ @@ -259,7 +259,7 @@ public TeleportedModeParams setTeleportedModeFreespeedFactor( this.teleportedModeFreespeedFactor = teleportedModeFreespeedFactor; return this; } - + @StringSetter("beelineDistanceFactor") public TeleportedModeParams setBeelineDistanceFactor( Double val ) { testForLocked() ; @@ -270,10 +270,10 @@ public TeleportedModeParams setBeelineDistanceFactor( Double val ) { public Double getBeelineDistanceFactor() { return this.beelineDistanceFactorForMode ; } - + } - - public PlansCalcRouteConfigGroup() { + + public RoutingConfigGroup() { super(GROUP_NAME); acceptModeParamsWithoutClearing = true; @@ -288,7 +288,7 @@ public PlansCalcRouteConfigGroup() { walk.setTeleportedModeSpeed( 3.0 / 3.6 ); // 3.0 km/h --> m/s addParameterSet( walk ); } - + // the following two are deliberately different from "walk" since "walk" may become a network routing mode, but these two // will not. kai, dec'15 { @@ -333,7 +333,7 @@ public PlansCalcRouteConfigGroup() { // addParameterSet( transit_walk ); // } // one might add the above but it was not added in the original design. Not sure about the reason. kai, feb'15 - + this.acceptModeParamsWithoutClearing = false; } @@ -461,7 +461,7 @@ public Map getModeRoutingParams() { for ( ConfigGroup pars : getParameterSets( TeleportedModeParams.SET_TYPE ) ) { if ( this.isLocked() ) { - pars.setLocked(); + pars.setLocked(); } final String mode = ((TeleportedModeParams) pars).getMode(); final TeleportedModeParams old = map.put( mode , (TeleportedModeParams) pars ); @@ -480,7 +480,7 @@ public TeleportedModeParams getOrCreateModeRoutingParams( final String mode ) { addParameterSet( pars ); } if ( this.isLocked() ) { - pars.setLocked(); + pars.setLocked(); } return pars; @@ -562,7 +562,7 @@ public Map getTeleportedModeSpeeds() { final Map map = new LinkedHashMap< >(); for ( TeleportedModeParams pars : getModeRoutingParams().values() ) { if ( this.isLocked() ) { - pars.setLocked(); + pars.setLocked(); } final Double speed = pars.getTeleportedModeSpeed(); @@ -575,7 +575,7 @@ public Map getTeleportedModeFreespeedFactors() { final Map map = new LinkedHashMap< >(); for ( TeleportedModeParams pars : getModeRoutingParams().values() ) { if ( this.isLocked() ) { - pars.setLocked(); + pars.setLocked(); } final Double speed = pars.getTeleportedModeFreespeedFactor(); @@ -583,12 +583,12 @@ public Map getTeleportedModeFreespeedFactors() { } return map; } - + public Map getBeelineDistanceFactors() { final Map map = new LinkedHashMap<>() ; for ( TeleportedModeParams pars : getModeRoutingParams().values() ) { if ( this.isLocked() ) { - pars.setLocked(); + pars.setLocked(); } final Double val = pars.getBeelineDistanceFactor() ; @@ -614,16 +614,16 @@ public void setTeleportedModeSpeed(String mode, double speed) { pars.setTeleportedModeSpeed( speed ); addParameterSet( pars ); } - + @Deprecated // use mode-specific beeline distance factors! kai, apr'15 public void setBeelineDistanceFactor(double val) { testForLocked() ; // yyyy thinking about this: this should in design maybe not be different from the other teleportation factors (reset everything // if one is set; or possibly disallow setting it at all). kai, feb'15 - + // memorize the global factor for ModeRoutingParams that are added later: this.beelineDistanceFactor = val ; - + // push the global factor to the local ones for all ModeRoutingParams that are already there: for ( TeleportedModeParams params : this.getModeRoutingParams().values() ) { params.setBeelineDistanceFactor( val ); diff --git a/matsim/src/main/java/org/matsim/core/config/groups/PlanCalcScoreConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/ScoringConfigGroup.java similarity index 98% rename from matsim/src/main/java/org/matsim/core/config/groups/PlanCalcScoreConfigGroup.java rename to matsim/src/main/java/org/matsim/core/config/groups/ScoringConfigGroup.java index 973bb8890bc..2f7955e23fc 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/PlanCalcScoreConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/ScoringConfigGroup.java @@ -52,19 +52,19 @@ *
    • The parameter names in the config file are not changed in this way * since this would mean a public api change. kai, dec'10 *
    - * + * * @author nagel * */ -public final class PlanCalcScoreConfigGroup extends ConfigGroup { +public final class ScoringConfigGroup extends ConfigGroup { - private static final Logger log = LogManager.getLogger(PlanCalcScoreConfigGroup.class); + private static final Logger log = LogManager.getLogger(ScoringConfigGroup.class); - public static final String GROUP_NAME = "planCalcScore"; + public static final String GROUP_NAME = "scoring"; private static final String LEARNING_RATE = "learningRate"; - private static final String BRAIN_EXP_BETA = "BrainExpBeta"; - private static final String PATH_SIZE_LOGIT_BETA = "PathSizeLogitBeta"; + private static final String BRAIN_EXP_BETA = "brainExpBeta"; + private static final String PATH_SIZE_LOGIT_BETA = "pathSizeLogitBeta"; private static final String LATE_ARRIVAL = "lateArrival"; private static final String EARLY_DEPARTURE = "earlyDeparture"; private static final String PERFORMING = "performing"; @@ -79,10 +79,10 @@ public final class PlanCalcScoreConfigGroup extends ConfigGroup { private static final String UTL_OF_LINE_SWITCH = "utilityOfLineSwitch"; private final ReflectiveDelegate delegate = new ReflectiveDelegate(); - + private boolean usesDeprecatedSyntax = false ; - public PlanCalcScoreConfigGroup() { + public ScoringConfigGroup() { super(GROUP_NAME); this.addScoringParameters(new ScoringParameterSet()); @@ -177,13 +177,13 @@ public static String createStageActivityType( String mode ){ public String getValue(final String key) { throw new IllegalArgumentException(key + ": getValue access disabled; use direct getter"); } - + private static final String msg = " is deprecated config syntax; please use the more " + "modern hierarchical format; your output_config.xml " + "will be in the correct version; the old version will fail eventually, since we want to reduce the " + "workload on this backwards compatibility (look into " + "PlanCalcScoreConfigGroup or PlanCalcRouteConfigGroup if you want to know what we mean)."; - + @Override public void addParam(final String key, final String value) { testForLocked(); @@ -198,7 +198,7 @@ public void addParam(final String key, final String value) { else if (key.startsWith("activityType_")) { log.warn( key + msg ); usesDeprecatedSyntax = true ; - + ActivityParams actParams = getActivityTypeByNumber(key.substring("activityType_".length())); actParams.setActivityType(value); @@ -348,7 +348,7 @@ else if (Arrays // log.warn( key + msg ); // usesDeprecatedSyntax = true ; // this is the stuff with the default subpopulation - + getScoringParameters(null).addParam(key, value); } @@ -420,7 +420,7 @@ public final Map getComments() { return map; } - + /* * * @returns a list of all Activities over all Subpopulations (if existent) @@ -442,15 +442,15 @@ public Collection getActivityTypes() { public Collection getAllModes() { if (getScoringParameters(null) != null) { return getScoringParameters(null).getModes().keySet(); - + } else { Set modes = new HashSet<>(); getScoringParametersPerSubpopulation().values().forEach(item -> modes.addAll(item.getModes().keySet())); return modes; } - + } - + public Collection getActivityParams() { if (getScoringParameters(null) != null) return getScoringParameters(null).getActivityParams(); @@ -469,8 +469,8 @@ else if (getScoringParameters(DEFAULT_SUBPOPULATION) != null) throw new RuntimeException("Default subpopulation is not defined"); } - - + + public Map getScoringParametersPerSubpopulation() { @SuppressWarnings("unchecked") final Collection parameters = (Collection) getParameterSets( @@ -609,14 +609,14 @@ protected void checkParameterSet(final ConfigGroup module) { @Override protected final void checkConsistency(final Config config) { super.checkConsistency(config); - + if ( usesDeprecatedSyntax && !config.global().isInsistingOnDeprecatedConfigVersion() ) { throw new RuntimeException( msg ) ; } - + if (getScoringParametersPerSubpopulation().size()>1){ - if (!getScoringParametersPerSubpopulation().containsKey(PlanCalcScoreConfigGroup.DEFAULT_SUBPOPULATION)){ - throw new RuntimeException("Using several subpopulations in "+PlanCalcScoreConfigGroup.GROUP_NAME+" requires defining a \""+PlanCalcScoreConfigGroup.DEFAULT_SUBPOPULATION+" \" subpopulation." + if (!getScoringParametersPerSubpopulation().containsKey(ScoringConfigGroup.DEFAULT_SUBPOPULATION)){ + throw new RuntimeException("Using several subpopulations in "+ ScoringConfigGroup.GROUP_NAME+" requires defining a \""+ ScoringConfigGroup.DEFAULT_SUBPOPULATION+" \" subpopulation." + " Otherwise, crashes can be expected."); } } @@ -633,7 +633,7 @@ protected final void checkConsistency(final Config config) { for (ScoringParameterSet scoringParameterSet : this.getScoringParametersPerSubpopulation().values()) { - for (String mode : config.plansCalcRoute().getNetworkModes()) { + for (String mode : config.routing().getNetworkModes()) { createAndAddInteractionActivity( scoringParameterSet, mode ); } // (In principle, the for loop following next should be sufficient, i.e. taking the necessary modes from scoring. @@ -819,7 +819,7 @@ public static class ActivityParams extends ReflectiveConfigGroup implements Mats // ActivityParams. I will try to pass the locked setting through the getters. kai, jun'15 public final static String SET_TYPE = "activityParams"; - + // --- private static final String TYPICAL_DURATION_SCORE_COMPUTATION = "typicalDurationScoreComputation"; @@ -1070,7 +1070,7 @@ public ActivityParams setClosingTime(final double closingTime) { } // --- - + static final String SCORING_THIS_ACTIVITY_AT_ALL = "scoringThisActivityAtAll"; private boolean scoringThisActivityAtAll = true; @@ -1091,7 +1091,7 @@ public ActivityParams setScoringThisActivityAtAll(boolean scoringThisActivityAtA public static class ModeParams extends ReflectiveConfigGroup implements MatsimParameters { final static String SET_TYPE = "modeParams"; - + private static final String MONETARY_DISTANCE_RATE = "monetaryDistanceRate"; private static final String MONETARY_DISTANCE_RATE_CMT = "[unit_of_money/m] conversion of distance into money. Normally negative."; @@ -1101,12 +1101,12 @@ public static class ModeParams extends ReflectiveConfigGroup implements MatsimPa private static final String CONSTANT_CMT = "[utils] alternative-specific constant. Normally per trip, but that is probably buggy for multi-leg trips."; public static final String MODE = "mode"; - + private static final String DAILY_MONETARY_CONSTANT = "dailyMonetaryConstant"; private static final String DAILY_MONETARY_CONSTANT_CMT = "[unit_of_money/day] Fixed cost of mode, per day."; private static final String DAILY_UTILITY_CONSTANT = "dailyUtilityConstant"; - + private String mode = null; private double traveling = -6.0; private double distance = 0.0; @@ -1524,12 +1524,12 @@ public void addActivityParams(final ActivityParams params) { @Override public void checkConsistency(Config config) { super.checkConsistency(config); - - + + boolean hasOpeningAndClosingTime = false; boolean hasOpeningTimeAndLatePenalty = false; - + // This cannot be done in ActivityParams (where it would make more // sense), // because some global properties are also checked @@ -1572,7 +1572,7 @@ public void checkConsistency(Config config) { private static class ReflectiveDelegate extends ReflectiveConfigGroup { private ReflectiveDelegate() { - super(PlanCalcScoreConfigGroup.GROUP_NAME); + super(ScoringConfigGroup.GROUP_NAME); } private double learningRate = 1.0; diff --git a/matsim/src/main/java/org/matsim/core/config/groups/TimeAllocationMutatorConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/TimeAllocationMutatorConfigGroup.java index 822763c7683..1a4b33e942e 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/TimeAllocationMutatorConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/TimeAllocationMutatorConfigGroup.java @@ -25,11 +25,13 @@ import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ReflectiveConfigGroup; +import org.matsim.core.utils.misc.Time; public final class TimeAllocationMutatorConfigGroup extends ReflectiveConfigGroup { - public static final String GROUP_NAME = "TimeAllocationMutator"; - + public static final String GROUP_NAME = "timeAllocationMutator"; + + public TimeAllocationMutatorConfigGroup() { super(GROUP_NAME); } @@ -39,15 +41,49 @@ public Map getComments() { Map comments = super.getComments(); comments.put(MUTATION_RANGE, "Default:1800.0; Defines how many seconds a time mutation can maximally shift a time."); comments.put(MUTATION_AFFECTS_DURATION, "Default:true; Defines whether time mutation changes an activity's duration."); - comments.put(USE_INDIVIDUAL_SETTINGS_FOR_SUBPOPULATIONS, "false; Use individual settings for each subpopulation. " - + "If enabled but no settings are found, regular settings are uses as fallback."); + comments.put(LATEST_ACTIVITY_END_TIME,"Latest Activity End Time. Default = 24:00:00"); + comments.put(MUTATION_RANGE_STEP,"Mutation Range Step, default = 1 second"); + comments.put(MUTATE_AROUND_INITIAL_END_TIME_ONLY,"Mutates times only around the initially defined end times."); return comments; } - + // --- + private static final String LATEST_ACTIVITY_END_TIME = "latestActivityEndTime"; + private static final String MUTATE_AROUND_INITIAL_END_TIME_ONLY = "mutateAroundInitialEndTimeOnly"; + private static final String MUTATION_RANGE_STEP = "mutationRangeStep"; private static final String MUTATION_RANGE = "mutationRange"; private double mutationRange = 1800.0; + private double latestActivityEndTime = 24*3600.0; + private boolean mutateAroundInitialEndTimeOnly = false; + private double mutationRangeStep = 1.0; + + @StringGetter(MUTATION_RANGE_STEP) + public double getMutationRangeStep() { + return mutationRangeStep; + } + @StringSetter(MUTATION_RANGE_STEP) + public void setMutationRangeStep(double mutationRangeStep) { + this.mutationRangeStep = mutationRangeStep; + } + @StringGetter(LATEST_ACTIVITY_END_TIME) + public double getLatestActivityEndTime() { + return latestActivityEndTime; + } + @StringSetter(LATEST_ACTIVITY_END_TIME) + public void setLatestActivityEndTime(String latestActivityEndTime) { + this.latestActivityEndTime = Time.parseTime(latestActivityEndTime); + } + + @StringGetter(MUTATE_AROUND_INITIAL_END_TIME_ONLY) + public boolean isMutateAroundInitialEndTimeOnly() { + return mutateAroundInitialEndTimeOnly; + } + @StringSetter(MUTATE_AROUND_INITIAL_END_TIME_ONLY) + public void setMutateAroundInitialEndTimeOnly(boolean mutateAroundInitialEndTimeOnly) { + this.mutateAroundInitialEndTimeOnly = mutateAroundInitialEndTimeOnly; + } + @StringGetter(MUTATION_RANGE) public double getMutationRange() { return this.mutationRange; @@ -56,9 +92,9 @@ public double getMutationRange() { public void setMutationRange(final double val) { this.mutationRange = val; } - + // --- - + private static final String MUTATION_AFFECTS_DURATION = "mutationAffectsDuration"; private boolean affectingDuration = true; @StringGetter(MUTATION_AFFECTS_DURATION) @@ -69,114 +105,6 @@ public boolean isAffectingDuration() { public void setAffectingDuration(boolean affectingDuration) { this.affectingDuration = affectingDuration; } - - // --- - - private static final String USE_INDIVIDUAL_SETTINGS_FOR_SUBPOPULATIONS = "useIndividualSettingsForSubpopulations"; - private boolean useIndividualSettingsForSubpopulations = false; -// @StringGetter(USE_INDIVIDUAL_SETTINGS_FOR_SUBPOPULATIONS) // I am disabling the xml usage for the time being, see comment below. kai, may'19 - public boolean isUseIndividualSettingsForSubpopulations() { - // yyyy is it really so plausible to have this? If we continue in this direction, we will eventually have the PTV behaviorally homogeneous - // groups. I would find it more natural to have behavior that depends continuously on person type, and then use Java in order to define that - // behaviour. Rather than to overload the config mechanism. kai, may'19 - return this.useIndividualSettingsForSubpopulations; - } -// @StringSetter(USE_INDIVIDUAL_SETTINGS_FOR_SUBPOPULATIONS) // I am disabling the xml usage for the time being, see comments. kai, may'19 - public void setUseIndividualSettingsForSubpopulations(boolean useIndividualSettingsForSubpopulations) { - // yyyy see comment under isUseIndividualSettingsForSubpopulations. kai, may'10 - this.useIndividualSettingsForSubpopulations = useIndividualSettingsForSubpopulations; - } - + // --- - - public TimeAllocationMutatorSubpopulationSettings getTimeAllocationMutatorSubpopulationSettings(String subpopulation) { - - if (subpopulation == null) return null; - - Collection configGroups = this.getParameterSets(TimeAllocationMutatorSubpopulationSettings.SET_NAME); - for (ConfigGroup group : configGroups) { - if (group instanceof TimeAllocationMutatorSubpopulationSettings) { - TimeAllocationMutatorSubpopulationSettings subpopulationSettings = (TimeAllocationMutatorSubpopulationSettings) group; - if (subpopulation.equals(subpopulationSettings.subpopulation)) return subpopulationSettings; - } - } - - return null; - } - - @Override - public ConfigGroup createParameterSet(final String type) { - switch (type) { - case TimeAllocationMutatorSubpopulationSettings.SET_NAME: - return new TimeAllocationMutatorSubpopulationSettings(); - default: - throw new IllegalArgumentException("unknown set type '" + type + "'"); - } - } - - @Override - public void addParameterSet(final ConfigGroup set) { - switch (set.getName()) { - case TimeAllocationMutatorSubpopulationSettings.SET_NAME: - super.addParameterSet(set); - break; - default: - throw new IllegalArgumentException( set.getName() ); - } - } - - public static class TimeAllocationMutatorSubpopulationSettings extends ReflectiveConfigGroup { - - public static final String SET_NAME = "subpopulationSettings"; - private static final String MUTATION_RANGE = "mutationRange"; - private static final String MUTATION_AFFECTS_DURATION = "mutationAffectsDuration"; - private static final String SUBPOPULATION = "subpopulation"; - - private double mutationRange = 1800.0; - private boolean affectingDuration = true; - private String subpopulation = null; - - public TimeAllocationMutatorSubpopulationSettings() { - super(SET_NAME); - } - - @Override - public final Map getComments() { - Map comments = super.getComments(); - comments.put(MUTATION_RANGE, "Default:1800.0; Defines how many seconds a time mutation can maximally shift a time."); - comments.put(MUTATION_AFFECTS_DURATION, "Default:true; Defines whether time mutation changes an activity's duration."); - comments.put(SUBPOPULATION, "Subpopulation to which the values from this parameter set are applied."); - return comments; - } - - @StringGetter(MUTATION_RANGE) - public double getMutationRange() { - return this.mutationRange; - } - - @StringSetter(MUTATION_RANGE) - public void setMutationRange(final double val) { - this.mutationRange = val; - } - - @StringGetter(MUTATION_AFFECTS_DURATION) - public boolean isAffectingDuration() { - return affectingDuration; - } - - @StringSetter(MUTATION_AFFECTS_DURATION) - public void setAffectingDuration(boolean affectingDuration) { - this.affectingDuration = affectingDuration; - } - - @StringSetter(SUBPOPULATION) - public void setSubpopulation(final String subpopulation) { - this.subpopulation = subpopulation; - } - - @StringGetter(SUBPOPULATION) - public String getSubpopulation() { - return this.subpopulation; - } - } } diff --git a/matsim/src/main/java/org/matsim/core/config/groups/TravelTimeCalculatorConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/TravelTimeCalculatorConfigGroup.java index 8ca06b3fc1f..c0302d24095 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/TravelTimeCalculatorConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/TravelTimeCalculatorConfigGroup.java @@ -41,9 +41,6 @@ public final class TravelTimeCalculatorConfigGroup extends ReflectiveConfigGroup public static final String GROUPNAME = "travelTimeCalculator"; - public enum TravelTimeCalculatorType {TravelTimeCalculatorArray,TravelTimeCalculatorHashMap} - - private static final String TRAVEL_TIME_CALCULATOR = "travelTimeCalculator"; private static final String TRAVEL_TIME_BIN_SIZE = "travelTimeBinSize"; private static final String TRAVEL_TIME_AGGREGATOR = "travelTimeAggregator"; private static final String TRAVEL_TIME_GETTER = "travelTimeGetter"; @@ -56,7 +53,6 @@ public enum TravelTimeCalculatorType {TravelTimeCalculatorArray,TravelTimeCalcul private static final String FILTERMODES = "filterModes"; private static final String SEPARATEMODES = "separateModes"; - private TravelTimeCalculatorType travelTimeCalculator = TravelTimeCalculatorType.TravelTimeCalculatorArray; private String travelTimeAggregator = "optimistic"; private String travelTimeGetter = "average"; private double traveltimeBinSize = 15 * 60; // use a default of 15min time-bins for analyzing the travel times @@ -89,22 +85,11 @@ public final Map getComments() { "respected by the travel time collector. 'car' is default which includes also buses from the pt simulation module."); map.put(FILTERMODES, "(only for backwards compatiblity; only used if " + SEPARATEMODES + "==false) Only modes included in analyzedModes are included." ) ; map.put(SEPARATEMODES, "(only for backwards compatibility) If false, link travel times are measured and aggregated over all vehicles using the link." ) ; - map.put( TRAVEL_TIME_CALCULATOR, "possible values: " + Arrays.stream( TravelTimeCalculatorType.values() ).map( type -> type.toString() + ' ' ).collect( Collectors.joining() ) ); return map; } enum DifferentModesHandling { separateAccordingToAnalyzedModes, jointButRestrictedToAnalyzedModes, jointAndUsingAllModes } - // --- - @StringSetter( TRAVEL_TIME_CALCULATOR ) - public void setTravelTimeCalculatorType(final String travelTimeCalculator){ - // leaving this as setter from string for backwards compatibility; enum.name() is not that terrible. kai, feb'18 - this.travelTimeCalculator = TravelTimeCalculatorType.valueOf( travelTimeCalculator ) ; - } - @StringGetter( TRAVEL_TIME_CALCULATOR ) - public TravelTimeCalculatorType getTravelTimeCalculatorType(){ - return this.travelTimeCalculator; - } // --- @StringSetter( TRAVEL_TIME_AGGREGATOR ) public void setTravelTimeAggregatorType(final String travelTimeAggregator){ diff --git a/matsim/src/main/java/org/matsim/core/controler/AbstractController.java b/matsim/src/main/java/org/matsim/core/controler/AbstractController.java index a335453cea5..5edf2d01b20 100644 --- a/matsim/src/main/java/org/matsim/core/controler/AbstractController.java +++ b/matsim/src/main/java/org/matsim/core/controler/AbstractController.java @@ -23,11 +23,13 @@ import org.apache.logging.log4j.Logger; import org.matsim.analysis.IterationStopWatch; import org.matsim.core.config.Config; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.listener.ControlerListener; import org.matsim.core.gbl.MatsimRandom; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.utils.MemoryObserver; +import java.io.UncheckedIOException; + /*package*/ abstract class AbstractController { // we already had one case where a method of this was removed, causing downstream failures; better just not // offer it at all; framework with injector should now be flexible enough. kai, mar'18 @@ -46,7 +48,7 @@ private Integer thisIteration = null; - + protected AbstractController() { this(new ControlerListenerManagerImpl(), new IterationStopWatch(), null); } @@ -97,7 +99,7 @@ public void shutdown(boolean unexpected) { protected abstract void runMobSim(); protected abstract void prepareForSim(); - + protected abstract void prepareForMobsim() ; /** @@ -112,11 +114,11 @@ public void shutdown(boolean unexpected) { protected abstract boolean shouldTerminate(int iteration); private void doIterations(Config config) throws MatsimRuntimeModifications.UnexpectedShutdownException { - int iteration = config.controler().getFirstIteration(); - + int iteration = config.controller().getFirstIteration(); + // Special case if lastIteration == -1 -> Do not run any Mobsim - boolean doTerminate = config.controler().getLastIteration() < iteration; - + boolean doTerminate = config.controller().getLastIteration() < iteration; + while (!doTerminate) { boolean isLastIteration = mayTerminateAfterIteration(iteration); iteration(config, iteration, isLastIteration); @@ -124,7 +126,7 @@ private void doIterations(Config config) throws MatsimRuntimeModifications.Unexp iteration++; } } - + final String MARKER = "### "; private void iteration(final Config config, final int iteration, boolean isLastIteration) throws MatsimRuntimeModifications.UnexpectedShutdownException { @@ -143,7 +145,7 @@ public void run() { } }); - if (iteration > config.controler().getFirstIteration()) { + if (iteration > config.controller().getFirstIteration()) { iterationStep("replanning", new Runnable() { @Override public void run() { @@ -172,12 +174,12 @@ public void run() { this.getStopwatch().endIteration(); try { - this.getStopwatch().writeTextFile(this.getControlerIO().getOutputFilename("stopwatch")); + this.getStopwatch().writeSeparatedFile(this.getControlerIO().getOutputFilename("stopwatch.csv"), config.global().getDefaultDelimiter()); } catch (UncheckedIOException e) { log.error("Could not write stopwatch file.", e); } - if (config.controler().isCreateGraphs()) { - this.getStopwatch().writeGraphFile(this.getControlerIO().getOutputFilename("stopwatch")); + if (config.controller().isCreateGraphs()) { + this.getStopwatch().writeGraphFile(this.getControlerIO().getOutputFilename("stopwatch.png", ControllerConfigGroup.CompressionType.none)); } log.info(MARKER + "ITERATION " + iteration + " ENDS"); log.info(Controler.DIVIDER); @@ -196,7 +198,7 @@ public void run() { controlerListenerManagerImpl.fireControlerBeforeMobsimEvent(iteration, isLastIteration); } }); - + iterationStep( "prepareForMobsim", new Runnable(){ @Override public void run() { @@ -224,7 +226,7 @@ public void run() { // Java 7 seems able to detect which throwables this can be, thus no // need to wrap or anything... Nice! - // If an exception occurs in the finally bloc, this exception will be + // If an exception occurs in the finally-block, this exception will be // suppressed, but at least we logged it. throw t; } diff --git a/matsim/src/main/java/org/matsim/core/controler/Controler.java b/matsim/src/main/java/org/matsim/core/controler/Controler.java index 43f893d8a41..bc7fbdc47da 100755 --- a/matsim/src/main/java/org/matsim/core/controler/Controler.java +++ b/matsim/src/main/java/org/matsim/core/controler/Controler.java @@ -194,7 +194,7 @@ private Controler(final String configFileName, final Config config, Scenario sce //scenario = ScenarioUtils.createScenario(this.config); //ScenarioUtils.loadScenario(scenario) ; } - this.config.parallelEventHandling().makeLocked(); + this.config.eventsManager().makeLocked(); this.scenario = scenario; this.overrides = scenario == null ? new ScenarioByConfigModule() : diff --git a/matsim/src/main/java/org/matsim/core/controler/ControlerDefaultsModule.java b/matsim/src/main/java/org/matsim/core/controler/ControlerDefaultsModule.java index 311c3ca9216..fc5c43da358 100755 --- a/matsim/src/main/java/org/matsim/core/controler/ControlerDefaultsModule.java +++ b/matsim/src/main/java/org/matsim/core/controler/ControlerDefaultsModule.java @@ -37,6 +37,7 @@ import org.matsim.core.population.VspPlansCleanerModule; import org.matsim.core.replanning.StrategyManagerModule; import org.matsim.core.replanning.annealing.ReplanningAnnealer; +import org.matsim.core.replanning.inheritance.PlanInheritanceModule; import org.matsim.core.router.TripRouterModule; import org.matsim.core.router.costcalculators.TravelDisutilityModule; import org.matsim.core.scoring.functions.CharyparNagelScoringFunctionModule; @@ -44,7 +45,6 @@ import org.matsim.core.utils.timing.TimeInterpretationModule; import org.matsim.counts.CountsModule; import org.matsim.guice.DependencyGraphModule; -import org.matsim.pt.counts.PtCountsModule; import org.matsim.vis.snapshotwriters.SnapshotWritersModule; import javax.imageio.ImageIO; @@ -74,10 +74,10 @@ public void install() { install(new ScoreStatsModule()); install(new ModeStatsModule()); install(new CountsModule()); - install(new PtCountsModule()); install(new VspPlansCleanerModule()); install(new SnapshotWritersModule()); install(new DependencyGraphModule()); + install(new PlanInheritanceModule()); // Comment by Tarek Chouaki. // To make sure the cache files used under ChartUtils are located in tmp folder in the output directory diff --git a/matsim/src/main/java/org/matsim/core/controler/NewControler.java b/matsim/src/main/java/org/matsim/core/controler/NewControler.java index c36813f7be2..13047b030fd 100755 --- a/matsim/src/main/java/org/matsim/core/controler/NewControler.java +++ b/matsim/src/main/java/org/matsim/core/controler/NewControler.java @@ -24,7 +24,7 @@ import org.matsim.analysis.IterationStopWatch; import org.matsim.core.config.Config; import org.matsim.core.config.consistency.ConfigConsistencyCheckerImpl; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.corelisteners.*; import org.matsim.core.controler.listener.ControlerListener; import org.matsim.core.mobsim.framework.Mobsim; @@ -48,7 +48,7 @@ class NewControler extends AbstractController implements ControlerI { private final TerminationCriterion terminationCriterion; private final DumpDataAtEnd dumpDataAtEnd; private final Set controlerListenersDeclaredByModules; - private final ControlerConfigGroup controlerConfigGroup; + private final ControllerConfigGroup controllerConfigGroup; private final OutputDirectoryHierarchy outputDirectoryHierarchy; @Inject @@ -56,7 +56,7 @@ class NewControler extends AbstractController implements ControlerI { IterationStopWatch stopWatch, PrepareForSim prepareForSim, EventsHandling eventsHandling, PlansDumping plansDumping, PlansReplanning plansReplanning, Provider mobsimProvider, PlansScoring plansScoring, TerminationCriterion terminationCriterion, DumpDataAtEnd dumpDataAtEnd, - Set controlerListenersDeclaredByModules, ControlerConfigGroup controlerConfigGroup, + Set controlerListenersDeclaredByModules, ControllerConfigGroup controllerConfigGroup, OutputDirectoryHierarchy outputDirectoryHierarchy , PrepareForMobsim prepareForMobsim ) { @@ -73,7 +73,7 @@ class NewControler extends AbstractController implements ControlerI { this.terminationCriterion = terminationCriterion; this.dumpDataAtEnd = dumpDataAtEnd; this.controlerListenersDeclaredByModules = controlerListenersDeclaredByModules; - this.controlerConfigGroup = controlerConfigGroup; + this.controllerConfigGroup = controllerConfigGroup; this.outputDirectoryHierarchy = outputDirectoryHierarchy; } @@ -94,7 +94,7 @@ protected final void loadCoreListeners() { * IMPORTANT: The execution order is reverse to the order the listeners * are added to the list. */ - if (controlerConfigGroup.getDumpDataAtEnd()) { + if (controllerConfigGroup.getDumpDataAtEnd()) { this.addCoreControlerListener(this.dumpDataAtEnd); } diff --git a/matsim/src/main/java/org/matsim/core/controler/OutputDirectoryHierarchy.java b/matsim/src/main/java/org/matsim/core/controler/OutputDirectoryHierarchy.java index 0e719b1dc8e..86272160a77 100644 --- a/matsim/src/main/java/org/matsim/core/controler/OutputDirectoryHierarchy.java +++ b/matsim/src/main/java/org/matsim/core/controler/OutputDirectoryHierarchy.java @@ -29,7 +29,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.utils.io.IOUtils; import jakarta.inject.Inject; @@ -53,12 +53,12 @@ public enum OverwriteFileSetting {failIfDirectoryExists, overwriteExistingFiles, private final String outputPath; - private final ControlerConfigGroup.CompressionType defaultCompressionType; + private final ControllerConfigGroup.CompressionType defaultCompressionType; private OverwriteFileSetting overwriteFiles = OverwriteFileSetting.failIfDirectoryExists; @Inject - OutputDirectoryHierarchy(ControlerConfigGroup config) { + OutputDirectoryHierarchy(ControllerConfigGroup config) { this(config.getOutputDirectory(), config.getRunId(), @@ -72,14 +72,14 @@ public enum OverwriteFileSetting {failIfDirectoryExists, overwriteExistingFiles, * @param config */ public OutputDirectoryHierarchy( Config config ) { - this( config.controler().getOutputDirectory(), config.controler().getRunId(), config.controler().getOverwriteFileSetting(), config.controler().getCompressionType() ); + this( config.controller().getOutputDirectory(), config.controller().getRunId(), config.controller().getOverwriteFileSetting(), config.controller().getCompressionType() ); } - public OutputDirectoryHierarchy(String outputPath, OverwriteFileSetting overwriteFiles, ControlerConfigGroup.CompressionType defaultCompressionType) { + public OutputDirectoryHierarchy(String outputPath, OverwriteFileSetting overwriteFiles, ControllerConfigGroup.CompressionType defaultCompressionType) { this(outputPath, null, overwriteFiles, true, defaultCompressionType); } - public OutputDirectoryHierarchy(String outputPath, String runId, OverwriteFileSetting overwriteFiles, ControlerConfigGroup.CompressionType defaultCompressionType) { + public OutputDirectoryHierarchy(String outputPath, String runId, OverwriteFileSetting overwriteFiles, ControllerConfigGroup.CompressionType defaultCompressionType) { this(outputPath, runId, overwriteFiles, true, defaultCompressionType); } /** @@ -89,7 +89,7 @@ public OutputDirectoryHierarchy(String outputPath, String runId, OverwriteFileSe * @param outputPath the path to the output directory * @param createDirectories create the directories or abort if they exist */ - public OutputDirectoryHierarchy(String outputPath, String runId, OverwriteFileSetting overwriteFiles, boolean createDirectories, ControlerConfigGroup.CompressionType compressionType){ + public OutputDirectoryHierarchy(String outputPath, String runId, OverwriteFileSetting overwriteFiles, boolean createDirectories, ControllerConfigGroup.CompressionType compressionType){ this.overwriteFiles = overwriteFiles; if (outputPath.endsWith("/")) { outputPath = outputPath.substring(0, outputPath.length() - 1); @@ -144,11 +144,18 @@ public final String getIterationFilename(final int iteration, final String filen return s.toString(); } + public String getIterationFilename(int iteration, String filename, ControllerConfigGroup.CompressionType compression) { + if (compression == null) { + return getIterationFilename(iteration, filename); + } + return getIterationFilename(iteration, filename + compression.fileEnding); + } + public final String getIterationFilename(int iteration, Controler.DefaultFiles file) { return getIterationFilename(iteration, file, this.defaultCompressionType); } - public final String getIterationFilename(int iteration, Controler.DefaultFiles file, ControlerConfigGroup.CompressionType compression) { + public final String getIterationFilename(int iteration, Controler.DefaultFiles file, ControllerConfigGroup.CompressionType compression) { if (compression == null) { return getIterationFilename(iteration, file.filename); } @@ -173,6 +180,13 @@ public final String getOutputFilename(final String filename) { return s.toString(); } + public String getOutputFilename(String filename, ControllerConfigGroup.CompressionType compression) { + if (compression == null) { + return getOutputFilename(filename); + } + return getOutputFilename(filename + compression.fileEnding); + } + public final String getOutputFilenameWithOutputPrefix(final String filename) { return getOutputFilename(Controler.OUTPUT_PREFIX + filename); } @@ -181,7 +195,7 @@ public final String getOutputFilename(Controler.DefaultFiles file) { return getOutputFilename(file, this.defaultCompressionType); } - public final String getOutputFilename(Controler.DefaultFiles file, ControlerConfigGroup.CompressionType compression) { + public final String getOutputFilename(Controler.DefaultFiles file, ControllerConfigGroup.CompressionType compression) { if (compression == null) { return getOutputFilename(Controler.OUTPUT_PREFIX + file.filename); } diff --git a/matsim/src/main/java/org/matsim/core/controler/PrepareForSimImpl.java b/matsim/src/main/java/org/matsim/core/controler/PrepareForSimImpl.java index e1e15970ef7..3278f06e295 100644 --- a/matsim/src/main/java/org/matsim/core/controler/PrepareForSimImpl.java +++ b/matsim/src/main/java/org/matsim/core/controler/PrepareForSimImpl.java @@ -19,9 +19,11 @@ * * * *********************************************************************** */ - package org.matsim.core.controler; +package org.matsim.core.controler; +import jakarta.inject.Inject; +import jakarta.inject.Provider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; @@ -49,7 +51,6 @@ import org.matsim.core.router.TripStructureUtils; import org.matsim.core.router.TripStructureUtils.Trip; import org.matsim.core.scenario.Lockable; -import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.timing.TimeInterpretation; import org.matsim.facilities.ActivityFacilities; import org.matsim.facilities.FacilitiesFromPopulation; @@ -57,12 +58,8 @@ import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; -import jakarta.inject.Inject; -import jakarta.inject.Provider; - import javax.annotation.Nullable; import java.util.*; -import java.util.stream.Collectors; import static org.matsim.core.config.groups.QSimConfigGroup.VehiclesSource.modeVehicleTypesFromVehiclesData; @@ -230,13 +227,35 @@ private void createAndAddVehiclesForEveryNetworkMode() { for (Person person : scenario.getPopulation().getPersons().values()) { - var modeToVehicle = modeVehicleTypes.entrySet().stream() - // map mode type to vehicle id - .map(modeType -> Tuple.of(modeType, createVehicleId(person, modeType.getKey()))) - // create a corresponding vehicle - .peek(tuple -> createAndAddVehicleIfNecessary(tuple.getSecond(), tuple.getFirst().getValue())) - // write mode-string to vehicle-id into a map - .collect(Collectors.toMap(tuple -> tuple.getFirst().getKey(), Tuple::getSecond)); + + Map> modeToVehicle = new HashMap<>(); + + // optional attribute, that can be null + Map> modeTypes = VehicleUtils.getVehicleTypes(person); + + for (Map.Entry modeType : modeVehicleTypes.entrySet()) { + + String mode = modeType.getKey(); + + Id vehicleId = createVehicleId(person, mode); + + // get the type + VehicleType type = modeType.getValue(); + + // Use the person attribute to map to a more specific vehicle type + if (modeTypes != null && modeTypes.containsKey(mode)) { + Id typeId = modeTypes.get(mode); + type = scenario.getVehicles().getVehicleTypes().get(typeId); + if (type == null) { + throw new IllegalStateException("Vehicle type " + typeId + " specified for person " + person.getId() + ", but not found in scenario."); + } + } + + createAndAddVehicleIfNecessary(vehicleId, type); + + // write mode-string to vehicle-id into a map + modeToVehicle.put(mode, vehicleId); + } VehicleUtils.insertVehicleIdsIntoAttributes(person, modeToVehicle); } @@ -266,7 +285,7 @@ private Map getVehicleTypesForAllNetworkAndMainModes() { } Set modes = new HashSet<>(qSimConfigGroup.getMainModes()); - modes.addAll(scenario.getConfig().plansCalcRoute().getNetworkModes()); + modes.addAll(scenario.getConfig().routing().getNetworkModes()); for (String mode : modes) { VehicleType type; diff --git a/matsim/src/main/java/org/matsim/core/controler/TerminateAtFixedIterationNumber.java b/matsim/src/main/java/org/matsim/core/controler/TerminateAtFixedIterationNumber.java index 6ce863d4164..d5b3a7a95dc 100644 --- a/matsim/src/main/java/org/matsim/core/controler/TerminateAtFixedIterationNumber.java +++ b/matsim/src/main/java/org/matsim/core/controler/TerminateAtFixedIterationNumber.java @@ -23,14 +23,14 @@ import jakarta.inject.Inject; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; class TerminateAtFixedIterationNumber implements TerminationCriterion { private final int lastIteration; @Inject - TerminateAtFixedIterationNumber(ControlerConfigGroup controlerConfigGroup) { - this.lastIteration = controlerConfigGroup.getLastIteration(); + TerminateAtFixedIterationNumber(ControllerConfigGroup controllerConfigGroup) { + this.lastIteration = controllerConfigGroup.getLastIteration(); } @Override diff --git a/matsim/src/main/java/org/matsim/core/controler/corelisteners/DumpDataAtEndImpl.java b/matsim/src/main/java/org/matsim/core/controler/corelisteners/DumpDataAtEndImpl.java index 25fd325c37a..74d2d84ce14 100644 --- a/matsim/src/main/java/org/matsim/core/controler/corelisteners/DumpDataAtEndImpl.java +++ b/matsim/src/main/java/org/matsim/core/controler/corelisteners/DumpDataAtEndImpl.java @@ -30,7 +30,7 @@ import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigWriter; -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.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -69,7 +69,7 @@ final class DumpDataAtEndImpl implements DumpDataAtEnd, ShutdownListener { private Config config; @Inject - private ControlerConfigGroup controlerConfigGroup; + private ControllerConfigGroup controllerConfigGroup; @Inject private VspExperimentalConfigGroup vspConfig; @@ -129,7 +129,7 @@ public void notifyShutdown(ShutdownEvent event) { dumpLanes(); dumpCounts(); - if (!event.isUnexpected() && this.vspConfig.isWritingOutputEvents() && (this.controlerConfigGroup.getWriteEventsInterval()!=0)) { + if (!event.isUnexpected() && this.vspConfig.isWritingOutputEvents() && (this.controllerConfigGroup.getWriteEventsInterval()!=0)) { dumpOutputEvents(event.getIteration()); } dumpOutputTrips(event.getIteration()); @@ -137,13 +137,13 @@ public void notifyShutdown(ShutdownEvent event) { dumpOutputActivities(event.getIteration()); dumpExperiencedPlans(event.getIteration()); - if (controlerConfigGroup.getCleanItersAtEnd() == ControlerConfigGroup.CleanIterations.delete) { + if (controllerConfigGroup.getCleanItersAtEnd() == ControllerConfigGroup.CleanIterations.delete) { this.controlerIO.deleteIterationDirectory(); } } private void dumpOutputEvents(int iteration) { - for (ControlerConfigGroup.EventsFileFormat format : this.controlerConfigGroup.getEventsFileFormats()) { + for (ControllerConfigGroup.EventsFileFormat format : this.controllerConfigGroup.getEventsFileFormats()) { try{ Controler.DefaultFiles file; switch (format) { @@ -200,7 +200,7 @@ private void dumpOutputLegs(int iteration) { } private void dumpExperiencedPlans(int iteration) { - if (this.config.planCalcScore().isWriteExperiencedPlans() ) { + if (this.config.scoring().isWriteExperiencedPlans() ) { try { IOUtils.copyFile(this.controlerIO.getIterationFilename(iteration, Controler.DefaultFiles.experiencedPlans), this.controlerIO.getOutputFilename(Controler.DefaultFiles.experiencedPlans)); @@ -306,8 +306,8 @@ private void dumpFacilities() { private void dumpConfig() { // dump config - new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(Controler.DefaultFiles.config, ControlerConfigGroup.CompressionType.none)); - new ConfigWriter(this.config, ConfigWriter.Verbosity.minimal).write(this.controlerIO.getOutputFilename(Controler.DefaultFiles.configReduced, ControlerConfigGroup.CompressionType.none)); + new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(Controler.DefaultFiles.config, ControllerConfigGroup.CompressionType.none)); + new ConfigWriter(this.config, ConfigWriter.Verbosity.minimal).write(this.controlerIO.getOutputFilename(Controler.DefaultFiles.configReduced, ControllerConfigGroup.CompressionType.none)); } private void dumpNetwork() { diff --git a/matsim/src/main/java/org/matsim/core/controler/corelisteners/EventsHandlingImpl.java b/matsim/src/main/java/org/matsim/core/controler/corelisteners/EventsHandlingImpl.java index e4d87291d8b..722bbe2c0d9 100644 --- a/matsim/src/main/java/org/matsim/core/controler/corelisteners/EventsHandlingImpl.java +++ b/matsim/src/main/java/org/matsim/core/controler/corelisteners/EventsHandlingImpl.java @@ -32,8 +32,8 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.ControlerConfigGroup.EventsFileFormat; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup.EventsFileFormat; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.events.BeforeMobsimEvent; @@ -54,14 +54,14 @@ final class EventsHandlingImpl implements EventsHandling, BeforeMobsimListener, IterationEndsListener, ShutdownListener { final static private Logger log = LogManager.getLogger(EventsHandlingImpl.class); - + private final EventsManager eventsManager; private List eventWriters = new LinkedList<>(); private int writeEventsInterval; - + private Set eventsFileFormats ; - + private OutputDirectoryHierarchy controlerIO ; private int writeMoreUntilIteration; @@ -69,7 +69,7 @@ final class EventsHandlingImpl implements EventsHandling, BeforeMobsimListener, @Inject EventsHandlingImpl( final EventsManager eventsManager, - final ControlerConfigGroup config, + final ControllerConfigGroup config, final OutputDirectoryHierarchy controlerIO) { this.eventsManager = eventsManager; this.writeEventsInterval = config.getWriteEventsInterval(); @@ -118,11 +118,11 @@ public void notifyBeforeMobsim(BeforeMobsimEvent event) { } } } - + @Override public void notifyIterationEnds(IterationEndsEvent event) { /* - * Events that are produced after the Mobsim has ended, e.g. by the RoadProcing + * Events that are produced after the Mobsim has ended, e.g. by the RoadProcing * module, should also be written to the events file. */ for (EventWriter writer : this.eventWriters) { @@ -138,5 +138,5 @@ public void notifyShutdown(ShutdownEvent event) { writer.closeFile(); } } - + } diff --git a/matsim/src/main/java/org/matsim/core/controler/corelisteners/PlansDumpingImpl.java b/matsim/src/main/java/org/matsim/core/controler/corelisteners/PlansDumpingImpl.java index 5857544e818..66a57005853 100644 --- a/matsim/src/main/java/org/matsim/core/controler/corelisteners/PlansDumpingImpl.java +++ b/matsim/src/main/java/org/matsim/core/controler/corelisteners/PlansDumpingImpl.java @@ -27,7 +27,7 @@ import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.events.BeforeMobsimEvent; @@ -41,7 +41,7 @@ /** * {@link org.matsim.core.controler.listener.ControlerListener} that dumps the * complete plans regularly at the start of an iteration - * ({@link ControlerConfigGroup#getWritePlansInterval()} as well as in the first + * ({@link ControllerConfigGroup#getWritePlansInterval()} as well as in the first * iteration, just in case someone might check that the replanning worked * correctly in the first iteration. * @@ -62,7 +62,7 @@ final class PlansDumpingImpl implements PlansDumping, BeforeMobsimListener { private int writeMoreUntilIteration; @Inject - PlansDumpingImpl(ControlerConfigGroup config) { + PlansDumpingImpl(ControllerConfigGroup config) { this.writePlansInterval = config.getWritePlansInterval(); this.writeMoreUntilIteration = config.getWritePlansUntilIteration() ; } diff --git a/matsim/src/main/java/org/matsim/core/events/EventsManagerModule.java b/matsim/src/main/java/org/matsim/core/events/EventsManagerModule.java index ca7c38ce61b..f6c8b093339 100644 --- a/matsim/src/main/java/org/matsim/core/events/EventsManagerModule.java +++ b/matsim/src/main/java/org/matsim/core/events/EventsManagerModule.java @@ -34,10 +34,10 @@ public final class EventsManagerModule extends AbstractModule { @Override public void install() { - if (BooleanUtils.isTrue(getConfig().parallelEventHandling().getOneThreadPerHandler())) { + if (BooleanUtils.isTrue(getConfig().eventsManager().getOneThreadPerHandler())) { bindEventsManager().to(ParallelEventsManager.class).in(Singleton.class); - } else if (getConfig().parallelEventHandling().getNumberOfThreads() != null) { - if (BooleanUtils.isTrue(getConfig().parallelEventHandling().getSynchronizeOnSimSteps())) { + } else if (getConfig().eventsManager().getNumberOfThreads() != null) { + if (BooleanUtils.isTrue(getConfig().eventsManager().getSynchronizeOnSimSteps())) { bindEventsManager().to(SimStepParallelEventsManagerImpl.class).in(Singleton.class); } else { bindEventsManager().to(ParallelEventsManagerImpl.class).in(Singleton.class); diff --git a/matsim/src/main/java/org/matsim/core/events/EventsReaderJson.java b/matsim/src/main/java/org/matsim/core/events/EventsReaderJson.java index 9c1f9dea65c..85d4e24fba0 100644 --- a/matsim/src/main/java/org/matsim/core/events/EventsReaderJson.java +++ b/matsim/src/main/java/org/matsim/core/events/EventsReaderJson.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.UncheckedIOException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; @@ -63,7 +64,6 @@ import org.matsim.api.core.v01.events.HasPersonId; import org.matsim.core.events.MatsimEventsReader.CustomEventMapper; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.facilities.ActivityFacility; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.TransitLine; @@ -147,13 +147,13 @@ private void parseEvent(JsonNode o) { // === material related to wait2link below here === if (LinkLeaveEvent.EVENT_TYPE.equals(eventType)) { - this.events.processEvent(new LinkLeaveEvent(time, + this.events.processEvent(new LinkLeaveEvent(time, Id.create(o.get(LinkLeaveEvent.ATTRIBUTE_VEHICLE).asText(), Vehicle.class), Id.create(o.get(LinkLeaveEvent.ATTRIBUTE_LINK).asText(), Link.class) // had driver id in previous version )); } else if (LinkEnterEvent.EVENT_TYPE.equals(eventType)) { - this.events.processEvent(new LinkEnterEvent(time, + this.events.processEvent(new LinkEnterEvent(time, Id.create(o.get(LinkEnterEvent.ATTRIBUTE_VEHICLE).asText(), Vehicle.class), Id.create(o.get(LinkEnterEvent.ATTRIBUTE_LINK).asText(), Link.class) // had driver id in previous version @@ -161,7 +161,7 @@ private void parseEvent(JsonNode o) { } else if (VehicleEntersTrafficEvent.EVENT_TYPE.equals(eventType)) { // (this is the new version, marked by the new events name) - this.events.processEvent(new VehicleEntersTrafficEvent(time, + this.events.processEvent(new VehicleEntersTrafficEvent(time, Id.create(o.get(HasPersonId.ATTRIBUTE_PERSON).asText(), Person.class), Id.create(o.get(VehicleEntersTrafficEvent.ATTRIBUTE_LINK).asText(), Link.class), Id.create(o.get(VehicleEntersTrafficEvent.ATTRIBUTE_VEHICLE).asText(), Vehicle.class), @@ -189,7 +189,7 @@ private void parseEvent(JsonNode o) { position )); } else if (VehicleLeavesTrafficEvent.EVENT_TYPE.equals(eventType)) { - this.events.processEvent(new VehicleLeavesTrafficEvent(time, + this.events.processEvent(new VehicleLeavesTrafficEvent(time, Id.create(o.get(VehicleLeavesTrafficEvent.ATTRIBUTE_DRIVER).asText(), Person.class), Id.create(o.get(VehicleLeavesTrafficEvent.ATTRIBUTE_LINK).asText(), Link.class), o.has(VehicleLeavesTrafficEvent.ATTRIBUTE_VEHICLE) ? Id.create(o.get(VehicleLeavesTrafficEvent.ATTRIBUTE_VEHICLE).asText(), Vehicle.class) : null, @@ -206,7 +206,7 @@ else if (ActivityEndEvent.EVENT_TYPE.equals(eventType)) { coord = new Coord(xx, yy); } this.events.processEvent(new ActivityEndEvent( - time, + time, Id.create(o.get(HasPersonId.ATTRIBUTE_PERSON).asText(), Person.class), Id.create(o.get(HasLinkId.ATTRIBUTE_LINK).asText(), Link.class), o.has(HasFacilityId.ATTRIBUTE_FACILITY) ? Id.create(o.get(HasFacilityId.ATTRIBUTE_FACILITY).asText(), ActivityFacility.class) : null, @@ -297,7 +297,7 @@ else if (ActivityEndEvent.EVENT_TYPE.equals(eventType)) { this.events.processEvent(new PersonLeavesVehicleEvent(time, pId, vId)); } else if (TeleportationArrivalEvent.EVENT_TYPE.equals(eventType)) { this.events.processEvent(new TeleportationArrivalEvent( - time, + time, Id.create(o.get(TeleportationArrivalEvent.ATTRIBUTE_PERSON).asText(), Person.class), o.get(TeleportationArrivalEvent.ATTRIBUTE_DISTANCE).asDouble(), o.path(TeleportationArrivalEvent.ATTRIBUTE_MODE).asText(null))); diff --git a/matsim/src/main/java/org/matsim/core/events/MatsimEventsReader.java b/matsim/src/main/java/org/matsim/core/events/MatsimEventsReader.java index 24663d4ba92..25bbe72a79e 100644 --- a/matsim/src/main/java/org/matsim/core/events/MatsimEventsReader.java +++ b/matsim/src/main/java/org/matsim/core/events/MatsimEventsReader.java @@ -33,7 +33,7 @@ import org.matsim.api.core.v01.events.GenericEvent; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.api.internal.MatsimReader; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.utils.io.MatsimXmlParser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; @@ -94,7 +94,7 @@ public void readStream(final InputStream stream) { new XmlEventsReader(this.events, this.customEventMappers).parse(stream ); } - public void readStream(final InputStream stream, final ControlerConfigGroup.EventsFileFormat format) { + public void readStream(final InputStream stream, final ControllerConfigGroup.EventsFileFormat format) { switch (format) { case xml: new XmlEventsReader(this.events, this.customEventMappers).parse(stream); diff --git a/matsim/src/main/java/org/matsim/core/events/ParallelEventsManager.java b/matsim/src/main/java/org/matsim/core/events/ParallelEventsManager.java index 287cc7eb216..996816efebe 100644 --- a/matsim/src/main/java/org/matsim/core/events/ParallelEventsManager.java +++ b/matsim/src/main/java/org/matsim/core/events/ParallelEventsManager.java @@ -59,7 +59,7 @@ public final class ParallelEventsManager implements EventsManager { @Inject ParallelEventsManager(Config config) { - this(config.parallelEventHandling().getSynchronizeOnSimSteps() != null ? config.parallelEventHandling().getSynchronizeOnSimSteps() : true, config.parallelEventHandling().getEventsQueueSize()); + this(config.eventsManager().getSynchronizeOnSimSteps() != null ? config.eventsManager().getSynchronizeOnSimSteps() : true, config.eventsManager().getEventsQueueSize()); } diff --git a/matsim/src/main/java/org/matsim/core/events/ParallelEventsManagerImpl.java b/matsim/src/main/java/org/matsim/core/events/ParallelEventsManagerImpl.java index 64287c3acdb..820e8874ee2 100644 --- a/matsim/src/main/java/org/matsim/core/events/ParallelEventsManagerImpl.java +++ b/matsim/src/main/java/org/matsim/core/events/ParallelEventsManagerImpl.java @@ -82,10 +82,10 @@ public final class ParallelEventsManagerImpl implements EventsManager { @Inject ParallelEventsManagerImpl(Config config) { - if (config.parallelEventHandling().getEstimatedNumberOfEvents() != null) { - preInputBufferMaxLength = (int) (config.parallelEventHandling().getEstimatedNumberOfEvents() / 10); + if (config.eventsManager().getEstimatedNumberOfEvents() != null) { + preInputBufferMaxLength = (int) (config.eventsManager().getEstimatedNumberOfEvents() / 10); } - init(config.parallelEventHandling().getNumberOfThreads()); + init(config.eventsManager().getNumberOfThreads()); } /** diff --git a/matsim/src/main/java/org/matsim/core/events/SimStepParallelEventsManagerImpl.java b/matsim/src/main/java/org/matsim/core/events/SimStepParallelEventsManagerImpl.java index c7a282c5a4d..726c62b96e8 100644 --- a/matsim/src/main/java/org/matsim/core/events/SimStepParallelEventsManagerImpl.java +++ b/matsim/src/main/java/org/matsim/core/events/SimStepParallelEventsManagerImpl.java @@ -36,7 +36,7 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.events.Event; import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.config.groups.ParallelEventHandlingConfigGroup; +import org.matsim.core.config.groups.EventsManagerConfigGroup; import org.matsim.core.events.handler.EventHandler; import org.matsim.core.gbl.Gbl; @@ -67,7 +67,7 @@ class SimStepParallelEventsManagerImpl implements EventsManager { private AtomicReference hadException = new AtomicReference<>(); @Inject - SimStepParallelEventsManagerImpl(ParallelEventHandlingConfigGroup config) { + SimStepParallelEventsManagerImpl(EventsManagerConfigGroup config) { this(config.getNumberOfThreads() != null ? config.getNumberOfThreads() : 1); } diff --git a/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterJson.java b/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterJson.java index f4a9cd13eea..85c26e35e00 100644 --- a/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterJson.java +++ b/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterJson.java @@ -6,11 +6,11 @@ import org.matsim.api.core.v01.events.Event; import org.matsim.core.events.handler.BasicEventHandler; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import java.io.File; import java.io.IOException; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.util.Map; /** @@ -69,4 +69,4 @@ public void handleEvent(final Event event) { public void reset(final int iter) { } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterXML.java b/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterXML.java index a1968661df9..b6099c9e69b 100644 --- a/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterXML.java +++ b/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterXML.java @@ -23,12 +23,12 @@ import org.matsim.api.core.v01.events.Event; import org.matsim.core.events.handler.BasicEventHandler; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; +import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.Map; @@ -98,7 +98,7 @@ public void handleEvent(final Event event) { /** * Encodes the given string in such a way that it no longer contains * characters that have a special meaning in xml. - * + * * @see http://www.w3.org/International/questions/qa-escapes#use * @param attributeValue * @return String with some characters replaced by their xml-encoding. @@ -141,7 +141,7 @@ private String encodeAttributeValue(final String attributeValue) { bf.append(ch); } } - + return bf.toString(); } return attributeValue; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/DefaultMobsimModule.java b/matsim/src/main/java/org/matsim/core/mobsim/DefaultMobsimModule.java index 24649b3e059..eb5463a2e7c 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/DefaultMobsimModule.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/DefaultMobsimModule.java @@ -22,7 +22,7 @@ package org.matsim.core.mobsim; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.ExternalMobimConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.events.MobsimScopeEventHandlingModule; @@ -34,13 +34,13 @@ public class DefaultMobsimModule extends AbstractModule { @Override public void install() { - if (getConfig().controler().getMobsim().equals(ControlerConfigGroup.MobsimType.qsim.toString())) { + if (getConfig().controller().getMobsim().equals(ControllerConfigGroup.MobsimType.qsim.toString())) { install(new QSimModule()); // bind( RelativePositionOfEntryExitOnLink.class ).toInstance( () -> 1. ); - } else if (getConfig().controler().getMobsim().equals(ControlerConfigGroup.MobsimType.JDEQSim.toString())) { + } else if (getConfig().controller().getMobsim().equals(ControllerConfigGroup.MobsimType.JDEQSim.toString())) { bindMobsim().to(JDEQSimulation.class); // bind( RelativePositionOfEntryExitOnLink.class ).toInstance( () -> 0. ); - } else if (getConfig().controler().getMobsim().equals(ControlerConfigGroup.MobsimType.hermes.toString())) { + } else if (getConfig().controller().getMobsim().equals(ControllerConfigGroup.MobsimType.hermes.toString())) { bindMobsim().toProvider(HermesProvider.class); } else if (getConfig().getModule(ExternalMobimConfigGroup.GROUP_NAME) != null && ((ExternalMobimConfigGroup)getConfig().getModule( diff --git a/matsim/src/main/java/org/matsim/core/mobsim/hermes/HermesConfigGroup.java b/matsim/src/main/java/org/matsim/core/mobsim/hermes/HermesConfigGroup.java index 61f82aa42ce..044f374dfb1 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/hermes/HermesConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/hermes/HermesConfigGroup.java @@ -20,7 +20,6 @@ import jakarta.validation.constraints.Positive; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.TransportMode; import org.matsim.core.config.Config; import org.matsim.core.config.ReflectiveConfigGroup; @@ -168,7 +167,7 @@ public Map getComments() { @Override protected void checkConsistency(Config config) { super.checkConsistency(config); - if (config.parallelEventHandling().getOneThreadPerHandler()!=true && config.controler().getMobsim().equals("hermes")){ + if (config.eventsManager().getOneThreadPerHandler()!=true && config.controller().getMobsim().equals("hermes")){ LogManager.getLogger(getClass()).warn("Hermes should be run with one thread per handler."); } } diff --git a/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/JDEQSimConfigGroup.java b/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/JDEQSimConfigGroup.java index f2abdfbbfb2..a7766a68582 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/JDEQSimConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/JDEQSimConfigGroup.java @@ -30,7 +30,7 @@ */ public class JDEQSimConfigGroup extends ReflectiveConfigGroup { - public final static String NAME = "JDEQSim"; + public final static String NAME = "jdeqsim"; // CONSTANTS public static final String START_LEG = "start leg"; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/DefaultTeleportationEngine.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/DefaultTeleportationEngine.java index 2b7d7823a67..86d1759be15 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/DefaultTeleportationEngine.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/DefaultTeleportationEngine.java @@ -96,7 +96,7 @@ public boolean handleDeparture(double now, MobsimAgent agent, Id linkId) { double travelTime = agent.getExpectedTravelTime().seconds() ; if ( withTravelTimeCheck ) { - Double speed = scenario.getConfig().plansCalcRoute().getTeleportedModeSpeeds().get( agent.getMode() ) ; + Double speed = scenario.getConfig().routing().getTeleportedModeSpeeds().get( agent.getMode() ) ; Facility dpfac = agent.getCurrentFacility() ; Facility arfac = agent.getDestinationFacility() ; travelTime = DefaultTeleportationEngine.travelTimeCheck(travelTime, speed, dpfac, arfac); diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/PreplanningEngine.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/PreplanningEngine.java index f6be7dc4ca9..cb85462403e 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/PreplanningEngine.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/PreplanningEngine.java @@ -22,7 +22,7 @@ package org.matsim.core.mobsim.qsim; import static java.util.Comparator.comparing; -import static org.matsim.core.config.groups.PlanCalcScoreConfigGroup.createStageActivityType; +import static org.matsim.core.config.groups.ScoringConfigGroup.createStageActivityType; import java.util.ArrayList; import java.util.Collections; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/AbstractTransitDriverAgent.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/AbstractTransitDriverAgent.java index 6555514f4c1..d7dd5939154 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/AbstractTransitDriverAgent.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/AbstractTransitDriverAgent.java @@ -65,7 +65,7 @@ public abstract class AbstractTransitDriverAgent implements TransitDriverAgent, private final PassengerAccessEgressImpl accessEgress; - /* package */ MobsimAgent.State state = MobsimAgent.State.ACTIVITY ; + /* package */ MobsimAgent.State state = MobsimAgent.State.ACTIVITY ; // yy not so great: implicit instantiation at activity. kai, nov'11 @Override public final MobsimAgent.State getState() { @@ -147,6 +147,17 @@ public final void notifyMoveOverNode(Id nextLinkId) { this.nextLinkIndex++; } + protected final int getNextLinkIndex() { + return nextLinkIndex; + } + + /** + * Overwrite the current link index. May be used by implementing classes, but should be handled with care. + */ + protected final void setNextLinkIndex(int idx) { + nextLinkIndex = idx; + } + @Override public final TransitStopFacility getNextTransitStop() { if (this.nextStop == null) { @@ -165,7 +176,7 @@ public double handleTransitStop(final TransitStopFacility stop, final double now TransitRoute route = this.getTransitRoute(); List stopsToCome = route.getStops().subList(stopIterator.nextIndex(), route.getStops().size()); /* - * If there are passengers leaving or entering, the stop time must be not greater than 1.0 in order to let them (de-)board every second. + * If there are passengers leaving or entering, the stop time must be not greater than 1.0 in order to let them (de-)board every second. * If a stopTime greater than 1.0 is used, this method is not necessarily triggered by the qsim, so (de-)boarding will not happen. Dg, 10-2012 */ double stopTime = this.accessEgress.calculateStopTimeAndTriggerBoarding(getTransitRoute(), getTransitLine(), this.vehicle, stop, stopsToCome, now); @@ -202,7 +213,7 @@ public void notifyArrivalOnLinkByNonNetworkMode(final Id linkId) { /**Design comments:
      *
    • Keeping this for the time being, since the derived methods somehow need to get the selected plan. Might * keep track of the selected plan directly, but someone would need to look more into the design. kai, jun'11 - *
    • For that reason, I made the method package-private. There is, however, probably not much harm to make + *
    • For that reason, I made the method package-private. There is, however, probably not much harm to make * it public again as long as it is not part of the PlanDriverAgent interface. kai, jun'11 *
    */ @@ -276,7 +287,7 @@ private void depart(final double now) { private void assertAllStopsServed() { if (this.nextStop != null) { - RuntimeException e = new RuntimeException("Transit vehicle is not yet at last stop! vehicle-id = " + RuntimeException e = new RuntimeException("Transit vehicle is not yet at last stop! vehicle-id = " + this.vehicle.getVehicle().getId() + "; next-stop = " + this.nextStop.getStopFacility().getId()); log.error(e); throw e; @@ -377,17 +388,17 @@ public void setStartLinkId(final Id linkId) { public void setRouteDescription(String routeDescription) { throw new UnsupportedOperationException("read only route."); } - + @Override public String getRouteDescription() { return this.delegate.getRouteDescription(); } - + @Override public String getRouteType() { return this.delegate.getRouteType(); } - + @Override @Deprecated public double getDistance() { @@ -437,4 +448,4 @@ public NetworkRouteWrapper clone() { } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/DefaultTransitDriverAgentFactory.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/DefaultTransitDriverAgentFactory.java index 07a6a5eb3de..f38e55d3195 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/DefaultTransitDriverAgentFactory.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/DefaultTransitDriverAgentFactory.java @@ -28,17 +28,8 @@ */ public class DefaultTransitDriverAgentFactory implements TransitDriverAgentFactory { - private final InternalInterface internalInterface; - private final TransitStopAgentTracker transitStopAgentTracker; - - public DefaultTransitDriverAgentFactory(InternalInterface internalInterface, TransitStopAgentTracker transitStopAgentTracker) { - this.internalInterface = internalInterface; - this.transitStopAgentTracker = transitStopAgentTracker; - } - - @Override - public AbstractTransitDriverAgent createTransitDriver(Umlauf umlauf) { + public AbstractTransitDriverAgent createTransitDriver(Umlauf umlauf, InternalInterface internalInterface, TransitStopAgentTracker transitStopAgentTracker) { return new TransitDriverAgentImpl(umlauf, TransportMode.car, transitStopAgentTracker, internalInterface); } diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitDriverAgentFactory.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitDriverAgentFactory.java index 2ea71d38b27..2268fd5d0ff 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitDriverAgentFactory.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitDriverAgentFactory.java @@ -20,6 +20,7 @@ package org.matsim.core.mobsim.qsim.pt; import org.matsim.core.api.internal.MatsimFactory; +import org.matsim.core.mobsim.qsim.InternalInterface; import org.matsim.pt.Umlauf; /** @@ -27,6 +28,6 @@ */ public interface TransitDriverAgentFactory extends MatsimFactory { - AbstractTransitDriverAgent createTransitDriver(Umlauf umlauf); + AbstractTransitDriverAgent createTransitDriver(Umlauf umlauf, InternalInterface internalInterface, TransitStopAgentTracker transitStopAgentTracker); } diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitEngineModule.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitEngineModule.java index bcbcf85b57e..a6d75867864 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitEngineModule.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitEngineModule.java @@ -21,7 +21,15 @@ package org.matsim.core.mobsim.qsim.pt; +import com.google.inject.Inject; +import com.google.inject.Provider; +import com.google.inject.Provides; +import com.google.inject.Singleton; +import com.google.inject.multibindings.OptionalBinder; +import org.matsim.core.config.Config; +import org.matsim.core.gbl.Gbl; import org.matsim.core.mobsim.qsim.AbstractQSimModule; +import org.matsim.core.mobsim.qsim.QSim; import org.matsim.pt.ReconstructingUmlaufBuilder; import org.matsim.pt.UmlaufBuilder; @@ -42,5 +50,13 @@ protected void configureQSim() { bind( UmlaufBuilder.class ).to( ReconstructingUmlaufBuilder.class ); + OptionalBinder.newOptionalBinder(binder(), TransitDriverAgentFactory.class) + .setDefault().to( DefaultTransitDriverAgentFactory.class ); + } + + @Provides + @Singleton + public TransitStopAgentTracker transitStopAgentTracker(QSim qSim) { + return new TransitStopAgentTracker(qSim.getEventsManager()); } } diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitQSimEngine.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitQSimEngine.java index 190cd06be13..d0e04b20752 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitQSimEngine.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitQSimEngine.java @@ -54,7 +54,7 @@ * @author mrieser * @author mzilske */ -public class TransitQSimEngine implements DepartureHandler, MobsimEngine, AgentSource, HasAgentTracker { +public class TransitQSimEngine implements DepartureHandler, MobsimEngine, AgentSource, HasAgentTracker { private Collection ptDrivers; @@ -80,27 +80,32 @@ public TransitAgentTriesToTeleportException(String message) { private TransitStopHandlerFactory stopHandlerFactory = new SimpleTransitStopHandlerFactory(); - private TransitDriverAgentFactory transitDriverFactory; + private final TransitDriverAgentFactory transitDriverFactory; private InternalInterface internalInterface = null ; @Override public void setInternalInterface( InternalInterface internalInterface ) { this.internalInterface = internalInterface ; - transitDriverFactory = new DefaultTransitDriverAgentFactory(internalInterface, agentTracker); } TransitQSimEngine(QSim queueSimulation) { - this(queueSimulation, new SimpleTransitStopHandlerFactory(), new ReconstructingUmlaufBuilder(queueSimulation.getScenario()) ); + this(queueSimulation, new SimpleTransitStopHandlerFactory(), + new ReconstructingUmlaufBuilder(queueSimulation.getScenario()), + new TransitStopAgentTracker(queueSimulation.getEventsManager()), + new DefaultTransitDriverAgentFactory()); } @Inject - public TransitQSimEngine(QSim queueSimulation, TransitStopHandlerFactory stopHandlerFactory, UmlaufBuilder umlaufBuilder) { + public TransitQSimEngine(QSim queueSimulation, TransitStopHandlerFactory stopHandlerFactory, + UmlaufBuilder umlaufBuilder, TransitStopAgentTracker tracker, + TransitDriverAgentFactory transitDriverFactory) { this.qSim = queueSimulation; this.schedule = queueSimulation.getScenario().getTransitSchedule(); this.umlaufBuilder = umlaufBuilder; - this.agentTracker = new TransitStopAgentTracker(this.qSim.getEventsManager()); + this.agentTracker = tracker; this.stopHandlerFactory = stopHandlerFactory; + this.transitDriverFactory = transitDriverFactory; } // For tests (which create an Engine, and externally create Agents as well). @@ -154,7 +159,7 @@ private UmlaufCache getOrCreateUmlaufCache(final Scenario scenario) { private AbstractTransitDriverAgent createAndScheduleVehicleAndDriver(Umlauf umlauf, Vehicle vehicle) { TransitQVehicle veh = new TransitQVehicle(vehicle); - AbstractTransitDriverAgent driver = this.transitDriverFactory.createTransitDriver(umlauf); + AbstractTransitDriverAgent driver = this.transitDriverFactory.createTransitDriver(umlauf, internalInterface, agentTracker); veh.setDriver(driver); veh.setStopHandler(this.stopHandlerFactory.createTransitStopHandler(veh.getVehicle())); driver.setVehicle(veh); @@ -205,10 +210,6 @@ public void setTransitStopHandlerFactory(final TransitStopHandlerFactory stopHan this.stopHandlerFactory = stopHandlerFactory; } - public void setAbstractTransitDriverFactory(final TransitDriverAgentFactory abstractTransitDriverFactory) { - this.transitDriverFactory = abstractTransitDriverFactory; - } - @Override public void doSimStep(double time) { // Nothing to do here. diff --git a/matsim/src/main/java/org/matsim/core/network/io/NetworkWriter.java b/matsim/src/main/java/org/matsim/core/network/io/NetworkWriter.java index 9d02042583c..d8f7dc4e207 100644 --- a/matsim/src/main/java/org/matsim/core/network/io/NetworkWriter.java +++ b/matsim/src/main/java/org/matsim/core/network/io/NetworkWriter.java @@ -30,18 +30,18 @@ import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.IdentityTransformation; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.utils.objectattributes.AttributeConverter; import java.io.IOException; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.util.HashMap; import java.util.Map; public final class NetworkWriter extends MatsimXmlWriter implements MatsimWriter { - + private static final Logger log = LogManager.getLogger(NetworkWriter.class); - + private final Network network; private final CoordinateTransformation transformation; private final Map,AttributeConverter> converters = new HashMap<>(); diff --git a/matsim/src/main/java/org/matsim/core/population/PlanImpl.java b/matsim/src/main/java/org/matsim/core/population/PlanImpl.java index 9c8957cd480..8477a25b7dc 100644 --- a/matsim/src/main/java/org/matsim/core/population/PlanImpl.java +++ b/matsim/src/main/java/org/matsim/core/population/PlanImpl.java @@ -27,17 +27,22 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Customizable; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; +import org.matsim.core.replanning.inheritance.PlanInheritanceModule; import org.matsim.core.scenario.CustomizableUtils; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesImpl; /* deliberately package */ final class PlanImpl implements Plan { + private Id id= null; + private ArrayList actsLegs = new ArrayList<>(); private Double score = null; @@ -121,6 +126,44 @@ public String getType() { public void setType(final String type) { this.type = type; } + + @Override + public Id getId() { + if(this.id!=null) + return this.id; + else { + if(this.getAttributes().getAttribute(PlanInheritanceModule.PLAN_ID)!=null) + return Id.create(this.getAttributes().getAttribute(PlanInheritanceModule.PLAN_ID).toString(),Plan.class); + else return null; + } + + } + + @Override + public void setPlanId(Id planId) { + this.getAttributes().putAttribute(PlanInheritanceModule.PLAN_ID, planId.toString()); + this.id = planId; + } + + @Override + public int getIterationCreated() { + return (int) this.getAttributes().getAttribute(PlanInheritanceModule.ITERATION_CREATED); + } + + @Override + public void setIterationCreated(int iteration) { + this.getAttributes().putAttribute(PlanInheritanceModule.ITERATION_CREATED, iteration); + } + + @Override + public String getPlanMutator() { + return (String) this.getAttributes().getAttribute(PlanInheritanceModule.PLAN_MUTATOR); + } + + @Override + public void setPlanMutator(String planMutator) { + this.getAttributes().putAttribute(PlanInheritanceModule.PLAN_MUTATOR, planMutator); + } @Override public final List getPlanElements() { @@ -164,6 +207,8 @@ public final Map getCustomAttributes() { return this.customizableDelegate.getCustomAttributes(); } + + // public final void setLocked() { // for ( PlanElement pe : this.actsLegs ) { // if ( pe instanceof ActivityImpl ) { diff --git a/matsim/src/main/java/org/matsim/core/population/PopulationUtils.java b/matsim/src/main/java/org/matsim/core/population/PopulationUtils.java index cc26dd7608c..9a572ead6ca 100644 --- a/matsim/src/main/java/org/matsim/core/population/PopulationUtils.java +++ b/matsim/src/main/java/org/matsim/core/population/PopulationUtils.java @@ -24,6 +24,7 @@ import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; @@ -52,7 +53,7 @@ import org.matsim.api.core.v01.population.Route; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.PlansConfigGroup; import org.matsim.core.gbl.Gbl; import org.matsim.core.gbl.MatsimRandom; @@ -71,7 +72,6 @@ import org.matsim.core.scenario.MutableScenario; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.OptionalTime; import org.matsim.facilities.ActivityFacilities; import org.matsim.facilities.ActivityFacility; @@ -182,7 +182,7 @@ public String getRoutingMode() { public void setRoutingMode(String routingMode) { throw new UnsupportedOperationException() ; } - + @Override public Route getRoute() { // route should be unmodifiable. kai @@ -381,6 +381,36 @@ public String getType() { public void setType(String type) { throw new UnsupportedOperationException(); } + + @Override + public Id getId() { + return this.delegate.getId(); + } + + @Override + public void setPlanId(Id planId) { + throw new UnsupportedOperationException(); + } + + @Override + public int getIterationCreated() { + return this.delegate.getIterationCreated(); + } + + @Override + public void setIterationCreated(int iteration) { + throw new UnsupportedOperationException(); + } + + @Override + public String getPlanMutator() { + return this.delegate.getPlanMutator(); + } + + @Override + public void setPlanMutator(String planMutator) { + throw new UnsupportedOperationException(); + } @Override public void addLeg(Leg leg) { @@ -526,10 +556,10 @@ public static double calculateSimilarity(List legs1, List legs2, Netwo double sameModeReward, double sameRouteReward ) { // yyyy should be made configurable somehow (i.e. possibly not a static method any more). kai, apr'15 - // yy kwa points to: + // yy kwa points to: // Schüssler, N. and K.W. Axhausen (2009b) Accounting for similarities in destination choice modelling: A concept, paper presented at the 9th Swiss Transport Research Conference, Ascona, October 2009. - // und - // Joh, Chang-Hyeon, Theo A. Arentze and Harry J. P. Timmermans (2001). + // und + // Joh, Chang-Hyeon, Theo A. Arentze and Harry J. P. Timmermans (2001). // A Position-Sensitive Sequence Alignment Method Illustrated for Space-Time Activity-Diary Data¹, Environment and Planning A 33(2): 313­338. // Mahdieh Allahviranloo has some work on activity pattern similarity (iatbr'15) @@ -581,10 +611,10 @@ public static double calculateSimilarity(List activities1, List facilityId) { return getFactory().createInteractionActivityFromActivityFacilityId(type, facilityId); } - + public static Activity createActivityFromCoord(String type, Coord coord) { return getFactory().createActivityFromCoord(type, coord) ; } @@ -775,7 +805,7 @@ public static Activity createActivityFromCoord(String type, Coord coord) { public static Activity createInteractionActivityFromCoord(String type, Coord coord) { return getFactory().createInteractionActivityFromCoord(type, coord) ; } - + public static Activity createActivityFromCoordAndLinkId(String type, Coord coord, Id linkId) { Activity act = getFactory().createActivityFromCoord(type, coord) ; act.setLinkId(linkId); @@ -832,7 +862,7 @@ public static Activity createAndAddActivity(Plan plan, String type) { } public static Activity createStageActivityFromCoordLinkIdAndModePrefix(final Coord interactionCoord, final Id interactionLink, String modePrefix ) { - Activity act = createInteractionActivityFromCoordAndLinkId(PlanCalcScoreConfigGroup.createStageActivityType(modePrefix), interactionCoord, interactionLink); + Activity act = createInteractionActivityFromCoordAndLinkId(ScoringConfigGroup.createStageActivityType(modePrefix), interactionCoord, interactionLink); // act.setMaximumDuration(0.0); // obsolete since this is hard-coded in InteractionActivity return act; } @@ -849,7 +879,7 @@ public static void copyFromTo(final Plan in, final Plan out) { /* * By default 'false' to be backwards compatible. As a result, InteractionActivities will be converted to ActivityImpl. */ - copyFromTo(in, out, false); + copyFromTo(in, out, false); } public static void copyFromTo(final Plan in, final Plan out, final boolean withInteractionActivities) { diff --git a/matsim/src/main/java/org/matsim/core/population/algorithms/MutateActivityTimeAllocation.java b/matsim/src/main/java/org/matsim/core/population/algorithms/MutateActivityTimeAllocation.java new file mode 100644 index 00000000000..e658570f8ea --- /dev/null +++ b/matsim/src/main/java/org/matsim/core/population/algorithms/MutateActivityTimeAllocation.java @@ -0,0 +1,122 @@ +/* *********************************************************************** * + * project: org.matsim.* + * PlanMutateTimeAllocation.java + * * + * *********************************************************************** * + * * + * copyright : (C) 2007, 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.core.population.algorithms; + +import java.util.Random; + +import org.matsim.api.core.v01.population.Activity; +import org.matsim.api.core.v01.population.Leg; +import org.matsim.api.core.v01.population.Plan; +import org.matsim.api.core.v01.population.PlanElement; +import org.matsim.core.router.TripStructureUtils; +import org.matsim.core.router.TripStructureUtils.StageActivityHandling; + +/** + * Mutates the duration of activities randomly within a specified range. + * + * @author knagel, jbischoff + */ +public final class MutateActivityTimeAllocation implements PlanAlgorithm { + + + public static final String INITIAL_END_TIME_ATTRIBUTE = "initialEndTime"; + private final double mutationRange; + private final Random random; + private final boolean affectingDuration; + private final double latestActivityEndTime; + private final boolean mutateAroundInitialEndTimeOnly; + private final double mutationRangeStep; + + + public MutateActivityTimeAllocation(final double mutationRange, boolean affectingDuration, final Random random, double latestActivityEndTime, boolean mutateAroundInitialEndTimeOnly, double mutationRangeStep) { + this.mutationRange = mutationRange; + this.affectingDuration = affectingDuration; + this.random = random; + this.latestActivityEndTime = latestActivityEndTime; + this.mutateAroundInitialEndTimeOnly = mutateAroundInitialEndTimeOnly; + this.mutationRangeStep = Math.max(1.0,mutationRangeStep); + + } + + @Override + public void run(final Plan plan) { + for ( Activity act : TripStructureUtils.getActivities( plan , StageActivityHandling.ExcludeStageActivities ) ) { + if (act.getEndTime().isDefined()) { + double endTime = act.getEndTime().seconds(); + if (mutateAroundInitialEndTimeOnly){ + Object initialEndtime = act.getAttributes().getAttribute(INITIAL_END_TIME_ATTRIBUTE); + if (initialEndtime!=null) { + endTime = (double) initialEndtime; + } else { + act.getAttributes().putAttribute(INITIAL_END_TIME_ATTRIBUTE,endTime); + } + } + double newEndTime = Math.min(mutateTime(endTime, mutationRange),this.latestActivityEndTime); + act.setEndTime(newEndTime); + act.setStartTimeUndefined(); + } + else if ( affectingDuration ) { + if ( act.getMaximumDuration().isDefined()) { + act.setMaximumDuration(mutateTime(act.getMaximumDuration().seconds(), mutationRange)); + } + } + } + setLegDepartureTimes(plan); + + } + + private void setLegDepartureTimes(Plan plan) { + //setting leg departure times can only be an estimate and might be useful for certain dynamic modes. + //In general, it is best to trigger a reroute after mutating time. + double now = 0; + for (PlanElement planElement : plan.getPlanElements()){ + if (planElement instanceof Activity activity){ + if (activity.getEndTime().isDefined()){ + now = activity.getEndTime().seconds(); + } + else if (activity.getMaximumDuration().isDefined()){ + now = now + activity.getMaximumDuration().seconds(); + } + } else if (planElement instanceof Leg leg){ + if (leg.getDepartureTime().isDefined()) { + leg.setDepartureTime(now); + if (leg.getTravelTime().isDefined()) { + now = now + leg.getTravelTime().seconds(); + } + } + } + } + } + + private double mutateTime(final double time, double mutationRange) { + double t = time; + int mutationRangeBins = (int) Math.ceil( mutationRange/mutationRangeStep); + t = t - mutationRange + (2*this.random.nextInt(mutationRangeBins)*mutationRangeStep) ; + if (t < 0) { + t = 0; + } + // note that this also affects duration + return t; + } + + + +} diff --git a/matsim/src/main/java/org/matsim/core/population/algorithms/PlanMutateTimeAllocation.java b/matsim/src/main/java/org/matsim/core/population/algorithms/PlanMutateTimeAllocation.java deleted file mode 100644 index b078ed95700..00000000000 --- a/matsim/src/main/java/org/matsim/core/population/algorithms/PlanMutateTimeAllocation.java +++ /dev/null @@ -1,142 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PlanMutateTimeAllocation.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007, 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.core.population.algorithms; - -import java.util.List; -import java.util.Random; - -import org.matsim.api.core.v01.population.Activity; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Plan; -import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.core.utils.misc.OptionalTime; - -/** - * Mutates the duration of activities randomly within a specified range. - * For the first act, the end-time is mutated. For the last act, duration and end-time are set to UNDEFINED. - * For all other acts, the duration is mutated, and the end-time is updated accordingly. - * If an activity has no duration set (UNDEFINED_TIME), a random time between 0 and 24h will be chosen. - * Departure and arrival times of legs are updated according to the activity durations, but the - * leg travel time is not modified (e.g. updated according to new expected departure time). - * - * @author mrieser - */ -public final class PlanMutateTimeAllocation implements PlanAlgorithm { - - private final double mutationRange; - private final Random random; - - public PlanMutateTimeAllocation(final double mutationRange, final Random random) { - this.mutationRange = mutationRange; - this.random = random; - } - - @Override - public void run(final Plan plan) { - mutatePlan(plan); - } - - private void mutatePlan(final Plan plan) { - - List planElements = plan.getPlanElements(); - int max = planElements.size(); - - double now = 0; - - // apply mutation to all activities except the last home activity - for (int i = 0; i < max; i++) { - - PlanElement pe = planElements.get(i); - - if (pe instanceof Activity) { - Activity act = (Activity) pe; - - // handle first activity - if (i == 0) { - // set start to midnight - act.setStartTime(now); - // mutate the end time of the first activity - act.setEndTime(mutateTime(act.getEndTime())); - // calculate resulting duration - act.setMaximumDuration(act.getEndTime().seconds() - act.getStartTime().seconds()); - // move now pointer - now += act.getEndTime().seconds(); - - // handle middle activities - } else if (i < (max - 1)) { - - // assume that there will be no delay between arrival time and activity start time - act.setStartTime(now); - if (act.getMaximumDuration().isDefined()) { - // mutate the durations of all 'middle' activities - act.setMaximumDuration(mutateTime(act.getMaximumDuration())); - now += act.getMaximumDuration().seconds(); - // set end time accordingly - act.setEndTime(now); - } else { - double newEndTime = mutateTime(act.getEndTime()); - if (newEndTime < now) { - newEndTime = now; - } - act.setEndTime(newEndTime); - now = newEndTime; - } - // handle last activity - } else { - - // assume that there will be no delay between arrival time and activity start time - act.setStartTime(now); - // invalidate duration and end time because the plan will be interpreted 24 hour wrap-around - act.setMaximumDurationUndefined(); - act.setEndTimeUndefined(); - - } - - } else if (pe instanceof Leg) { - - Leg leg = (Leg) pe; - - // assume that there will be no delay between end time of previous activity and departure time - leg.setDepartureTime(now); - // let duration untouched. if defined add it to now - if (leg.getTravelTime().isDefined()) { - now += leg.getTravelTime().seconds(); - } - final double arrTime = now; - // set planned arrival time accordingly - leg.setTravelTime( arrTime - leg.getDepartureTime().seconds()); - - } - } - } - - private double mutateTime(final OptionalTime time) { - if (time.isDefined()) { - double t = time.seconds() + (int)((this.random.nextDouble() * 2.0 - 1.0) * this.mutationRange); - if (t < 0) t = 0; - if (t > 24*3600) t = 24*3600; - return t; - } else { - return this.random.nextInt(24*3600); - } - } - -} diff --git a/matsim/src/main/java/org/matsim/core/population/algorithms/PlanMutateTimeAllocationSimplified.java b/matsim/src/main/java/org/matsim/core/population/algorithms/PlanMutateTimeAllocationSimplified.java deleted file mode 100644 index 7e4434a9f94..00000000000 --- a/matsim/src/main/java/org/matsim/core/population/algorithms/PlanMutateTimeAllocationSimplified.java +++ /dev/null @@ -1,96 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PlanMutateTimeAllocation.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007, 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.core.population.algorithms; - -import java.util.Random; - -import org.matsim.api.core.v01.population.Activity; -import org.matsim.api.core.v01.population.Plan; -import org.matsim.core.router.TripStructureUtils; -import org.matsim.core.router.TripStructureUtils.StageActivityHandling; - -/** - * Mutates the duration of activities randomly within a specified range. - *
    - * Other than the "full" version, this version just mutates activity end time and activity duration if they are defined, - * without thinking any further. If this produces invalid plans, they will eventually be removed through the selection - * process. kai, jun'12 - * - * @author knagel - */ -public final class PlanMutateTimeAllocationSimplified implements PlanAlgorithm { - - private final StageActivityHandling stageActivityHandling; - private final double mutationRange; - private final Random random; - private final boolean affectingDuration; - - /** - * Initializes an instance mutating all activities in a plan - * @param mutationRange - * @param affectingDuration - * @param random - */ - public PlanMutateTimeAllocationSimplified(final double mutationRange, boolean affectingDuration, final Random random) { - this( StageActivityHandling.StagesAsNormalActivities , mutationRange , affectingDuration, random ); - } - /** - * Initializes an instance mutating all non-stage activities in a plan - * @param mutationRange - * @param affectingDuration - * @param random - */ - public PlanMutateTimeAllocationSimplified(final StageActivityHandling stageActivityHandling, final double mutationRange, boolean affectingDuration, final Random random) { - this.stageActivityHandling = stageActivityHandling; - this.mutationRange = mutationRange; - this.affectingDuration = affectingDuration; - this.random = random; - } - - @Override - public void run(final Plan plan) { - for ( Activity act : TripStructureUtils.getActivities( plan , stageActivityHandling ) ) { - // this is deliberately simplistic. Cleanup up of the time information should be done somewhere else. - if (act.getEndTime().isDefined()) { - act.setEndTime(mutateTime(act.getEndTime().seconds())); - } - if ( affectingDuration ) { - if ( act.getMaximumDuration().isDefined()) { - act.setMaximumDuration(mutateTime(act.getMaximumDuration().seconds())); - } - } - } - // the legs are not doing anything. kai, jun'12 - } - - private double mutateTime(final double time) { - double t = time; - t = t + (int)((this.random.nextDouble() * 2.0 - 1.0) * this.mutationRange); - - if (t < 0) { - t = 0; - } - // note that this also affects duration - - return t; - } - -} diff --git a/matsim/src/main/java/org/matsim/core/population/algorithms/TripPlanMutateTimeAllocation.java b/matsim/src/main/java/org/matsim/core/population/algorithms/TripPlanMutateTimeAllocation.java index b9e5ed82d7d..05940f1c8bd 100644 --- a/matsim/src/main/java/org/matsim/core/population/algorithms/TripPlanMutateTimeAllocation.java +++ b/matsim/src/main/java/org/matsim/core/population/algorithms/TripPlanMutateTimeAllocation.java @@ -69,12 +69,11 @@ public TripPlanMutateTimeAllocation(final double mutationRange, final boolean af this.mutationRange = mutationRange; this.affectingDuration = affectingDuration; this.random = random; -// this.subpopulationAttribute = subpopulationAttribute; this.subpopulationMutationRanges = subpopulationMutationRanges; this.subpopulationAffectingDuration = subpopulationAffectingDuration; this.latestEndTime = latestEndTime; } - + @Override public void run(final Plan plan) { mutatePlan(plan); @@ -89,12 +88,11 @@ private void mutatePlan(final Plan plan) { final String subpopulation = this.getSubpopulation(plan); final boolean affectingDuration = this.isAffectingDuration(subpopulation); final double mutationRange = this.getMutationRange(subpopulation); - + // apply mutation to all activities except the last home activity for (PlanElement pe : plan.getPlanElements()) { - if (pe instanceof Activity) { - Activity act = (Activity)pe; + if (pe instanceof Activity act) { // handle first activity if (isFirst) { @@ -124,7 +122,7 @@ private void mutatePlan(final Plan plan) { } now += act.getMaximumDuration().seconds(); // (may feel a bit disturbing since it was not mutated but it is just using the "old" value which is perfectly ok. kai, jan'14) - + // set end time accordingly act.setEndTime(now); } else { @@ -191,30 +189,28 @@ private double mutateTime(final OptionalTime time, final double mutationRange) { public void setUseActivityDurations(final boolean useActivityDurations) { this.useActivityDurations = useActivityDurations; } - - private final String getSubpopulation(final Plan plan) { -// if (this.subpopulationAttribute == null) return null; + + private String getSubpopulation(final Plan plan) { if (plan.getPerson() == null) return null; -// return (String) PopulationUtils.getPersonAttribute(plan.getPerson(), this.subpopulationAttribute); return PopulationUtils.getSubpopulation( plan.getPerson() ); } - - private final boolean isAffectingDuration(final String subpopulation) { + + private boolean isAffectingDuration(final String subpopulation) { if (subpopulation != null) { Boolean isAffectingDuration = this.subpopulationAffectingDuration.get(subpopulation); if (isAffectingDuration != null) return isAffectingDuration.booleanValue(); } - + // fallback solution: no subpopulation attribute was found return this.affectingDuration; } - - private final double getMutationRange(final String subpopulation) { + + private double getMutationRange(final String subpopulation) { if (subpopulation != null) { Double mutationRange = this.subpopulationMutationRanges.get(subpopulation); if (mutationRange != null) return mutationRange.doubleValue(); } - + // fallback solution: no subpopulation attribute was found return this.mutationRange; } diff --git a/matsim/src/main/java/org/matsim/core/population/io/AbstractPopulationWriterHandler.java b/matsim/src/main/java/org/matsim/core/population/io/AbstractPopulationWriterHandler.java index 9208db8e875..95a99b66e50 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/AbstractPopulationWriterHandler.java +++ b/matsim/src/main/java/org/matsim/core/population/io/AbstractPopulationWriterHandler.java @@ -77,7 +77,6 @@ else if (pe instanceof Leg) { } this.endPerson(writer); this.writeSeparator(writer); - writer.flush(); } public abstract void startPerson(final Person person, final BufferedWriter out) throws IOException; diff --git a/matsim/src/main/java/org/matsim/core/population/io/ParallelPopulationWriterHandlerV6.java b/matsim/src/main/java/org/matsim/core/population/io/ParallelPopulationWriterHandlerV6.java index c8755ed431d..975a926db40 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/ParallelPopulationWriterHandlerV6.java +++ b/matsim/src/main/java/org/matsim/core/population/io/ParallelPopulationWriterHandlerV6.java @@ -29,7 +29,6 @@ import org.matsim.core.router.TripStructureUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.Counter; import org.matsim.core.utils.misc.Time; import org.matsim.utils.objectattributes.AttributeConverter; @@ -41,6 +40,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -152,10 +152,10 @@ private void joinThreads() { } // pass on potential exceptions if (runnerException != null) { - throw new UncheckedIOException(runnerException); + throw new UncheckedIOException(new IOException(runnerException)); } if (writerException != null) { - throw new UncheckedIOException(writerException); + throw new UncheckedIOException(new IOException(writerException)); } } diff --git a/matsim/src/main/java/org/matsim/core/population/io/PopulationReaderMatsimV5.java b/matsim/src/main/java/org/matsim/core/population/io/PopulationReaderMatsimV5.java index b3a6fbf06c2..ccd67415f17 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/PopulationReaderMatsimV5.java +++ b/matsim/src/main/java/org/matsim/core/population/io/PopulationReaderMatsimV5.java @@ -269,9 +269,9 @@ private void finishLastRoute() { Coord toCoord = getCoord(this.curract); if (fromCoord != null && toCoord != null) { double dist = CoordUtils.calcEuclideanDistance(fromCoord, toCoord); - if ( this.scenario.getConfig().plansCalcRoute(). + if ( this.scenario.getConfig().routing(). getModeRoutingParams().containsKey( this.currleg.getMode() ) ) { - double estimatedNetworkDistance = dist * this.scenario.getConfig().plansCalcRoute(). + double estimatedNetworkDistance = dist * this.scenario.getConfig().routing(). getModeRoutingParams().get( this.currleg.getMode() ).getBeelineDistanceFactor() ; this.currRoute.setDistance(estimatedNetworkDistance); } @@ -376,9 +376,9 @@ private void endRoute(final String content) { Coord toCoord = getCoord(this.curract); if (fromCoord != null && toCoord != null) { double dist = CoordUtils.calcEuclideanDistance(fromCoord, toCoord); - if ( this.scenario.getConfig().plansCalcRoute(). + if ( this.scenario.getConfig().routing(). getModeRoutingParams().containsKey( this.currleg.getMode() ) ) { - double estimatedNetworkDistance = dist * this.scenario.getConfig().plansCalcRoute(). + double estimatedNetworkDistance = dist * this.scenario.getConfig().routing(). getModeRoutingParams().get( this.currleg.getMode() ).getBeelineDistanceFactor() ; this.currRoute.setDistance(estimatedNetworkDistance); } diff --git a/matsim/src/main/java/org/matsim/core/population/io/PopulationReaderMatsimV6.java b/matsim/src/main/java/org/matsim/core/population/io/PopulationReaderMatsimV6.java index dfbd02452d7..725ffb83654 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/PopulationReaderMatsimV6.java +++ b/matsim/src/main/java/org/matsim/core/population/io/PopulationReaderMatsimV6.java @@ -396,9 +396,9 @@ private void finishLastRoute() { Coord toCoord = getCoord(this.curract); if (fromCoord != null && toCoord != null) { double dist = CoordUtils.calcEuclideanDistance(fromCoord, toCoord); - if ( this.scenario.getConfig().plansCalcRoute(). + if ( this.scenario.getConfig().routing(). getModeRoutingParams().containsKey( this.currleg.getMode() ) ) { - double estimatedNetworkDistance = dist * this.scenario.getConfig().plansCalcRoute(). + double estimatedNetworkDistance = dist * this.scenario.getConfig().routing(). getModeRoutingParams().get( this.currleg.getMode() ).getBeelineDistanceFactor() ; this.currRoute.setDistance(estimatedNetworkDistance); } @@ -507,9 +507,9 @@ private void endRoute(final String content) { Coord toCoord = getCoord(this.curract); if (fromCoord != null && toCoord != null) { double dist = CoordUtils.calcEuclideanDistance(fromCoord, toCoord); - if ( this.scenario.getConfig().plansCalcRoute(). + if ( this.scenario.getConfig().routing(). getModeRoutingParams().containsKey( this.currleg.getMode() ) ) { - double estimatedNetworkDistance = dist * this.scenario.getConfig().plansCalcRoute(). + double estimatedNetworkDistance = dist * this.scenario.getConfig().routing(). getModeRoutingParams().get( this.currleg.getMode() ).getBeelineDistanceFactor() ; this.currRoute.setDistance(estimatedNetworkDistance); } diff --git a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriter.java b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriter.java index 827eeed3ee3..71fbd029550 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriter.java +++ b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriter.java @@ -22,6 +22,7 @@ import java.io.IOException; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.util.HashMap; import java.util.Map; @@ -36,7 +37,6 @@ import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.IdentityTransformation; import org.matsim.core.utils.io.AbstractMatsimWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.Counter; import org.matsim.utils.FeatureFlags; import org.matsim.utils.objectattributes.AttributeConverter; diff --git a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV0.java b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV0.java index 0009ba521e6..057684fb2f6 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV0.java +++ b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV0.java @@ -75,6 +75,7 @@ public void startPlans(final Population plans, final BufferedWriter out) throws @Override public void endPlans(final BufferedWriter out) throws IOException { out.write("\n"); + out.flush(); } ////////////////////////////////////////////////////////////////////// diff --git a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV4.java b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV4.java index 493ec680d06..c66dd9f57cc 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV4.java +++ b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV4.java @@ -82,6 +82,7 @@ public void startPlans(final Population plans, final BufferedWriter out) throws @Override public void endPlans(final BufferedWriter out) throws IOException { out.write("\n"); + out.flush(); } ////////////////////////////////////////////////////////////////////// diff --git a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV5.java b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV5.java index 7d1c42fe0b9..5ca46309074 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV5.java +++ b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV5.java @@ -99,12 +99,12 @@ else if (pe instanceof Leg) { } PopulationWriterHandlerImplV5.endPerson(out); this.writeSeparator(out); - out.flush(); } @Override public void endPlans(final BufferedWriter out) throws IOException { out.write("\n"); + out.flush(); } private static void startPerson(final Person person, final BufferedWriter out) throws IOException { diff --git a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV6.java b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV6.java index 67ff8fada0a..7d23d6c976a 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV6.java +++ b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandlerImplV6.java @@ -119,12 +119,12 @@ else if (pe instanceof Leg) { } PopulationWriterHandlerImplV6.endPerson(out); this.writeSeparator(out); - out.flush(); } @Override public void endPlans(final BufferedWriter out) throws IOException { out.write("\n"); + out.flush(); } private void startPerson(final Person person, final BufferedWriter out) throws IOException { diff --git a/matsim/src/main/java/org/matsim/core/population/io/StreamingPopulationWriter.java b/matsim/src/main/java/org/matsim/core/population/io/StreamingPopulationWriter.java index 9f9d24ff438..09710e5a20d 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/StreamingPopulationWriter.java +++ b/matsim/src/main/java/org/matsim/core/population/io/StreamingPopulationWriter.java @@ -31,7 +31,6 @@ import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.IdentityTransformation; import org.matsim.core.utils.io.AbstractMatsimWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.Counter; import org.matsim.utils.objectattributes.AttributeConverter; import org.matsim.utils.objectattributes.attributable.Attributes; @@ -39,6 +38,7 @@ import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.HashMap; import java.util.Map; diff --git a/matsim/src/main/java/org/matsim/core/replanning/GenericPlanStrategyImpl.java b/matsim/src/main/java/org/matsim/core/replanning/GenericPlanStrategyImpl.java index db83e5d4749..b9063b0878d 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/GenericPlanStrategyImpl.java +++ b/matsim/src/main/java/org/matsim/core/replanning/GenericPlanStrategyImpl.java @@ -22,6 +22,7 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.population.BasicPlan; import org.matsim.api.core.v01.population.HasPlansAndId; +import org.matsim.api.core.v01.population.Plan; import org.matsim.core.replanning.modules.GenericPlanStrategyModule; import org.matsim.core.replanning.selectors.PlanSelector; import org.matsim.core.replanning.selectors.RandomUnscoredPlanSelector; @@ -92,6 +93,13 @@ public void run(final HasPlansAndId person) { // set the working plan to a copy of the selected plan: plan = person.createCopyOfSelectedPlanAndMakeSelected(); + //Id is only set inside planInheritance -> if null planInheritance is disabled + if (plan instanceof Plan && ((Plan) plan).getId() != null) { + // add plan inheritance flags + ((Plan) plan).setIterationCreated(this.replanningContext.getIteration()); + ((Plan) plan).setPlanMutator(this.toString()); + } + // add new plan to container that contains the plans that are handled by this PlanStrategy: this.plans.add(plan); diff --git a/matsim/src/main/java/org/matsim/core/replanning/StrategyManager.java b/matsim/src/main/java/org/matsim/core/replanning/StrategyManager.java index d00190b72e4..1b8b31473d8 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/StrategyManager.java +++ b/matsim/src/main/java/org/matsim/core/replanning/StrategyManager.java @@ -26,8 +26,8 @@ import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.core.api.internal.MatsimManager; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.replanning.choosers.StrategyChooser; import org.matsim.core.replanning.selectors.PlanSelector; import org.matsim.core.replanning.selectors.WorstPlanForRemovalSelector; @@ -65,20 +65,20 @@ public class StrategyManager implements MatsimManager { private final GenericStrategyManagerImpl delegate; @Inject - StrategyManager( StrategyConfigGroup strategyConfigGroup, - ControlerConfigGroup controlerConfigGroup, StrategyChooser strategyChooser, - Map planStrategies ) { + StrategyManager(ReplanningConfigGroup replanningConfigGroup, + ControllerConfigGroup controllerConfigGroup, StrategyChooser strategyChooser, + Map planStrategies ) { this(strategyChooser); - setMaxPlansPerAgent(strategyConfigGroup.getMaxAgentPlanMemorySize()); + setMaxPlansPerAgent(replanningConfigGroup.getMaxAgentPlanMemorySize()); - int globalInnovationDisableAfter = (int) ((controlerConfigGroup.getLastIteration() - controlerConfigGroup.getFirstIteration()) - * strategyConfigGroup.getFractionOfIterationsToDisableInnovation() + controlerConfigGroup.getFirstIteration()); + int globalInnovationDisableAfter = (int) ((controllerConfigGroup.getLastIteration() - controllerConfigGroup.getFirstIteration()) + * replanningConfigGroup.getFractionOfIterationsToDisableInnovation() + controllerConfigGroup.getFirstIteration()); log.info("global innovation switch off after iteration: " + globalInnovationDisableAfter); - for (Map.Entry entry : planStrategies.entrySet()) { + for (Map.Entry entry : planStrategies.entrySet()) { PlanStrategy strategy = entry.getValue(); - StrategyConfigGroup.StrategySettings settings = entry.getKey(); + ReplanningConfigGroup.StrategySettings settings = entry.getKey(); addStrategy(strategy, settings.getSubpopulation(), settings.getWeight()); // now check if this modules should be disabled after some iterations @@ -90,7 +90,7 @@ public class StrategyManager implements MatsimManager { } if (maxIter >= 0) { - if (maxIter >= controlerConfigGroup.getFirstIteration()) { + if (maxIter >= controllerConfigGroup.getFirstIteration()) { addChangeRequest(maxIter + 1, strategy, settings.getSubpopulation(), 0.0); } else { /* The services starts at a later iteration than this change request is scheduled for. diff --git a/matsim/src/main/java/org/matsim/core/replanning/StrategyManagerModule.java b/matsim/src/main/java/org/matsim/core/replanning/StrategyManagerModule.java index 6ce4eba984b..d42fde9fabe 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/StrategyManagerModule.java +++ b/matsim/src/main/java/org/matsim/core/replanning/StrategyManagerModule.java @@ -30,7 +30,7 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -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.OutputDirectoryHierarchy; import org.matsim.core.replanning.choosers.StrategyChooser; @@ -55,11 +55,11 @@ public void install() { bind(new TypeLiteral>() {}).to(new TypeLiteral>() {}).asEagerSingleton(); bind(ReplanningContext.class).to(ReplanningContextImpl.class).asEagerSingleton(); - MapBinder planStrategyMapBinder = MapBinder.newMapBinder(binder(), StrategyConfigGroup.StrategySettings.class, PlanStrategy.class); + MapBinder planStrategyMapBinder = MapBinder.newMapBinder(binder(), ReplanningConfigGroup.StrategySettings.class, PlanStrategy.class); // (this will bind a Map that has StrategySettings as key, and PlanStrategy as value. Not sure why StrategySettings as key, and not just the name, but possibly this is mean to allow adding // the same strategy multiple times, with possibly different settings.) - for (StrategyConfigGroup.StrategySettings settings : getConfig().strategy().getStrategySettings()) { + for (ReplanningConfigGroup.StrategySettings settings : getConfig().replanning().getStrategySettings()) { String name = settings.getStrategyName() ; if (name.equals("ExternalModule")) { // plan strategy is some external executable: diff --git a/matsim/src/main/java/org/matsim/core/replanning/annealing/ReplanningAnnealer.java b/matsim/src/main/java/org/matsim/core/replanning/annealing/ReplanningAnnealer.java index 19ec1cc810e..b576833d9fd 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/annealing/ReplanningAnnealer.java +++ b/matsim/src/main/java/org/matsim/core/replanning/annealing/ReplanningAnnealer.java @@ -30,7 +30,7 @@ import org.matsim.api.core.v01.population.Plan; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.events.IterationStartsEvent; import org.matsim.core.controler.events.StartupEvent; @@ -91,9 +91,9 @@ public void notifyStartup(StartupEvent event) { this.currentValues.put(av.getAnnealParameter(), av.getStartValue()); header.add(av.getAnnealParameter().name()); if (av.getAnnealParameter().equals(AnnealParameterOption.globalInnovationRate)) { - header.addAll(this.config.strategy().getStrategySettings().stream() + header.addAll(this.config.replanning().getStrategySettings().stream() .filter(s -> Objects.equals(av.getDefaultSubpopulation(), s.getSubpopulation())) - .map(StrategyConfigGroup.StrategySettings::getStrategyName) + .map(ReplanningConfigGroup.StrategySettings::getStrategyName) .collect(Collectors.toList())); } } else { // if disabled, better remove it @@ -112,7 +112,7 @@ public void notifyStartup(StartupEvent event) { @Override public void notifyIterationStarts(IterationStartsEvent event) { - this.currentIter = event.getIteration() - this.config.controler().getFirstIteration(); + this.currentIter = event.getIteration() - this.config.controller().getFirstIteration(); Map annealStats = new HashMap<>(); for (AnnealingVariable av : this.saConfig.getAnnealingVariables().values()) { if (this.currentIter > 0) { @@ -140,7 +140,7 @@ public void notifyIterationStarts(IterationStartsEvent event) { break; case linear: double slope = (av.getStartValue() - av.getEndValue()) - / (this.config.controler().getFirstIteration() - this.innovationStop); + / (this.config.controller().getFirstIteration() - this.innovationStop); this.currentValues.compute(av.getAnnealParameter(), (k, v) -> this.currentIter * slope + av.getStartValue()); break; @@ -180,13 +180,13 @@ private void writeIterationstats(int currentIter, Map annealStat private void anneal(IterationStartsEvent event, AnnealingVariable av, double annealValue, Map annealStats) { switch (av.getAnnealParameter()) { case BrainExpBeta: - this.config.planCalcScore().setBrainExpBeta(annealValue); + this.config.scoring().setBrainExpBeta(annealValue); break; case PathSizeLogitBeta: - this.config.planCalcScore().setPathSizeLogitBeta(annealValue); + this.config.scoring().setPathSizeLogitBeta(annealValue); break; case learningRate: - this.config.planCalcScore().setLearningRate(annealValue); + this.config.scoring().setLearningRate(annealValue); break; case globalInnovationRate: if (this.currentIter > this.innovationStop) { @@ -195,7 +195,7 @@ private void anneal(IterationStartsEvent event, AnnealingVariable av, double ann List annealValues = annealReplanning(annealValue, event.getServices().getStrategyManager(), av.getDefaultSubpopulation()); int i = 0; - for (StrategyConfigGroup.StrategySettings ss : this.config.strategy().getStrategySettings()) { + for (ReplanningConfigGroup.StrategySettings ss : this.config.replanning().getStrategySettings()) { if (Objects.equals(ss.getSubpopulation(), av.getDefaultSubpopulation())) { annealStats.put(ss.getStrategyName(), String.format(Locale.US, "%.4f", annealValues.get(i))); i++; @@ -262,9 +262,9 @@ private double getStrategyWeights(Config config, String subpopulation, StratType if (this.currentIter == this.innovationStop + 1 && stratType.equals(StratType.allInnovation)) { return 0.0; } - Collection strategies = config.strategy().getStrategySettings(); + Collection strategies = config.replanning().getStrategySettings(); double totalWeights = 0.0; - for (StrategyConfigGroup.StrategySettings strategy : strategies) { + for (ReplanningConfigGroup.StrategySettings strategy : strategies) { if (Objects.equals(strategy.getSubpopulation(), subpopulation)) { switch (stratType) { case allSelectors: @@ -289,12 +289,12 @@ private double getStrategyWeights(Config config, String subpopulation, StratType } private int getInnovationStop(Config config) { - int globalInnovationDisableAfter = (int) ((config.controler().getLastIteration() - config.controler().getFirstIteration()) - * config.strategy().getFractionOfIterationsToDisableInnovation() + config.controler().getFirstIteration()); + int globalInnovationDisableAfter = (int) ((config.controller().getLastIteration() - config.controller().getFirstIteration()) + * config.replanning().getFractionOfIterationsToDisableInnovation() + config.controller().getFirstIteration()); int innoStop = -1; - for (StrategyConfigGroup.StrategySettings strategy : config.strategy().getStrategySettings()) { + for (ReplanningConfigGroup.StrategySettings strategy : config.replanning().getStrategySettings()) { // check if this modules should be disabled after some iterations int maxIter = strategy.getDisableAfter(); if ((maxIter > globalInnovationDisableAfter || maxIter == -1) && isInnovationStrategy(strategy.getStrategyName())) { @@ -312,20 +312,20 @@ private int getInnovationStop(Config config) { } } - return Math.min(innoStop, config.controler().getLastIteration()); + return Math.min(innoStop, config.controller().getLastIteration()); } private void checkAndFixStartValue(ReplanningAnnealerConfigGroup.AnnealingVariable av, StartupEvent event) { double configValue; switch (av.getAnnealParameter()) { case BrainExpBeta: - configValue = this.config.planCalcScore().getBrainExpBeta(); + configValue = this.config.scoring().getBrainExpBeta(); break; case PathSizeLogitBeta: - configValue = this.config.planCalcScore().getPathSizeLogitBeta(); + configValue = this.config.scoring().getPathSizeLogitBeta(); break; case learningRate: - configValue = this.config.planCalcScore().getLearningRate(); + configValue = this.config.scoring().getLearningRate(); break; case globalInnovationRate: double innovationWeights = getStrategyWeights(this.config, av.getDefaultSubpopulation(), StratType.allInnovation); @@ -362,8 +362,8 @@ private void rescaleStartupWeights(double innovationStartValue, Config config, S stratMan.changeWeightOfStrategy(strategy, subpopulation, weight); } // adapt also in config for the record - Collection strategiesConfig = config.strategy().getStrategySettings(); - for (StrategyConfigGroup.StrategySettings strategy : strategiesConfig) { + Collection strategiesConfig = config.replanning().getStrategySettings(); + for (ReplanningConfigGroup.StrategySettings strategy : strategiesConfig) { if (Objects.equals(strategy.getSubpopulation(), subpopulation)) { double weight = strategy.getWeight(); if (isInnovationStrategy(strategy.toString())) { diff --git a/matsim/src/main/java/org/matsim/core/replanning/annealing/ReplanningAnnealerConfigGroup.java b/matsim/src/main/java/org/matsim/core/replanning/annealing/ReplanningAnnealerConfigGroup.java index bf63bb63384..c3a9421862f 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/annealing/ReplanningAnnealerConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/replanning/annealing/ReplanningAnnealerConfigGroup.java @@ -30,7 +30,7 @@ public class ReplanningAnnealerConfigGroup extends ReflectiveConfigGroup { - public static final String GROUP_NAME = "ReplanningAnnealer"; + public static final String GROUP_NAME = "replanningAnnealer"; private static final String ACTIVATE_ANNEALING_MODULE = "activateAnnealingModule"; private boolean activateAnnealingModule = false; @@ -227,4 +227,4 @@ public Map getComments() { } } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceModule.java b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceModule.java new file mode 100644 index 00000000000..0a0a48f961d --- /dev/null +++ b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceModule.java @@ -0,0 +1,269 @@ +package org.matsim.core.replanning.inheritance; + +/* *********************************************************************** * + * project: org.matsim.* + * ParallelPopulationReaderMatsimV6.java + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 java.io.BufferedWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.population.Person; +import org.matsim.api.core.v01.population.Plan; +import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; +import org.matsim.core.controler.AbstractModule; +import org.matsim.core.controler.events.BeforeMobsimEvent; +import org.matsim.core.controler.events.ShutdownEvent; +import org.matsim.core.controler.events.StartupEvent; +import org.matsim.core.controler.listener.BeforeMobsimListener; +import org.matsim.core.controler.listener.ShutdownListener; +import org.matsim.core.controler.listener.StartupListener; +import org.matsim.core.population.PersonUtils; +import org.matsim.core.replanning.GenericPlanStrategy; +import org.matsim.core.replanning.StrategyManager; +import org.matsim.core.utils.io.IOUtils; + +import com.google.inject.Singleton; + +/** + * The core plan inheritance module responsible for + *
  • Initialization of initially read plans and default writers + *
  • Book-keeping, i.e. setting additional plan attributes not stored in the plan itself + *
  • Calculation default stats like the distribution of mutators among (selected) plans + * + * @author neuma, alex94263 + */ +@Singleton +public class PlanInheritanceModule extends AbstractModule implements StartupListener, BeforeMobsimListener, ShutdownListener { + + public static final String PLAN_ID = "planId"; + public static final String ITERATION_CREATED = "iterationCreated"; + public static final String PLAN_MUTATOR = "planMutator"; + + public static final String INITIAL_PLAN = "initialPlan"; + public static final String NONE = "NONE"; + + public static final String FILENAME_PLAN_INHERITANCE_RECORDS = "planInheritanceRecords"; + + long numberOfPlanInheritanceRecordsCreated = 0; + Map, PlanInheritanceRecord> planId2planInheritanceRecords = new ConcurrentHashMap<>(); + + PlanInheritanceRecordWriter planInheritanceRecordWriter; + private ArrayList strategies; + + private final Character DELIMITER = '\t'; + private BufferedWriter selectedPlanStrategyShareWriter; + private BufferedWriter planStrategyShareWriter; + + @Override + public void notifyStartup(StartupEvent event) { + // initialize all default writers + CompressionType compressionType = event.getServices().getConfig().controller().getCompressionType(); + this.planInheritanceRecordWriter = new PlanInheritanceRecordWriter(event.getServices().getControlerIO().getOutputFilename(FILENAME_PLAN_INHERITANCE_RECORDS + ".csv", compressionType)); + this.strategies = this.getActiveStrategies(event.getServices().getConfig().replanning().getStrategySettings(), event.getServices().getStrategyManager()); + this.selectedPlanStrategyShareWriter = this.initializeDistributionWriter(this.strategies, event.getServices().getControlerIO().getOutputFilename(FILENAME_PLAN_INHERITANCE_RECORDS + "_shares_selected.csv")); + this.planStrategyShareWriter = this.initializeDistributionWriter(this.strategies, event.getServices().getControlerIO().getOutputFilename(FILENAME_PLAN_INHERITANCE_RECORDS + "_shares.csv")); + + // reset all plan attributes that might be present from a previously performed matsim run + for (Person person : event.getServices().getScenario().getPopulation().getPersons().values()) { + for (Plan plan : person.getPlans()) { + plan.setPlanId(Id.create(NONE, Plan.class)); + plan.setPlanMutator(INITIAL_PLAN); + plan.setIterationCreated(0); + } + } + } + + /** + * Retrieve all active plan strategies with their correct name in alphabetical order + */ + private ArrayList getActiveStrategies(Collection strategySettings, StrategyManager strategyManager) { + Set activeSubpopulations = new HashSet<>(); + for (StrategySettings strategySetting : strategySettings) { + activeSubpopulations.add(strategySetting.getSubpopulation()); + } + + Set planStrategiesNames = new HashSet<>(); + for (String subpopulation : activeSubpopulations) { + for (GenericPlanStrategy planStrategy : strategyManager.getStrategies(subpopulation)) { + planStrategiesNames.add(planStrategy.toString()); + } + } + + ArrayList strategies = new ArrayList<>(planStrategiesNames.size() + 1); + strategies.addAll(planStrategiesNames); + Collections.sort(strategies); + strategies.add(0, INITIAL_PLAN); + + return strategies; + } + + /** + * Initialize the writer with the active strategies + */ + private BufferedWriter initializeDistributionWriter(ArrayList strategies, String filename) { + + BufferedWriter planStrategyShareWriter = IOUtils.getBufferedWriter(filename); + + StringBuffer header = new StringBuffer(); + header.append("iteration"); header.append(DELIMITER); + for (int i = 0; i < strategies.size(); i++) { + if (i > 0) { + header.append(DELIMITER); + } + header.append(strategies.get(i)); + } + + try { + planStrategyShareWriter.write(header.toString()); + planStrategyShareWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException("Could not initialize the plan strategy share writer!", e); + } + + return planStrategyShareWriter; + } + + @Override + public void notifyBeforeMobsim(BeforeMobsimEvent event) { + // check the plans of the population and all currently stored plan records - do the actual book-keeping + + Set> activePlanIds = new HashSet<>(); + Set> selectedPlanIds = new HashSet<>(); + + for (Person person : event.getServices().getScenario().getPopulation().getPersons().values()) { + for (Plan plan : person.getPlans()) { + + if (plan.getPlanMutator() == null) { + // initial plan - set initial plan defaults + plan.setPlanMutator(INITIAL_PLAN); + plan.setIterationCreated(event.getIteration()); + } + + if (plan.getIterationCreated() == event.getIteration()) { + // it's a new plan created in this iteration - create a new record + + PlanInheritanceRecord planInheritanceRecord = new PlanInheritanceRecord(); + planInheritanceRecord.setAgentId(person.getId()); + planInheritanceRecord.setPlanId(Id.create(Long.toString(++this.numberOfPlanInheritanceRecordsCreated, 36), Plan.class)); + planInheritanceRecord.setAncestorId(plan.getId()); //works because new plan is copy of old selected and attributes are copied -> thus current attribute plan id is old selected plan id + plan.setPlanId(planInheritanceRecord.getPlanId()); + planInheritanceRecord.setIterationCreated(plan.getIterationCreated()); + planInheritanceRecord.setMutatedBy(plan.getPlanMutator()); + + this.planId2planInheritanceRecords.put(planInheritanceRecord.getPlanId(), planInheritanceRecord); + } + + if (PersonUtils.isSelected(plan)) { + this.planId2planInheritanceRecords.get(plan.getId()).getIterationsSelected().add(event.getIteration()); + selectedPlanIds.add(plan.getId()); + } + + activePlanIds.add(plan.getId()); + } + } + + List> deletedPlans = new ArrayList<>(); + for (Id planId : this.planId2planInheritanceRecords.keySet()) { + if (!activePlanIds.contains(planId)) { + deletedPlans.add(planId); + } + } + + for (Id deletedPlanId : deletedPlans) { + PlanInheritanceRecord deletedPlanInheritanceRecord = this.planId2planInheritanceRecords.remove(deletedPlanId); + deletedPlanInheritanceRecord.setIterationRemoved(event.getIteration()); + this.planInheritanceRecordWriter.write(deletedPlanInheritanceRecord); + } + + this.planInheritanceRecordWriter.flush(); + + this.calculateAndWriteDistribution(event.getIteration(), this.strategies, this.planId2planInheritanceRecords, selectedPlanIds, this.selectedPlanStrategyShareWriter); + this.calculateAndWriteDistribution(event.getIteration(), this.strategies, this.planId2planInheritanceRecords, this.planId2planInheritanceRecords.keySet(), this.planStrategyShareWriter); + } + + /** + * Updates the default plan stats - namely the distribution of plan mutators based on the given plan ids. + */ + private void calculateAndWriteDistribution(int currentIteration, ArrayList strategies, Map, PlanInheritanceRecord> planId2planInheritanceRecords, Set> planIds, BufferedWriter writer) { + Map strategy2count = new HashMap<>(); + for (String strategyName : strategies) { + strategy2count.put(strategyName, new AtomicLong(0)); + } + for (Id planId : planIds) { + String mutatedBy = planId2planInheritanceRecords.get(planId).getMutatedBy(); + strategy2count.get(mutatedBy).incrementAndGet(); + } + long sum = strategy2count.values().stream().mapToLong(count -> count.get()).sum(); + StringBuffer line = new StringBuffer(); + line.append(currentIteration); + line.append(DELIMITER); + for (int i = 0; i < strategies.size(); i++) { + if (i > 0) { + line.append(DELIMITER); + } + line.append(String.valueOf(strategy2count.get(strategies.get(i)).doubleValue() / sum)); + } + try { + writer.write(line.toString()); + writer.newLine(); + } catch (IOException e) { + throw new RuntimeException("Could not initialize the plan strategy share writer!", e); + } + } + + @Override + public void notifyShutdown(ShutdownEvent event) { + // flush all pending plan inheritance records and close the readers + + for (PlanInheritanceRecord planInheritanceRecord : this.planId2planInheritanceRecords.values()) { + this.planInheritanceRecordWriter.write(planInheritanceRecord); + } + + this.planInheritanceRecordWriter.flush(); + this.planInheritanceRecordWriter.close(); + + try { + this.selectedPlanStrategyShareWriter.flush(); + this.selectedPlanStrategyShareWriter.close(); + this.planStrategyShareWriter.flush(); + this.planStrategyShareWriter.close(); + } catch (IOException e) { + new RuntimeException(e); + } + + this.planId2planInheritanceRecords.clear(); + } + + @Override + public void install() { + if (getConfig().planInheritance().getEnabled()) addControlerListenerBinding().to(PlanInheritanceModule.class); + } +} diff --git a/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecord.java b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecord.java new file mode 100644 index 00000000000..7212f337896 --- /dev/null +++ b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecord.java @@ -0,0 +1,129 @@ +package org.matsim.core.replanning.inheritance; + +/* *********************************************************************** * + * project: org.matsim.* + * ParallelPopulationReaderMatsimV6.java + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 java.util.ArrayList; +import java.util.List; + +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.population.Person; +import org.matsim.api.core.v01.population.Plan; + +/** + * Data container storing the data of a single plan. + * + * @author neuma, alex94263 + */ +public class PlanInheritanceRecord { + + /** + * Id of the person that plan record belongs to. + */ + private Id agentId; + + /** + * The globally unique plan id. + */ + private Id planId; + + /** + * Id of the plan that this plan had been copied from before mutating. + */ + private Id ancestorId; + + /** + * The name of the strategy that altered this plan. + */ + private String mutatedBy; + + /** + * Iteration in which this plan had been created. May be {@linkplain PlanInheritanceModule#INITIAL_PLAN} if the plan had been in the choice-set from the very beginning. + */ + private int iterationCreated; + + /** + * Iteration in which the plan had been removed from the choice-set. + */ + private int iterationRemoved = -1; + + /** + * Collection of iterations this plan had been the selected plan. + * Initialize this with one since each plan is selected at least once. + */ + private List iterationsSelected = new ArrayList<>(1); + + public Id getPlanId() { + return planId; + } + + public void setPlanId(Id planId) { + this.planId = planId; + } + + public Id getAncestorId() { + return ancestorId; + } + + public void setAncestorId(Id ancestorId) { + this.ancestorId = ancestorId; + } + + public String getMutatedBy() { + return mutatedBy; + } + + public void setMutatedBy(String mutatedBy) { + this.mutatedBy = mutatedBy; + } + + public int getIterationCreated() { + return iterationCreated; + } + + public void setIterationCreated(int iterationCreated) { + this.iterationCreated = iterationCreated; + } + + public int getIterationRemoved() { + return iterationRemoved; + } + + public void setIterationRemoved(int iterationRemoved) { + this.iterationRemoved = iterationRemoved; + } + + public List getIterationsSelected() { + return iterationsSelected; + } + + public void setIterationsSelected(List iterationsSelected) { + this.iterationsSelected = iterationsSelected; + } + + public Id getAgentId() { + return agentId; + } + + public void setAgentId(Id agentId) { + this.agentId = agentId; + } + +} diff --git a/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordReader.java b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordReader.java new file mode 100644 index 00000000000..8d83d6ef1de --- /dev/null +++ b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordReader.java @@ -0,0 +1,96 @@ +package org.matsim.core.replanning.inheritance; + +import java.io.BufferedReader; + +/* *********************************************************************** * + * project: org.matsim.* + * ParallelPopulationReaderMatsimV6.java + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 java.io.BufferedWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.population.Plan; +import org.matsim.core.utils.io.IOUtils; + +/** + * Writes {@linkplain PlanInheritanceRecord} to file in a fixed column sequence. + * + * @author alex94263 + */ +public class PlanInheritanceRecordReader { + + + private final String DELIMITER = "\t"; + private final BufferedReader reader; + + public PlanInheritanceRecordReader(String filename) { + this.reader = IOUtils.getBufferedReader(filename); + + + + } + public Map buildIdx(String[] header) { + Map lookup = new HashMap(); + for (int i=0; i read() { + List records = new ArrayList(); + try { + Map lookUp = buildIdx(reader.readLine().split(DELIMITER)); + String lineString = reader.readLine(); + while(lineString !=null) { + String[] line = lineString.split(DELIMITER); + PlanInheritanceRecord planInheritanceRecord = new PlanInheritanceRecord(); + planInheritanceRecord.setAgentId(Id.createPersonId(line[lookUp.get(PlanInheritanceRecordWriter.AGENT_ID)])); + planInheritanceRecord.setPlanId(Id.create(line[lookUp.get(PlanInheritanceRecordWriter.PLAN_ID)], Plan.class)); + planInheritanceRecord.setAncestorId(Id.create(line[lookUp.get(PlanInheritanceRecordWriter.ANCESTOR_ID)], Plan.class)); + planInheritanceRecord.setMutatedBy(line[lookUp.get(PlanInheritanceRecordWriter.MUTATED_BY)]); + planInheritanceRecord.setIterationCreated(Integer.parseInt(line[lookUp.get(PlanInheritanceRecordWriter.ITERATION_CREATED)])); + planInheritanceRecord.setIterationRemoved(Integer.parseInt(line[lookUp.get(PlanInheritanceRecordWriter.ITERATION_REMOVED)])); + String iterationsSelected = line[lookUp.get(PlanInheritanceRecordWriter.ITERATIONS_SELECTED)]; + planInheritanceRecord.setIterationsSelected(Arrays.asList(iterationsSelected.substring(1, iterationsSelected.length()-1).split(", ")).stream() + .map(Integer::parseInt) + .collect(Collectors.toList())); + records.add(planInheritanceRecord); + lineString = reader.readLine(); + } + return records; + + } catch (IOException e) { + throw new RuntimeException("Could not read the plan inheritance records!", e); + } + + + + } + + +} diff --git a/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordWriter.java b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordWriter.java new file mode 100644 index 00000000000..1400a915406 --- /dev/null +++ b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordWriter.java @@ -0,0 +1,99 @@ +package org.matsim.core.replanning.inheritance; + +/* *********************************************************************** * + * project: org.matsim.* + * ParallelPopulationReaderMatsimV6.java + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 java.io.BufferedWriter; +import java.io.IOException; + +import org.matsim.core.utils.io.IOUtils; + +/** + * Writes {@linkplain PlanInheritanceRecord} to file in a fixed column sequence. + * + * @author neuma, alex94263 + */ +public class PlanInheritanceRecordWriter { + + public static final String AGENT_ID = "agentId"; + public static final String PLAN_ID = "planId"; + public static final String ANCESTOR_ID = "ancestorId"; + public static final String MUTATED_BY = "mutatedBy"; + public static final String ITERATION_CREATED = "iterationCreated"; + public static final String ITERATION_REMOVED = "iterationRemoved"; + public static final String ITERATIONS_SELECTED = "iterationsSelected"; + + private final Character DELIMITER = '\t'; + private final BufferedWriter writer; + + public PlanInheritanceRecordWriter(String filename) { + this.writer = IOUtils.getBufferedWriter(filename); + + StringBuffer header = new StringBuffer(); + header.append(AGENT_ID); header.append(DELIMITER); + header.append(PLAN_ID); header.append(DELIMITER); + header.append(ANCESTOR_ID); header.append(DELIMITER); + header.append(MUTATED_BY); header.append(DELIMITER); + header.append(ITERATION_CREATED); header.append(DELIMITER); + header.append(ITERATION_REMOVED); header.append(DELIMITER); + header.append(ITERATIONS_SELECTED); + + try { + this.writer.write(header.toString()); + this.writer.newLine(); + } catch (IOException e) { + throw new RuntimeException("Could not initialize the plan inheritance writer!", e); + } + } + + public void write(PlanInheritanceRecord planInheritanceRecord) { + StringBuffer line = new StringBuffer(); + line.append(planInheritanceRecord.getAgentId()); line.append(DELIMITER); + line.append(planInheritanceRecord.getPlanId()); line.append(DELIMITER); + line.append(planInheritanceRecord.getAncestorId()); line.append(DELIMITER); + line.append(planInheritanceRecord.getMutatedBy()); line.append(DELIMITER); + line.append(planInheritanceRecord.getIterationCreated()); line.append(DELIMITER); + line.append(planInheritanceRecord.getIterationRemoved()); line.append(DELIMITER); + line.append(planInheritanceRecord.getIterationsSelected()); + + try { + this.writer.write(line.toString()); + this.writer.newLine(); + } catch (IOException e) { + throw new RuntimeException("Could not initialize the plan inheritance writer!", e); + } + } + + public void flush() { + try { + this.writer.flush(); + } catch (IOException e) { + throw new RuntimeException("Failed to flush plan inheritance writer!", e); + } + } + + public void close() { + try { + this.writer.close(); + } catch (IOException e) { + throw new RuntimeException("Failed to close plan inheritance writer!", e); + } + } +} diff --git a/matsim/src/main/java/org/matsim/core/replanning/modules/ExternalModule.java b/matsim/src/main/java/org/matsim/core/replanning/modules/ExternalModule.java index 7b55091f023..773e7a67148 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/modules/ExternalModule.java +++ b/matsim/src/main/java/org/matsim/core/replanning/modules/ExternalModule.java @@ -27,7 +27,6 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.api.core.v01.replanning.PlanStrategyModule; @@ -79,11 +78,11 @@ interface ExeRunnerDelegate { private String outFileRoot = ""; private final OutputDirectoryHierarchy controler; - + private int currentIteration = -1; - + private Population exportPopulation; - + private Map, Plan> plansToMutate = new HashMap<>(); public ExternalModule(final String exePath, final String moduleId, final OutputDirectoryHierarchy controler, final Scenario scenario) { @@ -120,7 +119,7 @@ public void handlePlan(final Plan plan) { // Creating a dummy population which only contains the plans which are passed here. // I need to copy the plans because I am not supposed to add a plan to a different Person. // I also need to memorize the plans which are passed here, because I am supposed to mutate them. - + final Person personWithOnlySelectedPlan = this.exportPopulation.getFactory().createPerson(plan.getPerson().getId()); final Plan planForNewPerson = PopulationUtils.createPlan(personWithOnlySelectedPlan); PopulationUtils.copyFromTo(plan, planForNewPerson); @@ -149,7 +148,7 @@ private void exportPopulation() { private void prepareExternalExeConfig() { Config extConfig; - String configFileName = this.scenario.getConfig().strategy().getExternalExeConfigTemplate(); + String configFileName = this.scenario.getConfig().replanning().getExternalExeConfigTemplate(); if (configFileName == null) { extConfig = new Config(); } else { diff --git a/matsim/src/main/java/org/matsim/core/replanning/modules/TripTimeAllocationMutator.java b/matsim/src/main/java/org/matsim/core/replanning/modules/TripTimeAllocationMutator.java deleted file mode 100644 index a30266f7821..00000000000 --- a/matsim/src/main/java/org/matsim/core/replanning/modules/TripTimeAllocationMutator.java +++ /dev/null @@ -1,89 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TransitTimeAllocationMutator.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.core.replanning.modules; - -import com.google.inject.Inject; -import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlansConfigGroup; -import org.matsim.core.config.groups.PlansConfigGroup.ActivityDurationInterpretation; -import org.matsim.core.gbl.MatsimRandom; -import org.matsim.core.population.algorithms.PlanAlgorithm; -import org.matsim.core.population.algorithms.TripPlanMutateTimeAllocation; -import org.matsim.core.router.TripRouter; - -import jakarta.inject.Provider; - -/** - * Copy/Paste of TimeAllocationMutator, that calls TransitPlanMutateTimeAllocation instead - * of PlanMutateTimeAllocation. - * - * @author mrieser - */ -public class TripTimeAllocationMutator extends AbstractMultithreadedModule { - - private final Provider tripRouterProvider; - - public final static String CONFIG_GROUP = "TimeAllocationMutator"; - public final static String CONFIG_MUTATION_RANGE = "mutationRange"; - - private double mutationRange = 1800.0; - private boolean useActivityDurations = true; - private final boolean affectingDuration; - - /** - * Creates a new TimeAllocationMutator with a mutation range as defined in - * the configuration (module "TimeAllocationMutator", param "mutationRange"). - */ - public TripTimeAllocationMutator(Config config, Provider tripRouterProvider) { - super(config.global()); - this.tripRouterProvider = tripRouterProvider; - this.mutationRange = config.timeAllocationMutator().getMutationRange() ; - this.affectingDuration = config.timeAllocationMutator().isAffectingDuration() ; - PlansConfigGroup.ActivityDurationInterpretation actDurInterpr = ( config.plans().getActivityDurationInterpretation() ) ; - if ( actDurInterpr == PlansConfigGroup.ActivityDurationInterpretation.minOfDurationAndEndTime ) { - useActivityDurations = true ; - } else if ( actDurInterpr == PlansConfigGroup.ActivityDurationInterpretation.endTimeOnly ) { - useActivityDurations = false ; - } else if ( actDurInterpr == PlansConfigGroup.ActivityDurationInterpretation.tryEndTimeThenDuration ) { - throw new UnsupportedOperationException( "need to clarify the correct setting here. Probably not a big deal, but not done yet. kai, aug'10") ; - } else { - throw new IllegalStateException( "beahvior not defined for this configuration setting") ; - } - } - - public TripTimeAllocationMutator(Config config, Provider tripRouterProvider, final double mutationRange, boolean affectingDuration) { - super(config.global()); - this.tripRouterProvider = tripRouterProvider; - this.mutationRange = mutationRange; - this.affectingDuration = affectingDuration; - } - - @Override - public PlanAlgorithm getPlanAlgoInstance() { - TripPlanMutateTimeAllocation pmta = - new TripPlanMutateTimeAllocation( - this.mutationRange, - affectingDuration, MatsimRandom.getLocalInstance()); - pmta.setUseActivityDurations(this.useActivityDurations); - return pmta; - } - -} diff --git a/matsim/src/main/java/org/matsim/core/replanning/selectors/ExpBetaPlanSelector.java b/matsim/src/main/java/org/matsim/core/replanning/selectors/ExpBetaPlanSelector.java index b7c2f399c99..6bc778ab513 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/selectors/ExpBetaPlanSelector.java +++ b/matsim/src/main/java/org/matsim/core/replanning/selectors/ExpBetaPlanSelector.java @@ -24,10 +24,9 @@ import java.util.Map; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.population.BasicPlan; import org.matsim.api.core.v01.population.HasPlansAndId; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.gbl.MatsimRandom; /** @@ -40,12 +39,12 @@ public class ExpBetaPlanSelector implements PlanSelector protected static final double MIN_WEIGHT = Double.MIN_VALUE; protected final double beta; - + public ExpBetaPlanSelector( final double logitScaleFactor ) { this.beta = logitScaleFactor ; } - public ExpBetaPlanSelector(PlanCalcScoreConfigGroup charyparNagelScoringConfigGroup) { + public ExpBetaPlanSelector(ScoringConfigGroup charyparNagelScoringConfigGroup) { this( charyparNagelScoringConfigGroup.getBrainExpBeta() ) ; } diff --git a/matsim/src/main/java/org/matsim/core/replanning/selectors/PathSizeLogitSelector.java b/matsim/src/main/java/org/matsim/core/replanning/selectors/PathSizeLogitSelector.java index 8791819e3b3..d63d8109d93 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/selectors/PathSizeLogitSelector.java +++ b/matsim/src/main/java/org/matsim/core/replanning/selectors/PathSizeLogitSelector.java @@ -31,7 +31,7 @@ import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; @@ -54,7 +54,7 @@ public PathSizeLogitSelector( final double pathSizeLogitExponent, final double l this.network = network ; } - public PathSizeLogitSelector(final PlanCalcScoreConfigGroup config, final Network network) { + public PathSizeLogitSelector(final ScoringConfigGroup config, final Network network) { this( config.getPathSizeLogitBeta(), config.getBrainExpBeta(), network ) ; } @@ -62,19 +62,19 @@ public PathSizeLogitSelector(final PlanCalcScoreConfigGroup config, final Networ @Override protected Map calcWeights(final List plans ) { // ("plans" is the list of plans of a single person) - + Map weights = new HashMap() ; double maxScore = Double.NEGATIVE_INFINITY; HashMap, ArrayList> linksInTime = new HashMap<>(); // (a data structure that memorizes possible leg start times for link utilization (??)) - + HashMap planLength = new HashMap(); // (a data structure that memorizes the total travel distance of each plan) // (yyyy is it obvious that no two plans can have the same hash code? what happens if they do? kai, oct'12) // (why not just ?????) - + //this gets the choice sets C_n //TODO [GL] since the lack of information in Route(), //the very first and the very last link of a path will be ignored - gl @@ -96,7 +96,7 @@ protected Map calcWeights(final List plans ) { pathSize += RouteUtils.calcDistanceExcludingStartEndLink(r, network); // (i.e. pathSize will be the sum over all routes of the plan) - + for (Id linkId : r.getLinkIds()){ ArrayList lit = linksInTime.get(linkId); if (lit == null){ @@ -140,17 +140,17 @@ protected Map calcWeights(final List plans ) { // tmp is now a number that contains the ``reduced'' travel distance of the plan. Divide it by the full travel distance // of the plan, and take to the power of this.beta: double PSi = Math.pow(tmp/planLength.get(plan.hashCode()), this.pathSizeLogitExponent); - + double weight; if (Double.isInfinite(maxScore)) { - // (isInfinite(x) also returns true when x==-Infinity) - + // (isInfinite(x) also returns true when x==-Infinity) + // likely that wc.maxScore == -Infinity, and thus plan.getScoreAsPrimitiveType() also == -Infinity, handle it like any other case where getScore() == maxScore // I do not understand the line above. kai, oct'12 - + weight = PSi; - // (yy I do not understand. Presumably, wc.maxScore may be -Infinity, in which case ALL plan scores are -Infinity - // (or NaN or null or something similar). In this case, plans are simply weighted by their PSi, so that + // (yy I do not understand. Presumably, wc.maxScore may be -Infinity, in which case ALL plan scores are -Infinity + // (or NaN or null or something similar). In this case, plans are simply weighted by their PSi, so that // overlapping plans get less weight than very different plans. kai, oct'12) } else { weight = Math.exp(this.logitScaleFactor * (plan.getScore() - maxScore))*PSi; @@ -159,12 +159,12 @@ protected Map calcWeights(final List plans ) { } if (weight <= 0.0) weight = 0; - // (yy how can weight become negative?? kai, oct'12) + // (yy how can weight become negative?? kai, oct'12) // the weight is memorized; the sum of all weights in computed. Choice will be based on those weights weights.put( plan, weight) ; } - + return weights ; } diff --git a/matsim/src/main/java/org/matsim/core/replanning/strategies/ChangeExpBeta.java b/matsim/src/main/java/org/matsim/core/replanning/strategies/ChangeExpBeta.java index 83815dba12c..ebf5881b6c3 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/strategies/ChangeExpBeta.java +++ b/matsim/src/main/java/org/matsim/core/replanning/strategies/ChangeExpBeta.java @@ -19,7 +19,7 @@ package org.matsim.core.replanning.strategies; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.replanning.PlanStrategy; import org.matsim.core.replanning.PlanStrategyImpl; import org.matsim.core.replanning.selectors.ExpBetaPlanChanger; @@ -29,7 +29,7 @@ public class ChangeExpBeta implements Provider { - @Inject private PlanCalcScoreConfigGroup config; + @Inject private ScoringConfigGroup config; @Override public PlanStrategy get() { diff --git a/matsim/src/main/java/org/matsim/core/replanning/strategies/DefaultPlanStrategiesModule.java b/matsim/src/main/java/org/matsim/core/replanning/strategies/DefaultPlanStrategiesModule.java index 02afce69dcb..18ff8e31436 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/strategies/DefaultPlanStrategiesModule.java +++ b/matsim/src/main/java/org/matsim/core/replanning/strategies/DefaultPlanStrategiesModule.java @@ -32,8 +32,8 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -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.AbstractModule; import org.matsim.core.population.algorithms.PermissibleModesCalculator; import org.matsim.core.population.algorithms.PermissibleModesCalculatorImpl; @@ -51,19 +51,19 @@ public enum DefaultPlansRemover { WorstPlanSelector, SelectRandom, SelectExpBeta @Override public void install() { - if (getConfig().strategy().getPlanSelectorForRemoval().equals(DefaultPlansRemover.WorstPlanSelector.toString())) { + if (getConfig().replanning().getPlanSelectorForRemoval().equals(DefaultPlansRemover.WorstPlanSelector.toString())) { bindPlanSelectorForRemoval().to(WorstPlanForRemovalSelector.class); } - if (getConfig().strategy().getPlanSelectorForRemoval().equals(DefaultPlansRemover.SelectRandom.toString())) { + if (getConfig().replanning().getPlanSelectorForRemoval().equals(DefaultPlansRemover.SelectRandom.toString())) { bindPlanSelectorForRemoval().to(new TypeLiteral>(){}); } - if (getConfig().strategy().getPlanSelectorForRemoval().equals(DefaultPlansRemover.SelectExpBetaForRemoval.toString())) { + if (getConfig().replanning().getPlanSelectorForRemoval().equals(DefaultPlansRemover.SelectExpBetaForRemoval.toString())) { bindPlanSelectorForRemoval().toProvider(ExpBetaPlanSelectorForRemoval.class); } - if (getConfig().strategy().getPlanSelectorForRemoval().equals(DefaultPlansRemover.ChangeExpBetaForRemoval.toString())) { + if (getConfig().replanning().getPlanSelectorForRemoval().equals(DefaultPlansRemover.ChangeExpBetaForRemoval.toString())) { bindPlanSelectorForRemoval().toProvider(ExpBetaPlanChangerForRemoval.class); } - if (getConfig().strategy().getPlanSelectorForRemoval().equals(DefaultPlansRemover.PathSizeLogitSelectorForRemoval.toString())) { + if (getConfig().replanning().getPlanSelectorForRemoval().equals(DefaultPlansRemover.PathSizeLogitSelectorForRemoval.toString())) { bindPlanSelectorForRemoval().toProvider(PathSizeLogitSelectorForRemoval.class); } @@ -73,7 +73,7 @@ public void install() { // that's fine: The StrategyManager will still only add those strategies to itself which are configured. // But we don't want to clutter the container here. Set usedStrategyNames = new HashSet<>(); - for (StrategyConfigGroup.StrategySettings settings : getConfig().strategy().getStrategySettings()) { + for (ReplanningConfigGroup.StrategySettings settings : getConfig().replanning().getStrategySettings()) { usedStrategyNames.add(settings.getStrategyName()); } @@ -160,7 +160,7 @@ public interface DefaultStrategy { private static class ExpBetaPlanSelectorForRemoval implements Provider> { - @Inject private PlanCalcScoreConfigGroup config; + @Inject private ScoringConfigGroup config; @Override public ExpBetaPlanSelector get() { @@ -170,7 +170,7 @@ public ExpBetaPlanSelector get() { private static class ExpBetaPlanChangerForRemoval implements Provider> { - @Inject private PlanCalcScoreConfigGroup config; + @Inject private ScoringConfigGroup config; @Override public ExpBetaPlanChanger get() { @@ -180,7 +180,8 @@ public ExpBetaPlanChanger get() { private static class PathSizeLogitSelectorForRemoval implements Provider { - @Inject PlanCalcScoreConfigGroup config; + @Inject + ScoringConfigGroup config; @Inject Network network; @Override diff --git a/matsim/src/main/java/org/matsim/core/replanning/strategies/SelectExpBeta.java b/matsim/src/main/java/org/matsim/core/replanning/strategies/SelectExpBeta.java index 1ad7755a512..95c19afd6c3 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/strategies/SelectExpBeta.java +++ b/matsim/src/main/java/org/matsim/core/replanning/strategies/SelectExpBeta.java @@ -19,7 +19,7 @@ package org.matsim.core.replanning.strategies; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.replanning.PlanStrategy; import org.matsim.core.replanning.PlanStrategyImpl; import org.matsim.core.replanning.selectors.ExpBetaPlanSelector; @@ -29,7 +29,7 @@ public class SelectExpBeta implements Provider { - @Inject private PlanCalcScoreConfigGroup config; + @Inject private ScoringConfigGroup config; @Override public PlanStrategy get() { diff --git a/matsim/src/main/java/org/matsim/core/replanning/strategies/SelectPathSizeLogit.java b/matsim/src/main/java/org/matsim/core/replanning/strategies/SelectPathSizeLogit.java index f5fd511744d..037c3a79aca 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/strategies/SelectPathSizeLogit.java +++ b/matsim/src/main/java/org/matsim/core/replanning/strategies/SelectPathSizeLogit.java @@ -20,7 +20,7 @@ package org.matsim.core.replanning.strategies; import org.matsim.api.core.v01.network.Network; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.replanning.PlanStrategy; import org.matsim.core.replanning.PlanStrategyImpl; import org.matsim.core.replanning.selectors.PathSizeLogitSelector; @@ -30,7 +30,7 @@ public class SelectPathSizeLogit implements Provider { - @Inject private PlanCalcScoreConfigGroup config; + @Inject private ScoringConfigGroup config; @Inject private Network network; @Override diff --git a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutator.java b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutator.java index 0d7ab5c75c6..c1fbe50e538 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutator.java +++ b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutator.java @@ -35,14 +35,11 @@ public class TimeAllocationMutator implements Provider { @Inject private GlobalConfigGroup globalConfigGroup; @Inject private TimeAllocationMutatorConfigGroup timeAllocationMutatorConfigGroup; @Inject private PlansConfigGroup plansConfigGroup; - @Inject private Provider tripRouterProvider; - @Inject private Population population; @Override public PlanStrategy get() { PlanStrategyImpl strategy = new PlanStrategyImpl(new RandomPlanSelector()); - TimeAllocationMutatorModule tam = new TimeAllocationMutatorModule(this.tripRouterProvider, - this.plansConfigGroup, this.timeAllocationMutatorConfigGroup, this.globalConfigGroup, population); + TimeAllocationMutatorModule tam = new TimeAllocationMutatorModule( this.timeAllocationMutatorConfigGroup, this.globalConfigGroup); strategy.addStrategyModule(tam); return strategy; } diff --git a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorModule.java b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorModule.java index 2486e8dbf77..485089a53ee 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorModule.java +++ b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorModule.java @@ -22,121 +22,45 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.replanning.PlanStrategyModule; -import org.matsim.core.config.Config; -import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.groups.GlobalConfigGroup; -import org.matsim.core.config.groups.PlansConfigGroup; import org.matsim.core.config.groups.TimeAllocationMutatorConfigGroup; -import org.matsim.core.config.groups.TimeAllocationMutatorConfigGroup.TimeAllocationMutatorSubpopulationSettings; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.population.algorithms.PlanAlgorithm; -import org.matsim.core.population.algorithms.PlanMutateTimeAllocationSimplified; -import org.matsim.core.population.algorithms.TripPlanMutateTimeAllocation; +import org.matsim.core.population.algorithms.MutateActivityTimeAllocation; import org.matsim.core.replanning.modules.AbstractMultithreadedModule; -import org.matsim.core.router.TripRouter; -import org.matsim.core.router.TripStructureUtils.StageActivityHandling; - -import jakarta.inject.Provider; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; /** - * Wraps the {@link org.matsim.core.population.algorithms.PlanMutateTimeAllocation}- + * Wraps the {@link org.matsim.core.population.algorithms.TripPlanMutateTimeAllocation}- * PlanAlgorithm into a {@link PlanStrategyModule} so it can be used for plans * replanning. Supports multiple threads. * * @author mrieser - * @see org.matsim.core.population.algorithms.PlanMutateTimeAllocation + * @see org.matsim.core.population.algorithms.TripPlanMutateTimeAllocation */ class TimeAllocationMutatorModule extends AbstractMultithreadedModule{ - private static boolean ACTIVITY_DURATION_WARNING_SHOWN = false; private static final Logger log = LogManager.getLogger( TimeAllocationMutatorModule.class ); - private final double mutationRange; private final boolean affectingDuration; -// private final String subpopulationAttribute; - private final Map subpopulationMutationRanges; - private final Map subpopulationAffectingDuration; - private final PlansConfigGroup.ActivityDurationInterpretation activityDurationInterpretation; - - /** - * Creates a new TimeAllocationMutator with a mutation range as defined in - * the configuration (module "TimeAllocationMutator", param "mutationRange"). - */ - @Deprecated - TimeAllocationMutatorModule( Config config, Provider tripRouterProvider, final double mutationRange, boolean affectingDuration ) { - super(config.global()); - this.affectingDuration = affectingDuration; - this.mutationRange = mutationRange; - this.activityDurationInterpretation = (config.plans().getActivityDurationInterpretation()); -// this.subpopulationAttribute = null; - this.subpopulationMutationRanges = null; - this.subpopulationAffectingDuration = null; - log.warn("deprecated constructor was used - individual time allocation mutator settings for subpopulations is not supported!"); - } + private final TimeAllocationMutatorConfigGroup timeAllocationMutatorConfigGroup; - TimeAllocationMutatorModule( Provider tripRouterProvider, PlansConfigGroup plansConfigGroup, TimeAllocationMutatorConfigGroup timeAllocationMutatorConfigGroup, GlobalConfigGroup globalConfigGroup ) { - this(tripRouterProvider, plansConfigGroup, timeAllocationMutatorConfigGroup, globalConfigGroup, null); - } - TimeAllocationMutatorModule( Provider tripRouterProvider, PlansConfigGroup plansConfigGroup, TimeAllocationMutatorConfigGroup timeAllocationMutatorConfigGroup, GlobalConfigGroup globalConfigGroup, - final Population population ) { + TimeAllocationMutatorModule( TimeAllocationMutatorConfigGroup timeAllocationMutatorConfigGroup, GlobalConfigGroup globalConfigGroup) { super(globalConfigGroup); - this.activityDurationInterpretation = plansConfigGroup.getActivityDurationInterpretation(); this.mutationRange = timeAllocationMutatorConfigGroup.getMutationRange(); this.affectingDuration = timeAllocationMutatorConfigGroup.isAffectingDuration(); + this.timeAllocationMutatorConfigGroup = timeAllocationMutatorConfigGroup; - // in case we have subpopulations and individual settings for them - if ( -// plansConfigGroup.getSubpopulationAttributeName() != null && - timeAllocationMutatorConfigGroup.isUseIndividualSettingsForSubpopulations() && population != null) { -// this.subpopulationAttribute = plansConfigGroup.getSubpopulationAttributeName(); - this.subpopulationMutationRanges = new HashMap<>(); - this.subpopulationAffectingDuration = new HashMap<>(); - - Collection settings = timeAllocationMutatorConfigGroup.getParameterSets(TimeAllocationMutatorSubpopulationSettings.SET_NAME); - for (ConfigGroup group : settings) { - TimeAllocationMutatorSubpopulationSettings subpopulationSettings = (TimeAllocationMutatorSubpopulationSettings) group; - String subpopulation = subpopulationSettings.getSubpopulation(); - this.subpopulationMutationRanges.put(subpopulation, subpopulationSettings.getMutationRange()); - this.subpopulationAffectingDuration.put(subpopulation, subpopulationSettings.isAffectingDuration()); - log.info("Found individual time mutator settings for subpopulation: " + subpopulation); - } - } else { -// this.subpopulationAttribute = null; - this.subpopulationMutationRanges = null; - this.subpopulationAffectingDuration = null; - } } @Override public PlanAlgorithm getPlanAlgoInstance() { - PlanAlgorithm pmta; - switch (this.activityDurationInterpretation) { - case minOfDurationAndEndTime: - pmta = new TripPlanMutateTimeAllocation(this.mutationRange, this.affectingDuration, MatsimRandom.getLocalInstance(), - this.subpopulationMutationRanges, this.subpopulationAffectingDuration); - break; - default: - if(this.affectingDuration) { - if (!ACTIVITY_DURATION_WARNING_SHOWN) { - log.warn("Please be aware that durations of activities now can mutate freely and possibly become negative." + - "This might be a problem if you have \n" + - "a) short activities that are only provided with duration and not with endtime AND\n" + - "b) agents with only one or two initial plans.\n" + - "This can have impact on scoring and maybe even on qsim execution. It is recommended to set affectingDuration=false for such set up."); - ACTIVITY_DURATION_WARNING_SHOWN = true; - } - } - pmta = new PlanMutateTimeAllocationSimplified( - // TODO: is StageActivityHandling.ExcludeStageActivities right here? - StageActivityHandling.ExcludeStageActivities, this.mutationRange, this.affectingDuration, MatsimRandom.getLocalInstance()); - } + PlanAlgorithm pmta = new MutateActivityTimeAllocation + (this.mutationRange, this.affectingDuration, MatsimRandom.getLocalInstance(), + timeAllocationMutatorConfigGroup.getLatestActivityEndTime(), timeAllocationMutatorConfigGroup.isMutateAroundInitialEndTimeOnly(), + timeAllocationMutatorConfigGroup.getMutationRangeStep()); return pmta; } } diff --git a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorReRoute.java b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorReRoute.java index 009e9e0199c..f430d0d3004 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorReRoute.java +++ b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorReRoute.java @@ -43,13 +43,12 @@ public class TimeAllocationMutatorReRoute implements Provider { @Inject private TimeAllocationMutatorConfigGroup timeAllocationMutatorConfigGroup; @Inject private PlansConfigGroup plansConfigGroup; @Inject private ActivityFacilities activityFacilities; - @Inject private Population population; @Inject private TimeInterpretation timeInterpretation; @Override public PlanStrategy get() { final PlanStrategyImpl strategy = new PlanStrategyImpl(new RandomPlanSelector()); - strategy.addStrategyModule(new TimeAllocationMutatorModule(this.tripRouterProvider, this.plansConfigGroup, this.timeAllocationMutatorConfigGroup, this.globalConfigGroup, this.population) ); + strategy.addStrategyModule(new TimeAllocationMutatorModule(this.timeAllocationMutatorConfigGroup, this.globalConfigGroup) ); strategy.addStrategyModule(new ReRoute(this.activityFacilities, this.tripRouterProvider, this.globalConfigGroup, this.timeInterpretation)); return strategy; } diff --git a/matsim/src/main/java/org/matsim/core/router/BeelineTeleportationRouting.java b/matsim/src/main/java/org/matsim/core/router/BeelineTeleportationRouting.java index 8988b95c413..721f77c986d 100644 --- a/matsim/src/main/java/org/matsim/core/router/BeelineTeleportationRouting.java +++ b/matsim/src/main/java/org/matsim/core/router/BeelineTeleportationRouting.java @@ -22,16 +22,16 @@ package org.matsim.core.router; import org.matsim.api.core.v01.Scenario; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import jakarta.inject.Inject; import jakarta.inject.Provider; class BeelineTeleportationRouting implements Provider { - private final PlansCalcRouteConfigGroup.TeleportedModeParams params; + private final RoutingConfigGroup.TeleportedModeParams params; - public BeelineTeleportationRouting( PlansCalcRouteConfigGroup.TeleportedModeParams params ) { + public BeelineTeleportationRouting( RoutingConfigGroup.TeleportedModeParams params ) { this.params = params; } diff --git a/matsim/src/main/java/org/matsim/core/router/DefaultRoutingModules.java b/matsim/src/main/java/org/matsim/core/router/DefaultRoutingModules.java index 45410a0ce48..8e26e960a76 100644 --- a/matsim/src/main/java/org/matsim/core/router/DefaultRoutingModules.java +++ b/matsim/src/main/java/org/matsim/core/router/DefaultRoutingModules.java @@ -21,8 +21,8 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.PopulationFactory; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.TeleportedModeParams; +import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup.TeleportedModeParams; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.utils.timing.TimeInterpretation; @@ -40,7 +40,7 @@ public final class DefaultRoutingModules { private DefaultRoutingModules(){} // do not instantiate public static RoutingModule createPseudoTransitRouter( String mode, PopulationFactory popFac, Network net, LeastCostPathCalculator routeAlgo, - PlansCalcRouteConfigGroup.TeleportedModeParams params ) { + RoutingConfigGroup.TeleportedModeParams params ) { return new FreespeedFactorRoutingModule( mode, popFac, diff --git a/matsim/src/main/java/org/matsim/core/router/FallbackRoutingModuleDefaultImpl.java b/matsim/src/main/java/org/matsim/core/router/FallbackRoutingModuleDefaultImpl.java index 52db4dea30f..42de02022cd 100644 --- a/matsim/src/main/java/org/matsim/core/router/FallbackRoutingModuleDefaultImpl.java +++ b/matsim/src/main/java/org/matsim/core/router/FallbackRoutingModuleDefaultImpl.java @@ -11,8 +11,7 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.api.core.v01.population.Population; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.GlobalConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.facilities.FacilitiesUtils; import org.matsim.facilities.Facility; @@ -24,7 +23,7 @@ class FallbackRoutingModuleDefaultImpl implements FallbackRoutingModule { @Deprecated // #deleteBeforeRelease : only used to retrofit plans created since the merge of fallback routing module (sep'-dec'19) public static final String _fallback = "_fallback"; - @Inject private PlansCalcRouteConfigGroup pcrCfg; + @Inject private RoutingConfigGroup pcrCfg; @Inject private Config config ; @Inject private Population population ; @Inject private Network network ; @@ -34,7 +33,7 @@ class FallbackRoutingModuleDefaultImpl implements FallbackRoutingModule { final Facility toFacility = request.getToFacility(); final double departureTime = request.getDepartureTime(); final Person person = request.getPerson(); - + Leg leg = population.getFactory().createLeg( TransportMode.walk ) ; Coord fromCoord = FacilitiesUtils.decideOnCoord( fromFacility, network, config ); Coord toCoord = FacilitiesUtils.decideOnCoord( toFacility, network, config ) ; @@ -45,7 +44,7 @@ class FallbackRoutingModuleDefaultImpl implements FallbackRoutingModule { * would be better if we would try the walkRouter first and fall back to "UltimateFallbackRoutingModule" or a * handwritten teleported walk like below only if the walkRouter returns null. - gl/kn-dec'19 */ - NetworkRoutingInclAccessEgressModule.routeBushwhackingLeg( person, leg, fromCoord, toCoord, departureTime, dpLinkId, arLinkId, population.getFactory(), + NetworkRoutingInclAccessEgressModule.routeBushwhackingLeg( person, leg, fromCoord, toCoord, departureTime, dpLinkId, arLinkId, population.getFactory(), pcrCfg.getModeRoutingParams().get(TransportMode.walk) ) ; return Collections.singletonList( leg ) ; } diff --git a/matsim/src/main/java/org/matsim/core/router/FastAStarEuclidean.java b/matsim/src/main/java/org/matsim/core/router/FastAStarEuclidean.java deleted file mode 100644 index 1020cca92f5..00000000000 --- a/matsim/src/main/java/org/matsim/core/router/FastAStarEuclidean.java +++ /dev/null @@ -1,140 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * FastAStarEuclidean.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.core.router; - -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.router.priorityqueue.BinaryMinHeap; -import org.matsim.core.router.util.AStarNodeData; -import org.matsim.core.router.util.AStarNodeDataFactory; -import org.matsim.core.router.util.ArrayRoutingNetwork; -import org.matsim.core.router.util.ArrayRoutingNetworkNode; -import org.matsim.core.router.util.PreProcessDijkstra; -import org.matsim.core.router.util.PreProcessEuclidean; -import org.matsim.core.router.util.RoutingNetwork; -import org.matsim.core.router.util.RoutingNetworkNode; -import org.matsim.core.router.util.TravelDisutility; -import org.matsim.core.router.util.TravelTime; -import org.matsim.core.utils.collections.RouterPriorityQueue; -import org.matsim.vehicles.Vehicle; - -/** - *

    - * Performance optimized version of the AStarEuclidean {@link org.matsim.core.router.AStarEuclidean} - * least cost path router which uses its own network to route within. - *

    - * - * @see org.matsim.core.router.AStarEuclidean - * @see org.matsim.core.router.util.RoutingNetwork - * @author cdobler - */ -public class FastAStarEuclidean extends AStarEuclidean { - - private final RoutingNetwork routingNetwork; - private final FastRouterDelegate fastRouter; - private BinaryMinHeap heap = null; - private int maxSize = -1; - - FastAStarEuclidean(final RoutingNetwork routingNetwork, final PreProcessEuclidean preProcessData, - final TravelDisutility costFunction, final TravelTime timeFunction, final double overdoFactor, - final FastRouterDelegateFactory fastRouterFactory) { - super(routingNetwork, preProcessData, costFunction, timeFunction, overdoFactor); - - this.routingNetwork = routingNetwork; - this.fastRouter = fastRouterFactory.createFastRouterDelegate(this, new AStarNodeDataFactory(), routingNetwork); - - this.nodeData.clear(); - } - - /* - * Replace the references to the from and to nodes with their corresponding - * nodes in the routing network. - */ - @Override - public Path calcLeastCostPath(final Node fromNode, final Node toNode, final double startTime, final Person person, final Vehicle vehicle) { - - this.fastRouter.initialize(); - this.routingNetwork.initialize(); - - RoutingNetworkNode routingNetworkFromNode = this.routingNetwork.getNodes().get(fromNode.getId()); - RoutingNetworkNode routingNetworkToNode = this.routingNetwork.getNodes().get(toNode.getId()); - - return super.calcLeastCostPath(routingNetworkFromNode, routingNetworkToNode, startTime, person, vehicle); - } - - @Override - /*package*/ RouterPriorityQueue createRouterPriorityQueue() { - /* - * Re-use existing BinaryMinHeap instead of creating a new one. For large networks (> 10^6 nodes and links) this reduced - * the computation time by 40%! cdobler, oct'15 - */ - if (this.routingNetwork instanceof ArrayRoutingNetwork) { - int size = this.routingNetwork.getNodes().size(); - if (this.heap == null || this.maxSize != size) { - this.maxSize = size; - this.heap = new BinaryMinHeap<>(maxSize); - return this.heap; - } else { - this.heap.reset(); - return this.heap; - } -// int maxSize = this.routingNetwork.getNodes().size(); -// return new BinaryMinHeap(maxSize); - } else { - return super.createRouterPriorityQueue(); - } - } - - /* - * Constructs the path and replaces the nodes and links from the routing network - * with their corresponding nodes and links from the network. - */ - @Override - protected Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime) { - return this.fastRouter.constructPath(fromNode, toNode, startTime, arrivalTime); - } - - /* - * For performance reasons the outgoing links of a node are stored in - * the routing network in an array instead of a map. Therefore we have - * to iterate over an array instead of over a map. - */ - @Override - protected void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue pendingNodes) { - this.fastRouter.relaxNode(outNode, toNode, pendingNodes); - } - - /* - * The DijkstraNodeData is taken from the RoutingNetworkNode and not from a map. - */ - @Override - protected AStarNodeData getData(final Node n) { - return (AStarNodeData) this.fastRouter.getData(n); - } - - /* - * The DeadEndData is taken from the RoutingNetworkNode and not from a map. - */ - @Override - protected PreProcessDijkstra.DeadEndData getPreProcessData(final Node n) { - return this.fastRouter.getPreProcessData(n); - } -} diff --git a/matsim/src/main/java/org/matsim/core/router/FastAStarEuclideanFactory.java b/matsim/src/main/java/org/matsim/core/router/FastAStarEuclideanFactory.java deleted file mode 100644 index dc301c9363e..00000000000 --- a/matsim/src/main/java/org/matsim/core/router/FastAStarEuclideanFactory.java +++ /dev/null @@ -1,93 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * FastAStarEuclideanFactory.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.core.router; - -import java.util.HashMap; -import java.util.Map; - -import org.matsim.api.core.v01.network.Network; -import org.matsim.core.router.util.ArrayRoutingNetworkFactory; -import org.matsim.core.router.util.LeastCostPathCalculator; -import org.matsim.core.router.util.LeastCostPathCalculatorFactory; -import org.matsim.core.router.util.PreProcessEuclidean; -import org.matsim.core.router.util.RoutingNetwork; -import org.matsim.core.router.util.RoutingNetworkFactory; -import org.matsim.core.router.util.RoutingNetworkNode; -import org.matsim.core.router.util.TravelDisutility; -import org.matsim.core.router.util.TravelTime; - -/** - * @author cdobler - */ -public class FastAStarEuclideanFactory implements LeastCostPathCalculatorFactory { - - private final RoutingNetworkFactory routingNetworkFactory; - private final Map routingNetworks = new HashMap<>(); - private final Map preProcessData = new HashMap<>(); - private final double overdoFactor; - - public FastAStarEuclideanFactory() { - this(1); - } - - public FastAStarEuclideanFactory(double overdoFactor) { - this(FastRouterType.ARRAY, overdoFactor); - } - - private FastAStarEuclideanFactory(final FastRouterType fastRouterType, double overdoFactor) { - this.overdoFactor = overdoFactor; - switch (fastRouterType) { - case ARRAY: - this.routingNetworkFactory = new ArrayRoutingNetworkFactory(); - break; - case POINTER: - throw new RuntimeException( - "PointerRoutingNetworks are no longer supported. Use ArrayRoutingNetworks instead. Aborting!"); - default: - throw new RuntimeException("Undefined FastRouterType: " + fastRouterType); - } - } - - @Override - public synchronized LeastCostPathCalculator createPathCalculator(final Network network, - final TravelDisutility travelCosts, final TravelTime travelTimes) { - RoutingNetwork routingNetwork = this.routingNetworks.get(network); - PreProcessEuclidean preProcessEuclidean = this.preProcessData.get(network); - - if (routingNetwork == null) { - routingNetwork = this.routingNetworkFactory.createRoutingNetwork(network); - - preProcessEuclidean = new PreProcessEuclidean(travelCosts); - preProcessEuclidean.run(network); - this.preProcessData.put(network, preProcessEuclidean); - - for (RoutingNetworkNode node : routingNetwork.getNodes().values()) { - node.setDeadEndData(preProcessEuclidean.getNodeData(node.getNode())); - } - - this.routingNetworks.put(network, routingNetwork); - } - FastRouterDelegateFactory fastRouterFactory = new ArrayFastRouterDelegateFactory(); - - return new FastAStarEuclidean(routingNetwork, preProcessEuclidean, travelCosts, travelTimes, overdoFactor, - fastRouterFactory); - } -} \ No newline at end of file diff --git a/matsim/src/main/java/org/matsim/core/router/FastAStarLandmarks.java b/matsim/src/main/java/org/matsim/core/router/FastAStarLandmarks.java deleted file mode 100644 index 50b8909d825..00000000000 --- a/matsim/src/main/java/org/matsim/core/router/FastAStarLandmarks.java +++ /dev/null @@ -1,146 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * FastAStarLandmarks.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.core.router; - -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.router.priorityqueue.BinaryMinHeap; -import org.matsim.core.router.util.AStarNodeData; -import org.matsim.core.router.util.AStarNodeDataFactory; -import org.matsim.core.router.util.ArrayRoutingNetwork; -import org.matsim.core.router.util.ArrayRoutingNetworkNode; -import org.matsim.core.router.util.PreProcessLandmarks; -import org.matsim.core.router.util.RoutingNetwork; -import org.matsim.core.router.util.RoutingNetworkNode; -import org.matsim.core.router.util.TravelDisutility; -import org.matsim.core.router.util.TravelTime; -import org.matsim.core.utils.collections.RouterPriorityQueue; -import org.matsim.vehicles.Vehicle; - -/** - *

    - * Performance optimized version of the Dijkstra {@link org.matsim.core.router.FastAStarLandmarks} - * least cost path router which uses its own network to route within. - *

    - * - * @see org.matsim.core.router.FastAStarLandmarks - * @see org.matsim.core.router.util.RoutingNetwork - * @author cdobler - */ -public class FastAStarLandmarks extends AStarLandmarks { - - private final RoutingNetwork routingNetwork; - private final FastRouterDelegate fastRouter; - private BinaryMinHeap heap = null; - private int maxSize = -1; - - FastAStarLandmarks(final RoutingNetwork routingNetwork, final PreProcessLandmarks preProcessData, - final TravelDisutility costFunction, final TravelTime timeFunction, final double overdoFactor, - final FastRouterDelegateFactory fastRouterFactory) { - super(routingNetwork, preProcessData, costFunction, timeFunction, overdoFactor); - - this.routingNetwork = routingNetwork; - this.fastRouter = fastRouterFactory.createFastRouterDelegate(this, new AStarNodeDataFactory(), routingNetwork); - - this.nodeData.clear(); - } - - /* - * Replace the references to the from and to nodes with their corresponding - * nodes in the routing network. - */ - @Override - public Path calcLeastCostPath(final Node fromNode, final Node toNode, final double startTime, final Person person, final Vehicle vehicle) { - - this.fastRouter.initialize(); - this.routingNetwork.initialize(); - - RoutingNetworkNode routingNetworkFromNode = routingNetwork.getNodes().get(fromNode.getId()); - RoutingNetworkNode routingNetworkToNode = routingNetwork.getNodes().get(toNode.getId()); - - return super.calcLeastCostPath(routingNetworkFromNode, routingNetworkToNode, startTime, person, vehicle); - } - - @Override - /*package*/ RouterPriorityQueue createRouterPriorityQueue() { - /* - * Re-use existing BinaryMinHeap instead of creating a new one. For large networks (> 10^6 nodes and links) this reduced - * the computation time by 40%! cdobler, oct'15 - */ - if (this.routingNetwork instanceof ArrayRoutingNetwork) { - int size = this.routingNetwork.getNodes().size(); - if (this.heap == null || this.maxSize != size) { - this.maxSize = size; - this.heap = new BinaryMinHeap<>(maxSize); - return this.heap; - } else { - this.heap.reset(); - return this.heap; - } - } else { - return super.createRouterPriorityQueue(); - } - } - - /* - * Constructs the path and replaces the nodes and links from the routing network - * with their corresponding nodes and links from the network. - */ - @Override - protected Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime) { - return this.fastRouter.constructPath(fromNode, toNode, startTime, arrivalTime); - } - - /* - * For performance reasons the outgoing links of a node are stored in - * the routing network in an array instead of a map. Therefore we have - * to iterate over an array instead of over a map. - */ - @Override - protected void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue pendingNodes) { - this.controlCounter++; - if (this.controlCounter == controlInterval) { - int newLandmarkIndex = checkToAddLandmark(outNode, toNode); - if (newLandmarkIndex > 0) { - updatePendingNodes(newLandmarkIndex, toNode, pendingNodes); - } - this.controlCounter = 0; - } - - this.fastRouter.relaxNode(outNode, toNode, pendingNodes); - } - - /* - * The DijkstraNodeData is taken from the RoutingNetworkNode and not from a map. - */ - @Override - protected AStarNodeData getData(final Node n) { - return (AStarNodeData) this.fastRouter.getData(n); - } - - /* - * The LandmarksData is taken from the RoutingNetworkNode and not from a map. - */ - @Override - protected PreProcessLandmarks.LandmarksData getPreProcessData(final Node n) { - return (PreProcessLandmarks.LandmarksData) this.fastRouter.getPreProcessData(n); - } -} \ No newline at end of file diff --git a/matsim/src/main/java/org/matsim/core/router/FastAStarLandmarksFactory.java b/matsim/src/main/java/org/matsim/core/router/FastAStarLandmarksFactory.java deleted file mode 100644 index f3dadbad642..00000000000 --- a/matsim/src/main/java/org/matsim/core/router/FastAStarLandmarksFactory.java +++ /dev/null @@ -1,104 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * FastAStarLandmarksFactory.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.core.router; - -import java.util.HashMap; -import java.util.Map; - -import jakarta.inject.Inject; -import jakarta.inject.Singleton; - -import org.matsim.api.core.v01.network.Network; -import org.matsim.core.config.groups.GlobalConfigGroup; -import org.matsim.core.router.util.ArrayRoutingNetworkFactory; -import org.matsim.core.router.util.LeastCostPathCalculator; -import org.matsim.core.router.util.LeastCostPathCalculatorFactory; -import org.matsim.core.router.util.PreProcessLandmarks; -import org.matsim.core.router.util.RoutingNetwork; -import org.matsim.core.router.util.RoutingNetworkFactory; -import org.matsim.core.router.util.RoutingNetworkNode; -import org.matsim.core.router.util.TravelDisutility; -import org.matsim.core.router.util.TravelTime; - -/** - * @author cdobler - */ -@Singleton -public class FastAStarLandmarksFactory implements LeastCostPathCalculatorFactory { - - private final RoutingNetworkFactory routingNetworkFactory; - private final Map routingNetworks = new HashMap<>(); - private final Map preProcessData = new HashMap<>(); - - private final int nThreads; - - @Inject - public FastAStarLandmarksFactory(final GlobalConfigGroup globalConfigGroup) { - this(FastRouterType.ARRAY, globalConfigGroup.getNumberOfThreads()); - } - - public FastAStarLandmarksFactory(int nThreads) { - this(FastRouterType.ARRAY, nThreads); - } - - // hide this constructor, as only one router type is allowed anyway... - private FastAStarLandmarksFactory(final FastRouterType fastRouterType, int numberOfThreads) { - switch (fastRouterType) { - case ARRAY: - this.routingNetworkFactory = new ArrayRoutingNetworkFactory(); - break; - case POINTER: - throw new RuntimeException( - "PointerRoutingNetworks are no longer supported. Use ArrayRoutingNetworks instead. Aborting!"); - default: - throw new RuntimeException("Undefined FastRouterType: " + fastRouterType); - } - - this.nThreads = numberOfThreads; - } - - @Override - public synchronized LeastCostPathCalculator createPathCalculator(final Network network, - final TravelDisutility travelCosts, final TravelTime travelTimes) { - RoutingNetwork routingNetwork = this.routingNetworks.get(network); - PreProcessLandmarks preProcessLandmarks = this.preProcessData.get(network); - - if (routingNetwork == null) { - routingNetwork = this.routingNetworkFactory.createRoutingNetwork(network); - - preProcessLandmarks = new PreProcessLandmarks(travelCosts); - preProcessLandmarks.setNumberOfThreads(nThreads); - preProcessLandmarks.run(network); - this.preProcessData.put(network, preProcessLandmarks); - - for (RoutingNetworkNode node : routingNetwork.getNodes().values()) { - node.setDeadEndData(preProcessLandmarks.getNodeData(node.getNode())); - } - - this.routingNetworks.put(network, routingNetwork); - } - FastRouterDelegateFactory fastRouterFactory = new ArrayFastRouterDelegateFactory(); - - final double overdoFactor = 1.0; - return new FastAStarLandmarks(routingNetwork, preProcessLandmarks, travelCosts, travelTimes, overdoFactor, - fastRouterFactory); - } -} diff --git a/matsim/src/main/java/org/matsim/core/router/FastDijkstra.java b/matsim/src/main/java/org/matsim/core/router/FastDijkstra.java deleted file mode 100644 index a048971a04e..00000000000 --- a/matsim/src/main/java/org/matsim/core/router/FastDijkstra.java +++ /dev/null @@ -1,142 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * FastDijkstra.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.core.router; - -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.router.priorityqueue.BinaryMinHeap; -import org.matsim.core.router.util.ArrayRoutingNetwork; -import org.matsim.core.router.util.ArrayRoutingNetworkNode; -import org.matsim.core.router.util.DijkstraNodeData; -import org.matsim.core.router.util.DijkstraNodeDataFactory; -import org.matsim.core.router.util.PreProcessDijkstra; -import org.matsim.core.router.util.RoutingNetwork; -import org.matsim.core.router.util.RoutingNetworkNode; -import org.matsim.core.router.util.TravelDisutility; -import org.matsim.core.router.util.TravelTime; -import org.matsim.core.utils.collections.RouterPriorityQueue; -import org.matsim.vehicles.Vehicle; - -/** - *

    - * Performance optimized version of the Dijkstra {@link org.matsim.core.router.Dijkstra} - * least cost path router which uses its own network to route within. - *

    - * - * @see org.matsim.core.router.Dijkstra - * @see org.matsim.core.router.util.RoutingNetwork - * @author cdobler - */ -public class FastDijkstra extends Dijkstra { - - private final RoutingNetwork routingNetwork; - private final FastRouterDelegate fastRouter; - private BinaryMinHeap heap = null; - private int maxSize = -1; - - /* - * Create the routing network here and clear the nodeData map - * which is not used by this implementation. - */ - FastDijkstra(final RoutingNetwork routingNetwork, final TravelDisutility costFunction, final TravelTime timeFunction, - final PreProcessDijkstra preProcessData, final FastRouterDelegateFactory fastRouterFactory) { - super(routingNetwork, costFunction, timeFunction, preProcessData); - - this.routingNetwork = routingNetwork; - this.fastRouter = fastRouterFactory.createFastRouterDelegate(this, new DijkstraNodeDataFactory(), routingNetwork); - - this.nodeData.clear(); - } - - /* - * Replace the references to the from and to nodes with their corresponding - * nodes in the routing network. - */ - @Override - public Path calcLeastCostPath(final Node fromNode, final Node toNode, final double startTime, final Person person, final Vehicle vehicle) { - - this.fastRouter.initialize(); - this.routingNetwork.initialize(); - - RoutingNetworkNode routingNetworkFromNode = this.routingNetwork.getNodes().get(fromNode.getId()); - RoutingNetworkNode routingNetworkToNode = this.routingNetwork.getNodes().get(toNode.getId()); - - return super.calcLeastCostPath(routingNetworkFromNode, routingNetworkToNode, startTime, person, vehicle); - } - - @Override - /*package*/ RouterPriorityQueue createRouterPriorityQueue() { - /* - * Re-use existing BinaryMinHeap instead of creating a new one. For large networks (> 10^6 nodes and links) this reduced - * the computation time by 40%! cdobler, oct'15 - */ - if (this.routingNetwork instanceof ArrayRoutingNetwork) { - int size = this.routingNetwork.getNodes().size(); - if (this.heap == null || this.maxSize != size) { - this.maxSize = size; - this.heap = new BinaryMinHeap<>(maxSize); - return this.heap; - } else { - this.heap.reset(); - return this.heap; - } -// int maxSize = this.routingNetwork.getNodes().size(); -// return new BinaryMinHeap(maxSize); - } else { - return super.createRouterPriorityQueue(); - } - } - - /* - * Constructs the path and replaces the nodes and links from the routing network - * with their corresponding nodes and links from the network. - */ - @Override - protected Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime) { - return this.fastRouter.constructPath(fromNode, toNode, startTime, arrivalTime); - } - - /* - * For performance reasons the outgoing links of a node are stored in - * the routing network in an array instead of a map. Therefore we have - * to iterate over an array instead of over a map. - */ - @Override - protected void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue pendingNodes) { - this.fastRouter.relaxNode(outNode, toNode, pendingNodes); - } - - /* - * The DijkstraNodeData is taken from the RoutingNetworkNode and not from a map. - */ - @Override - protected DijkstraNodeData getData(final Node n) { - return (DijkstraNodeData) this.fastRouter.getData(n); - } - - /* - * The DeadEndData is taken from the RoutingNetworkNode and not from a map. - */ - @Override - protected PreProcessDijkstra.DeadEndData getPreProcessData(final Node n) { - return this.fastRouter.getPreProcessData(n); - } -} diff --git a/matsim/src/main/java/org/matsim/core/router/FastDijkstraFactory.java b/matsim/src/main/java/org/matsim/core/router/FastDijkstraFactory.java deleted file mode 100644 index 46f37f798a1..00000000000 --- a/matsim/src/main/java/org/matsim/core/router/FastDijkstraFactory.java +++ /dev/null @@ -1,97 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * FastDijkstraFactory.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.core.router; - -import java.util.HashMap; -import java.util.Map; - -import jakarta.inject.Inject; -import jakarta.inject.Singleton; - -import org.matsim.api.core.v01.network.Network; -import org.matsim.core.router.util.ArrayRoutingNetworkFactory; -import org.matsim.core.router.util.LeastCostPathCalculator; -import org.matsim.core.router.util.LeastCostPathCalculatorFactory; -import org.matsim.core.router.util.PreProcessDijkstra; -import org.matsim.core.router.util.RoutingNetwork; -import org.matsim.core.router.util.RoutingNetworkFactory; -import org.matsim.core.router.util.RoutingNetworkNode; -import org.matsim.core.router.util.TravelDisutility; -import org.matsim.core.router.util.TravelTime; - -@Singleton -public class FastDijkstraFactory implements LeastCostPathCalculatorFactory { - - private final boolean usePreProcessData; - private final RoutingNetworkFactory routingNetworkFactory; - private final Map routingNetworks = new HashMap<>(); - private final Map preProcessData = new HashMap<>(); - - @Inject - public FastDijkstraFactory() { - this(false, FastRouterType.ARRAY); - } - - public FastDijkstraFactory(final boolean usePreProcessData) { - this(usePreProcessData, FastRouterType.ARRAY); - } - - private FastDijkstraFactory(final boolean usePreProcessData, final FastRouterType fastRouterType) { - this.usePreProcessData = usePreProcessData; - - switch (fastRouterType) { - case ARRAY: - this.routingNetworkFactory = new ArrayRoutingNetworkFactory(); - break; - case POINTER: - throw new RuntimeException("PointerRoutingNetworks are no longer supported. " - + "Use ArrayRoutingNetworks instead. Aborting!"); - default: - throw new RuntimeException("Undefined FastRouterType: " + fastRouterType); - } - } - - @Override - public synchronized LeastCostPathCalculator createPathCalculator(final Network network, - final TravelDisutility travelCosts, final TravelTime travelTimes) { - RoutingNetwork routingNetwork = this.routingNetworks.get(network); - PreProcessDijkstra preProcessDijkstra = this.preProcessData.get(network); - - if (routingNetwork == null) { - routingNetwork = this.routingNetworkFactory.createRoutingNetwork(network); - - if (this.usePreProcessData) { - preProcessDijkstra = new PreProcessDijkstra(); - preProcessDijkstra.run(network); - this.preProcessData.put(network, preProcessDijkstra); - - for (RoutingNetworkNode node : routingNetwork.getNodes().values()) { - node.setDeadEndData(preProcessDijkstra.getNodeData(node.getNode())); - } - } - - this.routingNetworks.put(network, routingNetwork); - } - FastRouterDelegateFactory fastRouterFactory = new ArrayFastRouterDelegateFactory(); - - return new FastDijkstra(routingNetwork, travelCosts, travelTimes, preProcessDijkstra, fastRouterFactory); - } -} diff --git a/matsim/src/main/java/org/matsim/core/router/FreespeedFactorRouting.java b/matsim/src/main/java/org/matsim/core/router/FreespeedFactorRouting.java index b6a77a716cb..9962ca9b674 100644 --- a/matsim/src/main/java/org/matsim/core/router/FreespeedFactorRouting.java +++ b/matsim/src/main/java/org/matsim/core/router/FreespeedFactorRouting.java @@ -28,7 +28,7 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.PopulationFactory; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.gbl.Gbl; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.LeastCostPathCalculatorFactory; @@ -38,9 +38,9 @@ class FreespeedFactorRouting implements Provider { - private final PlansCalcRouteConfigGroup.TeleportedModeParams params; + private final RoutingConfigGroup.TeleportedModeParams params; - public FreespeedFactorRouting( PlansCalcRouteConfigGroup.TeleportedModeParams params ) { + public FreespeedFactorRouting( RoutingConfigGroup.TeleportedModeParams params ) { this.params = params; } diff --git a/matsim/src/main/java/org/matsim/core/router/FreespeedFactorRoutingModule.java b/matsim/src/main/java/org/matsim/core/router/FreespeedFactorRoutingModule.java index 1a58eb5758d..ddafdcf37e3 100644 --- a/matsim/src/main/java/org/matsim/core/router/FreespeedFactorRoutingModule.java +++ b/matsim/src/main/java/org/matsim/core/router/FreespeedFactorRoutingModule.java @@ -24,7 +24,7 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; import org.matsim.api.core.v01.population.*; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.TeleportedModeParams; +import org.matsim.core.config.groups.RoutingConfigGroup.TeleportedModeParams; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.LeastCostPathCalculator.Path; import org.matsim.core.utils.geometry.CoordUtils; @@ -61,7 +61,7 @@ public List calcRoute(RoutingRequest request) { final Facility toFacility = request.getToFacility(); final double departureTime = request.getDepartureTime(); final Person person = request.getPerson(); - + Leg newLeg = this.populationFactory.createLeg( this.mode ); newLeg.setDepartureTime( departureTime ); @@ -99,19 +99,19 @@ public String toString() { // we're still missing the time on the final link, which the agent has to drive on in the java mobsim // so let's calculate the final part. double speed = toLink.getFreespeed(depTime + path.travelTime); - + // correct by speed limit: if ( speed > params.getTeleportedModeFreespeedLimit() ) { speed = params.getTeleportedModeFreespeedLimit() ; } - + // now correct the travel time: double travelTimeLastLink = toLink.getLength() / speed; - + travTime = (int) (((int) path.travelTime + travelTimeLastLink) * this.params.getTeleportedModeFreespeedFactor()); Route route = this.populationFactory.getRouteFactories().createRoute(Route.class, fromLink.getId(), toLink.getId()); route.setTravelTime(travTime); - + // yyyyyy the following should actually rather come from the route! There is a RouteUtils.calcDistance( route ) . kai, nov'16 double dist = 0; if ((fromAct.getCoord() != null) && (toAct.getCoord() != null)) { diff --git a/matsim/src/main/java/org/matsim/core/router/LeastCostPathCalculatorModule.java b/matsim/src/main/java/org/matsim/core/router/LeastCostPathCalculatorModule.java index b8ff6a40616..d88a07ebe12 100644 --- a/matsim/src/main/java/org/matsim/core/router/LeastCostPathCalculatorModule.java +++ b/matsim/src/main/java/org/matsim/core/router/LeastCostPathCalculatorModule.java @@ -23,7 +23,7 @@ package org.matsim.core.router; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.*; @@ -35,17 +35,13 @@ public void install() { // yy The code below will install _one_ LeastCostPathCalculator, which will be Dijkstra or Landmarks or something. It will be the // same Landmarks instance for all modes ... although one could do better by doing the preprocessing separately for the different modes. // kai/mm, jan'17 - + Config config = getConfig(); - if (config.controler().getRoutingAlgorithmType().equals(ControlerConfigGroup.RoutingAlgorithmType.Dijkstra)) { + if (config.controller().getRoutingAlgorithmType().equals(ControllerConfigGroup.RoutingAlgorithmType.Dijkstra)) { bind(LeastCostPathCalculatorFactory.class).to(DijkstraFactory.class); - } else if (config.controler().getRoutingAlgorithmType().equals(ControlerConfigGroup.RoutingAlgorithmType.AStarLandmarks)) { + } else if (config.controller().getRoutingAlgorithmType().equals(ControllerConfigGroup.RoutingAlgorithmType.AStarLandmarks)) { bind(LeastCostPathCalculatorFactory.class).to(AStarLandmarksFactory.class); - } else if (config.controler().getRoutingAlgorithmType().equals(ControlerConfigGroup.RoutingAlgorithmType.FastDijkstra)) { - bind(LeastCostPathCalculatorFactory.class).to(FastDijkstraFactory.class); - } else if (config.controler().getRoutingAlgorithmType().equals(ControlerConfigGroup.RoutingAlgorithmType.FastAStarLandmarks)) { - bind(LeastCostPathCalculatorFactory.class).to(FastAStarLandmarksFactory.class); - } else if (config.controler().getRoutingAlgorithmType().equals(ControlerConfigGroup.RoutingAlgorithmType.SpeedyALT)) { + } else if (config.controller().getRoutingAlgorithmType().equals(ControllerConfigGroup.RoutingAlgorithmType.SpeedyALT)) { bind(LeastCostPathCalculatorFactory.class).to(SpeedyALTFactory.class); } } diff --git a/matsim/src/main/java/org/matsim/core/router/LinkToLinkRouting.java b/matsim/src/main/java/org/matsim/core/router/LinkToLinkRouting.java index b4e136e352f..2d83a752dcb 100644 --- a/matsim/src/main/java/org/matsim/core/router/LinkToLinkRouting.java +++ b/matsim/src/main/java/org/matsim/core/router/LinkToLinkRouting.java @@ -30,7 +30,7 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.PopulationFactory; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.NetworkInverter; import org.matsim.core.network.algorithms.NetworkTurnInfoBuilderI; @@ -50,7 +50,7 @@ public class LinkToLinkRouting SingleModeNetworksCache singleModeNetworksCache; @Inject - PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; + RoutingConfigGroup routingConfigGroup; @Inject LeastCostPathCalculatorFactory leastCostPathCalcFactory; @@ -120,7 +120,7 @@ public RoutingModule get() { ); // see NetworkRoutingProvider for some notes - if (!plansCalcRouteConfigGroup.getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none)) { + if (!routingConfigGroup.getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none)) { if (mode.equals(TransportMode.walk)) { return DefaultRoutingModules.createAccessEgressNetworkRouter(mode, leastCostPathCalculator, scenario, filteredNetwork, invertedNetwork, null,null, timeInterpretation, multimodalLinkChooser); diff --git a/matsim/src/main/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModule.java b/matsim/src/main/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModule.java index f75bfd22a20..748b8c2e1d5 100644 --- a/matsim/src/main/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModule.java +++ b/matsim/src/main/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModule.java @@ -19,7 +19,7 @@ package org.matsim.core.router; -import static org.matsim.core.config.groups.PlansCalcRouteConfigGroup.TeleportedModeParams; +import static org.matsim.core.config.groups.RoutingConfigGroup.TeleportedModeParams; import java.util.ArrayList; import java.util.Collections; @@ -42,8 +42,8 @@ import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.api.core.v01.population.Route; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; import org.matsim.core.gbl.Gbl; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PopulationUtils; @@ -82,7 +82,7 @@ public final class NetworkRoutingInclAccessEgressModule implements RoutingModule private final Config config; private static boolean hasWarnedAccessEgress = false; - private PlansCalcRouteConfigGroup.AccessEgressType accessEgressType; + private RoutingConfigGroup.AccessEgressType accessEgressType; private final TimeInterpretation timeInterpretation; private final MultimodalLinkChooser multimodalLinkChooser; @@ -112,7 +112,7 @@ public final class NetworkRoutingInclAccessEgressModule implements RoutingModule this.config = scenario.getConfig(); this.accessToNetworkRouter = accessToNetworkRouter; this.egressFromNetworkRouter = egressFromNetworkRouter; - this.accessEgressType = config.plansCalcRoute().getAccessEgressType(); + this.accessEgressType = config.routing().getAccessEgressType(); this.timeInterpretation = timeInterpretation; if (accessEgressType.equals(AccessEgressType.none)) { throw new RuntimeException("trying to use access/egress but not switched on in config. " @@ -228,7 +228,7 @@ private List computeEgressTripFromLinkToFacilityIfNecessary(final F Facility fromFacility = FacilitiesUtils.wrapLinkAndCoord(egressActLink,startCoord); List networkRoutedEgressTrip = egressFromNetworkRouter.calcRoute(DefaultRoutingRequest.of(fromFacility, toFacility, departureTime, person, routingAttributes)); if(networkRoutedEgressTrip == null) return null; - if (this.accessEgressType.equals(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLinkPlusTimeConstant)){ + if (this.accessEgressType.equals(RoutingConfigGroup.AccessEgressType.accessEgressModeToLinkPlusTimeConstant)){ double egressTime = NetworkUtils.getLinkEgressTime(egressActLink,mode).orElseThrow(()->new RuntimeException("Egress Time not set for link "+ egressActLink.getId().toString())); Leg leg0 = TripStructureUtils.getLegs(networkRoutedEgressTrip).get(0); double travelTime = leg0.getTravelTime().seconds()+egressTime; @@ -277,7 +277,7 @@ private List computeAccessTripFromFacilityToLinkIfNecessa // yyyy might be possible to set the link ids to null. kai & dominik, may'16 accessTrip.add(accessLeg); - } else if (accessEgressType.equals(PlansCalcRouteConfigGroup.AccessEgressType.walkConstantTimeToLink)) { + } else if (accessEgressType.equals(RoutingConfigGroup.AccessEgressType.walkConstantTimeToLink)) { Leg accessLeg = populationFactory.createLeg(TransportMode.walk); accessLeg.setDepartureTime(departureTime); Id startLinkId = fromFacility.getLinkId(); @@ -296,7 +296,7 @@ private List computeAccessTripFromFacilityToLinkIfNecessa Facility toFacility = FacilitiesUtils.wrapLinkAndCoord(accessActLink,endCoord); List networkRoutedAccessTrip = accessToNetworkRouter.calcRoute(DefaultRoutingRequest.of(fromFacility, toFacility, departureTime, person, routingAttributes)); if (networkRoutedAccessTrip == null) return null; //no access trip could be computed for accessMode - if (this.accessEgressType.equals(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLinkPlusTimeConstant)){ + if (this.accessEgressType.equals(RoutingConfigGroup.AccessEgressType.accessEgressModeToLinkPlusTimeConstant)){ double accessTime = NetworkUtils.getLinkAccessTime(accessActLink,mode).orElseThrow(()->new RuntimeException("Access Time not set for link "+ accessActLink.getId().toString())); Leg leg0 = TripStructureUtils.getLegs(networkRoutedAccessTrip).get(0); double travelTime = leg0.getTravelTime().seconds()+accessTime; @@ -321,9 +321,9 @@ private static Activity createInteractionActivity(final Coord interactionCoord, private static void routeBushwhackingLeg(Person person, Leg leg, Coord fromCoord, Coord toCoord, double depTime, Id dpLinkId, Id arLinkId, PopulationFactory pf, Config config) { - final PlansCalcRouteConfigGroup.TeleportedModeParams params; - PlansCalcRouteConfigGroup.TeleportedModeParams tmp; - final Map paramsMap = config.plansCalcRoute().getModeRoutingParams(); + final RoutingConfigGroup.TeleportedModeParams params; + RoutingConfigGroup.TeleportedModeParams tmp; + final Map paramsMap = config.routing().getModeRoutingParams(); if ((tmp = paramsMap.get(TransportMode.non_network_walk)) != null) { params = tmp; } else if ((tmp = paramsMap.get(TransportMode.walk)) != null) { diff --git a/matsim/src/main/java/org/matsim/core/router/NetworkRoutingProvider.java b/matsim/src/main/java/org/matsim/core/router/NetworkRoutingProvider.java index 83eaf596b3f..b40087b6891 100644 --- a/matsim/src/main/java/org/matsim/core/router/NetworkRoutingProvider.java +++ b/matsim/src/main/java/org/matsim/core/router/NetworkRoutingProvider.java @@ -30,7 +30,7 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.core.config.groups.NetworkConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; import org.matsim.core.router.costcalculators.TravelDisutilityFactory; @@ -53,7 +53,8 @@ public class NetworkRoutingProvider implements Provider{ @Inject Map travelTimes; @Inject Map travelDisutilityFactories; @Inject SingleModeNetworksCache singleModeNetworksCache; - @Inject PlansCalcRouteConfigGroup plansCalcRouteConfigGroup; + @Inject + RoutingConfigGroup routingConfigGroup; @Inject Network network; @Inject NetworkConfigGroup networkConfigGroup; @Inject PopulationFactory populationFactory; @@ -129,7 +130,7 @@ public RoutingModule get() { travelTime); // the following again refers to the (transport)mode, since it will determine the mode of the leg on the network: - if ( !plansCalcRouteConfigGroup.getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !routingConfigGroup.getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { /* * All network modes should fall back to the TransportMode.walk RoutingModule for access/egress to the Network. * However, TransportMode.walk cannot fallback on itself for access/egress to the Network, so don't pass a standard diff --git a/matsim/src/main/java/org/matsim/core/router/TripRouterModule.java b/matsim/src/main/java/org/matsim/core/router/TripRouterModule.java index 4a369308aed..bba1a592379 100644 --- a/matsim/src/main/java/org/matsim/core/router/TripRouterModule.java +++ b/matsim/src/main/java/org/matsim/core/router/TripRouterModule.java @@ -22,7 +22,7 @@ package org.matsim.core.router; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.network.algorithms.NetworkTurnInfoBuilder; import org.matsim.core.network.algorithms.NetworkTurnInfoBuilderI; @@ -47,20 +47,20 @@ public void install() { install(new LeastCostPathCalculatorModule()); install(new TransitRouterModule()); bind(SingleModeNetworksCache.class).asEagerSingleton(); - PlansCalcRouteConfigGroup routeConfigGroup = getConfig().plansCalcRoute(); + RoutingConfigGroup routeConfigGroup = getConfig().routing(); for (String mode : routeConfigGroup.getTeleportedModeFreespeedFactors().keySet()) { if (getConfig().transit().isUseTransit() && getConfig().transit().getTransitModes().contains(mode)) { // default config contains "pt" as teleported mode, but if we have simulated transit, this is supposed to override it // better solve this on the config level eventually. continue; } - addRoutingModuleBinding(mode).toProvider(new FreespeedFactorRouting(getConfig().plansCalcRoute().getModeRoutingParams().get(mode))); + addRoutingModuleBinding(mode).toProvider(new FreespeedFactorRouting(getConfig().routing().getModeRoutingParams().get(mode))); } for (String mode : routeConfigGroup.getTeleportedModeSpeeds().keySet()) { - addRoutingModuleBinding(mode).toProvider(new BeelineTeleportationRouting(getConfig().plansCalcRoute().getModeRoutingParams().get(mode))); + addRoutingModuleBinding(mode).toProvider(new BeelineTeleportationRouting(getConfig().routing().getModeRoutingParams().get(mode))); } - boolean linkToLinkRouting = getConfig().controler().isLinkToLinkRoutingEnabled(); + boolean linkToLinkRouting = getConfig().controller().isLinkToLinkRoutingEnabled(); if (linkToLinkRouting) { bind(NetworkTurnInfoBuilderI.class).to(NetworkTurnInfoBuilder.class) ; } diff --git a/matsim/src/main/java/org/matsim/core/router/TripStructureUtils.java b/matsim/src/main/java/org/matsim/core/router/TripStructureUtils.java index bf23e04d526..69ac6c3d0c3 100644 --- a/matsim/src/main/java/org/matsim/core/router/TripStructureUtils.java +++ b/matsim/src/main/java/org/matsim/core/router/TripStructureUtils.java @@ -29,7 +29,7 @@ import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.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.core.utils.misc.OptionalTime; @@ -56,7 +56,7 @@ public final class TripStructureUtils { private static final Logger log = LogManager.getLogger(TripStructureUtils.class); public static final String routingMode = "routingMode"; - + public enum StageActivityHandling {StagesAsNormalActivities, ExcludeStageActivities} private TripStructureUtils() {} @@ -150,7 +150,7 @@ public static List getTrips( if ( currentIndex - originActivityIndex > 1 ) { // which means, if I am understanding this right, that two activities without a leg in between will not be considered - // a trip. + // a trip. trips.add( new Trip( (Activity) planElements.get( originActivityIndex ), @@ -421,7 +421,7 @@ public List getTripElements() { public List getLegsOnly() { return legs; } - + /** * Attributes of preceding activity are passed as trip attributes until more explicit encoding is found. */ @@ -625,7 +625,7 @@ public static boolean isStageActivityType( String activityType ) { return StageActivityTypeIdentifier.isStageActivity( activityType ) ; } public static String createStageActivityType( String mode ) { - return PlanCalcScoreConfigGroup.createStageActivityType( mode ) ; + return ScoringConfigGroup.createStageActivityType( mode ) ; } } diff --git a/matsim/src/main/java/org/matsim/core/router/costcalculators/FreespeedTravelTimeAndDisutility.java b/matsim/src/main/java/org/matsim/core/router/costcalculators/FreespeedTravelTimeAndDisutility.java index c361cc362ab..14ccca62bfd 100644 --- a/matsim/src/main/java/org/matsim/core/router/costcalculators/FreespeedTravelTimeAndDisutility.java +++ b/matsim/src/main/java/org/matsim/core/router/costcalculators/FreespeedTravelTimeAndDisutility.java @@ -25,7 +25,7 @@ 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.gbl.Gbl; import org.matsim.core.router.util.LinkToLinkTravelTime; import org.matsim.core.router.util.TravelDisutility; @@ -46,7 +46,7 @@ * @author dgrether */ public class FreespeedTravelTimeAndDisutility implements TravelDisutility, TravelTime, LinkToLinkTravelTime { - + private static final Logger log = LogManager.getLogger(FreespeedTravelTimeAndDisutility.class); private final double travelCostFactor; @@ -80,7 +80,7 @@ public FreespeedTravelTimeAndDisutility(double scaledMarginalUtilityOfTraveling, this.marginalUtlOfDistance = scaledMarginalUtilityOfDistance; } - public FreespeedTravelTimeAndDisutility(PlanCalcScoreConfigGroup cnScoringGroup){ + public FreespeedTravelTimeAndDisutility(ScoringConfigGroup cnScoringGroup){ this(cnScoringGroup.getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() / 3600.0, cnScoringGroup.getPerforming_utils_hr() / 3600.0, // cnScoringGroup.getMarginalUtlOfDistanceCar()); cnScoringGroup.getModes().get(TransportMode.car).getMonetaryDistanceRate() *cnScoringGroup.getMarginalUtilityOfMoney()); @@ -115,5 +115,5 @@ public double getLinkTravelTime(Link link, double time, Person person, Vehicle v public double getLinkToLinkTravelTime(Link fromLink, Link toLink, double time, Person person, Vehicle vehicle) { return this.getLinkTravelTime(fromLink, time, null, null); } - + } diff --git a/matsim/src/main/java/org/matsim/core/router/costcalculators/RandomizingTimeDistanceTravelDisutilityFactory.java b/matsim/src/main/java/org/matsim/core/router/costcalculators/RandomizingTimeDistanceTravelDisutilityFactory.java index 56f299a0a58..68389ef5d99 100644 --- a/matsim/src/main/java/org/matsim/core/router/costcalculators/RandomizingTimeDistanceTravelDisutilityFactory.java +++ b/matsim/src/main/java/org/matsim/core/router/costcalculators/RandomizingTimeDistanceTravelDisutilityFactory.java @@ -23,7 +23,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.core.config.Config; -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; @@ -50,15 +50,15 @@ public class RandomizingTimeDistanceTravelDisutilityFactory implements TravelDis private final String mode; private final double sigma; - private final PlanCalcScoreConfigGroup cnScoringGroup; + private final ScoringConfigGroup cnScoringGroup; public RandomizingTimeDistanceTravelDisutilityFactory( final String mode, Config config ) { // NOTE: It is difficult to get rid of this constructor completely, since "mode" needs to be passed in. One could still get all other // material from injection, but there are many uses of this class outside injection. this.mode = mode; - this.cnScoringGroup = config.planCalcScore(); - this.sigma = config.plansCalcRoute().getRoutingRandomness(); + this.cnScoringGroup = config.scoring(); + this.sigma = config.routing().getRoutingRandomness(); } @Override @@ -69,14 +69,14 @@ public TravelDisutility createTravelDisutility( final TravelTime travelTime) { // a warning. However, we know by now that few people think about such warnings. kai, mar'20 logWarningsIfNecessary( cnScoringGroup ); - final PlanCalcScoreConfigGroup.ModeParams params = cnScoringGroup.getModes().get( mode ) ; + final ScoringConfigGroup.ModeParams params = cnScoringGroup.getModes().get( mode ) ; if ( params == null ) { throw new NullPointerException( mode+" is not part of the valid mode parameters "+cnScoringGroup.getModes().keySet() ); } /* Usually, the travel-utility should be negative (it's a disutility) but the cost should be positive. Thus negate the utility.*/ final double marginalCostOfTime_s = (-params.getMarginalUtilityOfTraveling() / 3600.0) + (cnScoringGroup.getPerforming_utils_hr() / 3600.0); - final double marginalCostOfDistance_m = - params.getMonetaryDistanceRate() * cnScoringGroup.getMarginalUtilityOfMoney() + final double marginalCostOfDistance_m = - params.getMonetaryDistanceRate() * cnScoringGroup.getMarginalUtilityOfMoney() - params.getMarginalUtilityOfDistance() ; double normalization = 1; @@ -95,7 +95,7 @@ public TravelDisutility createTravelDisutility( final TravelTime travelTime) { sigma); } - private void logWarningsIfNecessary(final PlanCalcScoreConfigGroup cnScoringGroup) { + private void logWarningsIfNecessary(final ScoringConfigGroup cnScoringGroup) { if ( wrnCnt.getAndIncrement() < 1 ) { if ( cnScoringGroup.getModes().get( mode ).getMonetaryDistanceRate() > 0. ) { log.warn("Monetary distance cost rate needs to be NEGATIVE to produce the normal " + @@ -108,12 +108,12 @@ private void logWarningsIfNecessary(final PlanCalcScoreConfigGroup cnScoringGrou " The routing disutility will only consider the ones of the default subpopulation."); log.warn( "This warning can safely be ignored if disutility of traveling only depends on travel time."); } - + if ( cnScoringGroup.getModes().get( mode ).getMonetaryDistanceRate() == 0. && this.sigma != 0. ) { log.warn("There will be no routing randomness. The randomization of the travel disutility requires the monetary distance rate " + "to be different than zero. Continuing anyway.") ; } - + if ( (cnScoringGroup.getModes().get( mode ).getMarginalUtilityOfTraveling() + cnScoringGroup.getPerforming_utils_hr()) == 0. && this.sigma != 0. ) { log.warn("There will be no routing randomness. The randomization of the travel disutility requires the travel time cost rate " + "to be different than zero. Continuing anyway.") ; diff --git a/matsim/src/main/java/org/matsim/core/router/costcalculators/TravelDisutilityModule.java b/matsim/src/main/java/org/matsim/core/router/costcalculators/TravelDisutilityModule.java index 436bfde5b9c..1be425e7f0f 100644 --- a/matsim/src/main/java/org/matsim/core/router/costcalculators/TravelDisutilityModule.java +++ b/matsim/src/main/java/org/matsim/core/router/costcalculators/TravelDisutilityModule.java @@ -22,14 +22,14 @@ package org.matsim.core.router.costcalculators; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.AbstractModule; public class TravelDisutilityModule extends AbstractModule { @Override public void install() { - PlansCalcRouteConfigGroup routeConfigGroup = getConfig().plansCalcRoute(); + RoutingConfigGroup routeConfigGroup = getConfig().routing(); for (String mode : routeConfigGroup.getNetworkModes()) { final RandomizingTimeDistanceTravelDisutilityFactory builder = new RandomizingTimeDistanceTravelDisutilityFactory( mode, getConfig() ); diff --git a/matsim/src/main/java/org/matsim/core/router/priorityqueue/HasIndex.java b/matsim/src/main/java/org/matsim/core/router/priorityqueue/HasIndex.java index abb3dc906cc..948012eece4 100644 --- a/matsim/src/main/java/org/matsim/core/router/priorityqueue/HasIndex.java +++ b/matsim/src/main/java/org/matsim/core/router/priorityqueue/HasIndex.java @@ -20,21 +20,17 @@ package org.matsim.core.router.priorityqueue; -import org.matsim.core.router.util.ArrayRoutingNetwork; -import org.matsim.core.router.util.ArrayRoutingNetworkNode; - /** * An interface to mark classes that enumerate their objects. Each index * should be unique and can e.g. be used to lookup values in an array. This feature * is used in some classed due to performance reasons since a lookup in an array * is much faster than in a map. - * - * @see ArrayRoutingNetwork - * @see ArrayRoutingNetworkNode + * * @see BinaryMinHeap - * + * * @author cdobler */ +@Deprecated // Id.index() should be used instead nowadays. public interface HasIndex { public int getArrayIndex(); diff --git a/matsim/src/main/java/org/matsim/core/router/speedy/SpeedyALT.java b/matsim/src/main/java/org/matsim/core/router/speedy/SpeedyALT.java index 7fc5a740218..fb2c56a7f35 100644 --- a/matsim/src/main/java/org/matsim/core/router/speedy/SpeedyALT.java +++ b/matsim/src/main/java/org/matsim/core/router/speedy/SpeedyALT.java @@ -23,7 +23,7 @@ * * This implementation always looks at all landmarks and does not filter them, as performance measurements * suggest that selecting and re-selecting landmarks regularly actually results in an overhead compared - * to to just calculate the values for each landmark in each step (using a typical value of 16 landmarks). + * to just calculate the values for each landmark in each step (using a typical value of 16 landmarks). * This might be due to the fact that all values for each landmark are just next to each other in the memory, * so when accessing the travelcosts to/from one landmark basically already loads the values of all landmarks in * the CPU cache, making the calculation for the remaining landmarks very fast. diff --git a/matsim/src/main/java/org/matsim/core/router/util/TravelDisutilityUtils.java b/matsim/src/main/java/org/matsim/core/router/util/TravelDisutilityUtils.java index 800a82a0853..1f6073fe875 100644 --- a/matsim/src/main/java/org/matsim/core/router/util/TravelDisutilityUtils.java +++ b/matsim/src/main/java/org/matsim/core/router/util/TravelDisutilityUtils.java @@ -18,7 +18,7 @@ * *********************************************************************** */ package org.matsim.core.router.util; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; /** @@ -27,8 +27,8 @@ */ public final class TravelDisutilityUtils { private TravelDisutilityUtils(){} // do not instantiate - - public static TravelDisutility createFreespeedTravelTimeAndDisutility(PlanCalcScoreConfigGroup cnScoringGroup) { + + public static TravelDisutility createFreespeedTravelTimeAndDisutility(ScoringConfigGroup cnScoringGroup) { return new FreespeedTravelTimeAndDisutility(cnScoringGroup) ; } diff --git a/matsim/src/main/java/org/matsim/core/scenario/ScenarioLoaderImpl.java b/matsim/src/main/java/org/matsim/core/scenario/ScenarioLoaderImpl.java index 7685b927f9a..c0667068e67 100644 --- a/matsim/src/main/java/org/matsim/core/scenario/ScenarioLoaderImpl.java +++ b/matsim/src/main/java/org/matsim/core/scenario/ScenarioLoaderImpl.java @@ -36,7 +36,6 @@ import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.io.PopulationReader; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.facilities.MatsimFacilitiesReader; import org.matsim.households.HouseholdsReaderV10; import org.matsim.lanes.LanesReader; @@ -50,6 +49,7 @@ import org.matsim.vehicles.MatsimVehicleReader; +import java.io.UncheckedIOException; import java.net.URL; import java.util.*; @@ -220,7 +220,7 @@ private void loadPopulation() { "file is used for the 10pct and the 1pct scenario. The material that is still there will follow. kai, jun'19" ); - final String outputDirectory = this.config.controler().getOutputDirectory(); + final String outputDirectory = this.config.controller().getOutputDirectory(); // final File outDir = new File( outputDirectory ); // if ( outDir.exists() && outDir.canWrite() ){ // // since ScenarioLoader is supposed to only read material, there are cases where the output directory does not exist at @@ -336,7 +336,7 @@ private void loadVehicles() throws UncheckedIOException { if ( vehiclesFile != null ) { log.info("loading vehicles from " + vehiclesFile ); new MatsimVehicleReader(this.scenario.getVehicles()).readURL(IOUtils.extendUrl(this.config.getContext(), vehiclesFile ) ); - } + } else { log.info("no vehicles file set in config, not loading any vehicles"); } diff --git a/matsim/src/main/java/org/matsim/core/scoring/NewScoreAssignerImpl.java b/matsim/src/main/java/org/matsim/core/scoring/NewScoreAssignerImpl.java index 6365ed3af25..c6dc3ac3656 100644 --- a/matsim/src/main/java/org/matsim/core/scoring/NewScoreAssignerImpl.java +++ b/matsim/src/main/java/org/matsim/core/scoring/NewScoreAssignerImpl.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.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import jakarta.inject.Inject; import java.util.HashMap; @@ -45,13 +45,13 @@ class NewScoreAssignerImpl implements NewScoreAssigner { private long scoreCount = 0; @Inject - NewScoreAssignerImpl(PlanCalcScoreConfigGroup planCalcScoreConfigGroup, ControlerConfigGroup controlerConfigGroup) { - if (planCalcScoreConfigGroup.getFractionOfIterationsToStartScoreMSA()!=null ) { - final int diff = controlerConfigGroup.getLastIteration() - controlerConfigGroup.getFirstIteration(); + NewScoreAssignerImpl(ScoringConfigGroup scoringConfigGroup, ControllerConfigGroup controllerConfigGroup) { + if (scoringConfigGroup.getFractionOfIterationsToStartScoreMSA()!=null ) { + final int diff = controllerConfigGroup.getLastIteration() - controllerConfigGroup.getFirstIteration(); this.scoreMSAstartsAtIteration = (int) (diff - * planCalcScoreConfigGroup.getFractionOfIterationsToStartScoreMSA() + controlerConfigGroup.getFirstIteration()); + * scoringConfigGroup.getFractionOfIterationsToStartScoreMSA() + controllerConfigGroup.getFirstIteration()); } - learningRate = planCalcScoreConfigGroup.getLearningRate(); + learningRate = scoringConfigGroup.getLearningRate(); } public void assignNewScores(int iteration, ScoringFunctionsForPopulation scoringFunctionsForPopulation, Population population) { diff --git a/matsim/src/main/java/org/matsim/core/scoring/PlansScoringImpl.java b/matsim/src/main/java/org/matsim/core/scoring/PlansScoringImpl.java index 79458c4b4d9..bc774cc2c1d 100644 --- a/matsim/src/main/java/org/matsim/core/scoring/PlansScoringImpl.java +++ b/matsim/src/main/java/org/matsim/core/scoring/PlansScoringImpl.java @@ -25,8 +25,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.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.corelisteners.PlansScoring; import org.matsim.core.controler.events.IterationEndsEvent; @@ -46,8 +46,8 @@ @Singleton final class PlansScoringImpl implements PlansScoring, ScoringListener, IterationEndsListener { - @Inject private PlanCalcScoreConfigGroup planCalcScoreConfigGroup; - @Inject private ControlerConfigGroup controlerConfigGroup; + @Inject private ScoringConfigGroup scoringConfigGroup; + @Inject private ControllerConfigGroup controllerConfigGroup; @Inject private Population population; @Inject private OutputDirectoryHierarchy controlerIO; @Inject private ScoringFunctionsForPopulation scoringFunctionsForPopulation; @@ -56,30 +56,30 @@ final class PlansScoringImpl implements PlansScoring, ScoringListener, Iteration @Override public void notifyScoring(final ScoringEvent event) { scoringFunctionsForPopulation.finishScoringFunctions(); - NewScoreAssignerImpl newScoreAssigner = new NewScoreAssignerImpl(this.planCalcScoreConfigGroup, this.controlerConfigGroup); + NewScoreAssignerImpl newScoreAssigner = new NewScoreAssignerImpl(this.scoringConfigGroup, this.controllerConfigGroup); newScoreAssigner.assignNewScores(event.getIteration(), this.scoringFunctionsForPopulation, this.population); } @Override public void notifyIterationEnds(final IterationEndsEvent event) { - this.experiencedPlansService.finishIteration(); + this.experiencedPlansService.finishIteration(); // (currently sets scores to experienced plans) - - if(planCalcScoreConfigGroup.isWriteExperiencedPlans()) { - final int writePlansInterval = controlerConfigGroup.getWritePlansInterval(); + + if(scoringConfigGroup.isWriteExperiencedPlans()) { + final int writePlansInterval = controllerConfigGroup.getWritePlansInterval(); if (writePlansInterval > 0 && (event.getIteration() % writePlansInterval == 0 || event.isLastIteration())) { this.experiencedPlansService.writeExperiencedPlans(controlerIO.getIterationFilename(event.getIteration(), "experienced_plans.xml.gz")); this.scoringFunctionsForPopulation.writePartialScores(controlerIO.getIterationFilename(event.getIteration(), "experienced_plans_scores.txt.gz")); } } - if (planCalcScoreConfigGroup.isMemorizingExperiencedPlans() ) { + if (scoringConfigGroup.isMemorizingExperiencedPlans() ) { for ( Person person : this.population.getPersons().values() ) { Plan experiencedPlan = this.experiencedPlansService.getExperiencedPlans().get( person.getId() ) ; if ( experiencedPlan==null ) { throw new RuntimeException("experienced plan is null; I don't think this should happen") ; } Plan selectedPlan = person.getSelectedPlan() ; - selectedPlan.getCustomAttributes().put(PlanCalcScoreConfigGroup.EXPERIENCED_PLAN_KEY, experiencedPlan ) ; + selectedPlan.getCustomAttributes().put(ScoringConfigGroup.EXPERIENCED_PLAN_KEY, experiencedPlan ) ; } } } diff --git a/matsim/src/main/java/org/matsim/core/scoring/ScoringFunctionsForPopulation.java b/matsim/src/main/java/org/matsim/core/scoring/ScoringFunctionsForPopulation.java index 71b3fbf6f6d..db1695f5492 100644 --- a/matsim/src/main/java/org/matsim/core/scoring/ScoringFunctionsForPopulation.java +++ b/matsim/src/main/java/org/matsim/core/scoring/ScoringFunctionsForPopulation.java @@ -49,7 +49,7 @@ import org.matsim.core.api.experimental.events.TeleportationArrivalEvent; import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.ControlerListenerManager; import org.matsim.core.controler.listener.BeforeMobsimListener; import org.matsim.core.controler.listener.IterationStartsListener; @@ -73,15 +73,15 @@ * This class helps EventsToScore by keeping ScoringFunctions for the entire Population - one per Person -, and dispatching Activities * and Legs to the ScoringFunctions. It also gives out the ScoringFunctions, so they can be given other events by EventsToScore. * It is not independently useful. Please do not make public. - * + * * @author michaz * */ final class ScoringFunctionsForPopulation implements BasicEventHandler { - + private final Population population; private final ScoringFunctionFactory scoringFunctionFactory; - + private final EventsToLegs legsDelegate; private final EventsToActivities actsDelegate; @@ -89,17 +89,17 @@ final class ScoringFunctionsForPopulation implements BasicEventHandler { private final IdMap partialScores = new IdMap<>(Person.class); private final AtomicReference exception = new AtomicReference<>(); private final IdMap tripRecords = new IdMap<>(Person.class); - + private final Vehicle2DriverEventHandler vehicles2Drivers = new Vehicle2DriverEventHandler(); @Inject ScoringFunctionsForPopulation(ControlerListenerManager controlerListenerManager, EventsManager eventsManager, EventsToActivities eventsToActivities, EventsToLegs eventsToLegs, Population population, ScoringFunctionFactory scoringFunctionFactory, Config config) { - ControlerConfigGroup controlerConfigGroup = config.controler(); - - if (controlerConfigGroup.getEventTypeToCreateScoringFunctions() == ControlerConfigGroup.EventTypeToCreateScoringFunctions.IterationStarts) { + ControllerConfigGroup controllerConfigGroup = config.controller(); + + if (controllerConfigGroup.getEventTypeToCreateScoringFunctions() == ControllerConfigGroup.EventTypeToCreateScoringFunctions.IterationStarts) { controlerListenerManager.addControlerListener((IterationStartsListener) event -> init()); - } else if (controlerConfigGroup.getEventTypeToCreateScoringFunctions() == ControlerConfigGroup.EventTypeToCreateScoringFunctions.BeforeMobsim) { + } else if (controllerConfigGroup.getEventTypeToCreateScoringFunctions() == ControllerConfigGroup.EventTypeToCreateScoringFunctions.BeforeMobsim) { controlerListenerManager.addControlerListener((BeforeMobsimListener) event -> init()); } else { throw new RuntimeException("Unknown approach when to create the scoring functions for population. Aborting..."); @@ -248,7 +248,7 @@ void handleActivity(PersonExperiencedActivity o) { TDoubleCollection partialScoresForAgent = this.partialScores.get(agentId); partialScoresForAgent.add(scoringFunction.getScore()); } - + Plan plan = this.tripRecords.get( agentId ); // as container for trip if ( plan!= null ) { plan.addActivity( activity ); diff --git a/matsim/src/main/java/org/matsim/core/scoring/functions/ActivityUtilityParameters.java b/matsim/src/main/java/org/matsim/core/scoring/functions/ActivityUtilityParameters.java index 82657accb18..22c4250f8bb 100644 --- a/matsim/src/main/java/org/matsim/core/scoring/functions/ActivityUtilityParameters.java +++ b/matsim/src/main/java/org/matsim/core/scoring/functions/ActivityUtilityParameters.java @@ -21,7 +21,7 @@ package org.matsim.core.scoring.functions; import org.matsim.core.api.internal.MatsimParameters; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.utils.misc.OptionalTime; /** @@ -114,7 +114,7 @@ public Builder(ActivityParams ppp ) { throw new RuntimeException("not defined"); } // seems to be somewhat overkill to set a computation method that is only used in the builder ... but the builder has a method to - // (re)set the + // (re)set the } diff --git a/matsim/src/main/java/org/matsim/core/scoring/functions/ModeUtilityParameters.java b/matsim/src/main/java/org/matsim/core/scoring/functions/ModeUtilityParameters.java index 37bb726da35..1e85fcffccd 100644 --- a/matsim/src/main/java/org/matsim/core/scoring/functions/ModeUtilityParameters.java +++ b/matsim/src/main/java/org/matsim/core/scoring/functions/ModeUtilityParameters.java @@ -21,7 +21,7 @@ package org.matsim.core.scoring.functions; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; /** * Class that stores parameters used from the scoring functions @@ -38,7 +38,7 @@ public static class Builder { public Builder() {} - public Builder( PlanCalcScoreConfigGroup.ModeParams params ) { + public Builder( ScoringConfigGroup.ModeParams params ) { this.marginalUtilityOfTraveling_s = params.getMarginalUtilityOfTraveling() / 3600.0; this.marginalUtilityOfDistance_m = params.getMarginalUtilityOfDistance(); this.monetaryDistanceRate = params.getMonetaryDistanceRate(); @@ -61,7 +61,7 @@ public Builder setMonetaryDistanceRate(double monetaryDistanceRate) { this.monetaryDistanceRate = monetaryDistanceRate; return this; } - + public Builder setConstant(double constant) { this.constant = constant; return this; @@ -71,7 +71,7 @@ public Builder setDailyMoneyConstant(double dailyMoneyConstant) { this.dailyMoneyConstant = dailyMoneyConstant; return this; } - + public Builder setDailyUtilityConstant(double dailyUtilityConstant) { this.dailyUtilityConstant = dailyUtilityConstant; return this; diff --git a/matsim/src/main/java/org/matsim/core/scoring/functions/ScoringParameters.java b/matsim/src/main/java/org/matsim/core/scoring/functions/ScoringParameters.java index 7502919af20..9193c2685bc 100644 --- a/matsim/src/main/java/org/matsim/core/scoring/functions/ScoringParameters.java +++ b/matsim/src/main/java/org/matsim/core/scoring/functions/ScoringParameters.java @@ -23,12 +23,11 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Person; import org.matsim.core.api.internal.MatsimParameters; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.config.groups.ScenarioConfigGroup; import org.matsim.core.population.PopulationUtils; -import org.matsim.core.utils.collections.ArrayMap; import java.util.Map; import java.util.TreeMap; @@ -46,9 +45,9 @@ public class ScoringParameters implements MatsimParameters { public final double marginalUtilityOfMoney; public final double abortedPlanScore; public final boolean scoreActs; - + public final boolean usingOldScoringBelowZeroUtilityDuration ; - + public final double simulationPeriodInDays; private ScoringParameters( @@ -110,8 +109,8 @@ public Builder( final Scenario scenario, final Person person ) { this( - scenario.getConfig().planCalcScore(), - scenario.getConfig().planCalcScore().getScoringParameters( PopulationUtils.getSubpopulation( person ) ), + scenario.getConfig().scoring(), + scenario.getConfig().scoring().getScoringParameters( PopulationUtils.getSubpopulation( person ) ), scenario.getConfig().scenario() ); } @@ -125,11 +124,11 @@ public Builder( */ @Deprecated public Builder( - final PlanCalcScoreConfigGroup configGroup, - final PlanCalcScoreConfigGroup.ScoringParameterSet scoringParameterSet, + final ScoringConfigGroup configGroup, + final ScoringConfigGroup.ScoringParameterSet scoringParameterSet, final ScenarioConfigGroup scenarioConfig) { this.simulationPeriodInDays = scenarioConfig.getSimulationPeriodInDays(); - + this.usingOldScoringBelowZeroUtilityDuration = configGroup.isUsingOldScoringBelowZeroUtilityDuration() ; marginalUtilityOfWaiting_s = scoringParameterSet.getMarginalUtlOfWaiting_utils_hr() / 3600.0; @@ -149,9 +148,9 @@ public Builder( } modeParams = new TreeMap<>() ; - Map modes = scoringParameterSet.getModes(); + Map modes = scoringParameterSet.getModes(); double worstMarginalUtilityOfTraveling_s = 0.0; - for (Map.Entry mode : modes.entrySet()) { + for (Map.Entry mode : modes.entrySet()) { String modeName = mode.getKey(); ModeParams params = mode.getValue(); worstMarginalUtilityOfTraveling_s = Math.min(worstMarginalUtilityOfTraveling_s, params.getMarginalUtilityOfTraveling() / 3600. ); @@ -179,8 +178,8 @@ public Builder( * @param scenarioConfig */ public Builder( - final PlanCalcScoreConfigGroup configGroup, - final PlanCalcScoreConfigGroup.ScoringParameterSet scoringParameterSet, + final ScoringConfigGroup configGroup, + final ScoringConfigGroup.ScoringParameterSet scoringParameterSet, Map activityParams, final ScenarioConfigGroup scenarioConfig) { this.simulationPeriodInDays = scenarioConfig.getSimulationPeriodInDays(); @@ -200,9 +199,9 @@ public Builder( utilParams = activityParams; modeParams = new TreeMap<>() ; - Map modes = scoringParameterSet.getModes(); + Map modes = scoringParameterSet.getModes(); double worstMarginalUtilityOfTraveling_s = 0.0; - for (Map.Entry mode : modes.entrySet()) { + for (Map.Entry mode : modes.entrySet()) { String modeName = mode.getKey(); ModeParams params = mode.getValue(); worstMarginalUtilityOfTraveling_s = Math.min(worstMarginalUtilityOfTraveling_s, params.getMarginalUtilityOfTraveling() / 3600. ); diff --git a/matsim/src/main/java/org/matsim/core/scoring/functions/SubpopulationScoringParameters.java b/matsim/src/main/java/org/matsim/core/scoring/functions/SubpopulationScoringParameters.java index 68ec1cfdc02..ac1c1b67bb7 100644 --- a/matsim/src/main/java/org/matsim/core/scoring/functions/SubpopulationScoringParameters.java +++ b/matsim/src/main/java/org/matsim/core/scoring/functions/SubpopulationScoringParameters.java @@ -21,7 +21,7 @@ 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.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.PlansConfigGroup; import org.matsim.core.config.groups.ScenarioConfigGroup; import org.matsim.core.population.PopulationUtils; @@ -36,22 +36,22 @@ * @author thibautd */ public class SubpopulationScoringParameters implements ScoringParametersForPerson { - private final PlanCalcScoreConfigGroup config; + private final ScoringConfigGroup config; private final ScenarioConfigGroup scConfig; private final TransitConfigGroup transitConfigGroup; private final Map params = new HashMap<>(); private final Population population; @Inject - SubpopulationScoringParameters(PlansConfigGroup plansConfigGroup, PlanCalcScoreConfigGroup planCalcScoreConfigGroup, ScenarioConfigGroup scenarioConfigGroup, Population population, TransitConfigGroup transitConfigGroup) { - this.config = planCalcScoreConfigGroup; + SubpopulationScoringParameters(PlansConfigGroup plansConfigGroup, ScoringConfigGroup scoringConfigGroup, ScenarioConfigGroup scenarioConfigGroup, Population population, TransitConfigGroup transitConfigGroup) { + this.config = scoringConfigGroup; this.scConfig = scenarioConfigGroup; this.transitConfigGroup = transitConfigGroup; this.population = population ; } public SubpopulationScoringParameters(Scenario scenario) { - this(scenario.getConfig().plans(), scenario.getConfig().planCalcScore(), scenario.getConfig().scenario(), scenario.getPopulation(), scenario.getConfig().transit()); + this(scenario.getConfig().plans(), scenario.getConfig().scoring(), scenario.getConfig().scenario(), scenario.getPopulation(), scenario.getConfig().transit()); } @Override @@ -71,7 +71,7 @@ public ScoringParameters getScoringParameters(Person person) { - PlanCalcScoreConfigGroup.ActivityParams transitActivityParams = new PlanCalcScoreConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); + ScoringConfigGroup.ActivityParams transitActivityParams = new ScoringConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); transitActivityParams.setTypicalDuration(120.0); transitActivityParams.setOpeningTime(0.) ; transitActivityParams.setClosingTime(0.) ; diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/ArrayBasedDataContainerProvider.java b/matsim/src/main/java/org/matsim/core/trafficmonitoring/ArrayBasedDataContainerProvider.java deleted file mode 100644 index 870e47c41c0..00000000000 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/ArrayBasedDataContainerProvider.java +++ /dev/null @@ -1,82 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * ArrayBasedDataContainerProvider.java - * * - * *********************************************************************** * - * * - * 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.core.trafficmonitoring; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; -import org.matsim.core.router.priorityqueue.HasIndex; - -import java.util.Map; - -/** - * Uses an array to store DataContainer object for the TravelTimeCalculator. - * It is tried to get a DataContainer's position in the array is taken from the - * the Link, which is possible if routing networks are used (there, link implement - * the HasIndex interface). - * - * If regular network are used, calls are forwarded to a MapBasedDataContainerProvider, - * which represents the lookup approach used so far. - * - * @author cdobler - */ -class ArrayBasedDataContainerProvider implements DataContainerProvider { - - private final TravelTimeData[] arrayLinkData; - private final DataContainerProvider delegate; - - public ArrayBasedDataContainerProvider(Map, TravelTimeData> linkData, TravelTimeDataFactory ttDataFactory, - Network network) { - this.arrayLinkData = new TravelTimeData[network.getLinks().size()]; - this.delegate = new MapBasedDataContainerProvider(linkData, ttDataFactory); - } - - /* - * This method is called from the EventHandler part of the TravelTimeCalculator. - * There, only link ids are available. We cannot optimize this. - */ - @Override - public TravelTimeData getTravelTimeData(final Id linkId, final boolean createIfMissing) { - return this.delegate.getTravelTimeData(linkId, createIfMissing); - } - - /* - * This method is called from the TravelTime part of the TravelTimeCalculator. - * There, links are available. we can optimize this by using an array instead of a map. - * - * Probably pre-initialize all DataContainers to avoid the null-check? - */ - @Override - public TravelTimeData getTravelTimeData(Link link, boolean createIfMissing) { - if (link instanceof HasIndex) { - int index = ((HasIndex) link).getArrayIndex(); - TravelTimeData data = this.arrayLinkData[index]; - if (data == null) { - data = this.delegate.getTravelTimeData(link, createIfMissing); - this.arrayLinkData[index] = data; - } - return data; - } else { - return this.delegate.getTravelTimeData(link, createIfMissing); - } - } - -} diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/DataContainerProvider.java b/matsim/src/main/java/org/matsim/core/trafficmonitoring/DataContainerProvider.java deleted file mode 100644 index f308d815669..00000000000 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/DataContainerProvider.java +++ /dev/null @@ -1,37 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * DataContainerProvider.java - * * - * *********************************************************************** * - * * - * 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.core.trafficmonitoring; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; - -interface DataContainerProvider { - - /* - * This method is called from the EventHandler part of the TravelTimeCalculator. - */ - /*package*/ TravelTimeData getTravelTimeData(final Id linkId, final boolean createIfMissing); - - /* - * This method is called from the TravelTime part of the TravelTimeCalculator. - */ - /*package*/ TravelTimeData getTravelTimeData(final Link link, final boolean createIfMissing); -} diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeCalculator.java b/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeCalculator.java index 9c243c87116..1c28d9a0b19 100644 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeCalculator.java +++ b/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeCalculator.java @@ -61,11 +61,7 @@ * at a node may take a different amount of time. *
    * Travel times on links are collected and averaged in bins/slots with a specified size - * (binSize, in seconds, default 900 seconds = 15 minutes). The data for the travel times per link - * is stored in {@link TravelTimeData}-objects. If a short binSize is used, it is useful to - * use {@link TravelTimeDataHashMap},} - * as that one does not use any memory to time bins where no traffic occurred. By default, - * {@link TravelTimeDataArray} is used. + * (binSize, in seconds, default 900 seconds = 15 minutes). * * @author dgrether * @author mrieser @@ -82,12 +78,10 @@ public final class TravelTimeCalculator implements LinkEnterEventHandler, LinkLe private final int numSlots; TimeSlotComputation aggregator; + private final Network network; + private IdMap linkData; - private IdMap linkData; - - private Map, Id>, TravelTimeData> linkToLinkData; - - private final DataContainerProvider dataContainerProvider; + private Map, Id>, TravelTimeDataArray> linkToLinkData; private final Map, LinkEnterEvent> linkEnterEvents; @@ -100,12 +94,10 @@ public final class TravelTimeCalculator implements LinkEnterEventHandler, LinkLe private final boolean calculateLinkToLinkTravelTimes; - private TravelTimeDataFactory ttDataFactory = null; - @Inject private QSimConfigGroup qsimConfig ; TravelTimeGetter travelTimeGetter ; - @Deprecated // user builder instead. kai, feb'19 + @Deprecated // use builder instead. kai, feb'19 public static TravelTimeCalculator create(Network network, TravelTimeCalculatorConfigGroup group) { TravelTimeCalculator calculator = new TravelTimeCalculator(network, group); configure(calculator, group, network); @@ -115,29 +107,15 @@ public static TravelTimeCalculator create(Network network, TravelTimeCalculatorC private static TravelTimeCalculator configure(TravelTimeCalculator calculator, TravelTimeCalculatorConfigGroup config, Network network) { // This should be replaced by a builder if we need the functionality. kai/mads, feb'19 - - // Customize micro-behavior of the TravelTimeCalculator based on config. Should not be necessary for most use cases. - switch ( config.getTravelTimeCalculatorType() ) { - case TravelTimeCalculatorArray: - calculator.ttDataFactory = new TravelTimeDataArrayFactory(network, calculator.numSlots); + switch( config.getTravelTimeGetterType() ){ + case "average": + calculator.travelTimeGetter = new AveragingTravelTimeGetter( calculator.aggregator ); break; - case TravelTimeCalculatorHashMap: - calculator.ttDataFactory = new TravelTimeDataHashMapFactory(network); + case "linearinterpolation": + calculator.travelTimeGetter = new LinearInterpolatingTravelTimeGetter( calculator.numSlots, calculator.timeSlice, calculator.aggregator ); break; default: - throw new RuntimeException(config.getTravelTimeCalculatorType() + " is unknown!"); - } - { - switch( config.getTravelTimeGetterType() ){ - case "average": - calculator.travelTimeGetter = new AveragingTravelTimeGetter( calculator.aggregator ); - break; - case "linearinterpolation": - calculator.travelTimeGetter = new LinearInterpolatingTravelTimeGetter( calculator.numSlots, calculator.timeSlice, calculator.aggregator ); - break; - default: - throw new RuntimeException( config.getTravelTimeGetterType() + " is unknown!" ); - } + throw new RuntimeException( config.getTravelTimeGetterType() + " is unknown!" ); } return calculator; } @@ -232,27 +210,14 @@ private TravelTimeCalculator(final Network network, final double timeslice, fina this.calculateLinkToLinkTravelTimes = calculateLinkToLinkTravelTimes; this.filterAnalyzedModes = filterModes; this.analyzedModes = analyzedModes; + this.network = network; this.timeSlice = timeslice; this.numSlots = TimeBinUtils.getTimeBinCount(maxTime, timeslice); this.aggregator = new TimeSlotComputation(this.numSlots, this.timeSlice); this.travelTimeGetter = new AveragingTravelTimeGetter( this.aggregator ) ; - this.ttDataFactory = new TravelTimeDataArrayFactory(network, this.numSlots); - if (this.calculateLinkTravelTimes){ + if (this.calculateLinkTravelTimes) { this.linkData = new IdMap<>(Link.class); - - /* - * So far, link data objects were stored in a HashMap. This lookup strategy is used - * by a MapBasedDataContainerProvider. - * When ArrayRoutingNetworks are used (as the FastRouter implementations do), the - * getArrayIndex() methods from the RoutingLinks can be used to lookup the link - * data objects in an array. This approach is implemented by the ArrayBasedDataContainerProvider. - * Using a ArrayBasedDataContainerProvider instead of a MapBasedDataContainerProvider - * increases the routing performance by 20-30%. - * cdobler, oct'13 - */ - // this.dataContainerProvider = new MapBasedDataContainerProvider(linkData, ttDataFactory); - this.dataContainerProvider = new ArrayBasedDataContainerProvider(linkData, ttDataFactory, network); - } else this.dataContainerProvider = null; + } if (this.calculateLinkToLinkTravelTimes){ // assume that every link has 2 outgoing links as default this.linkToLinkData = new ConcurrentHashMap<>((int) (network.getLinks().size() * 1.4 * 2)); @@ -289,7 +254,7 @@ public void handleEvent(final LinkLeaveEvent e) { if (this.calculateLinkTravelTimes) { LinkEnterEvent oldEvent = this.linkEnterEvents.get(e.getVehicleId()); if (oldEvent != null) { - TravelTimeData data = this.dataContainerProvider.getTravelTimeData(e.getLinkId(), true); + TravelTimeData data = this.getTravelTimeData(e.getLinkId(), true); double enterTime = oldEvent.getTime(); final int timeSlot = this.aggregator.getTimeSlotIndex(enterTime ); @@ -312,7 +277,7 @@ public void handleEvent(VehicleEntersTrafficEvent event) { @Override public void handleEvent(final VehicleLeavesTrafficEvent event) { /* remove EnterEvents from list when a vehicle arrives. - * otherwise, the activity duration would counted as travel time, when the + * otherwise, the activity duration would be counted as travel time, when the * vehicle departs again and leaves the link! */ this.linkEnterEvents.remove(event.getVehicleId()); @@ -323,7 +288,7 @@ public void handleEvent(final VehicleLeavesTrafficEvent event) { @Override public void handleEvent(VehicleArrivesAtFacilityEvent event) { /* remove EnterEvents from list when a bus stops on a link. - * otherwise, the stop time would counted as travel time, when the + * otherwise, the stop time would be counted as travel time, when the * bus departs again and leaves the link! */ this.linkEnterEvents.remove(event.getVehicleId()); } @@ -332,7 +297,7 @@ public void handleEvent(VehicleArrivesAtFacilityEvent event) { public void handleEvent(VehicleAbortsEvent event) { LinkEnterEvent e = this.linkEnterEvents.remove(event.getVehicleId()); if (e != null) { - TravelTimeData data = this.dataContainerProvider.getTravelTimeData(e.getLinkId(), true); + TravelTimeData data = this.getTravelTimeData(e.getLinkId(), true); data.setNeedsConsolidation( true ); // this.aggregator.addStuckEventTravelTime(data, e.getTime(), event.getTime()); @@ -351,57 +316,36 @@ public void handleEvent(VehicleAbortsEvent event) { if (filterAnalyzedModes) this.vehiclesToIgnore.remove(event.getVehicleId()); } - private TravelTimeData getLinkToLinkTravelTimeData( Tuple, Id> fromLinkToLink ) { - TravelTimeData data = this.linkToLinkData.get(fromLinkToLink); + private TravelTimeDataArray getTravelTimeData(final Id linkId, final boolean createIfMissing) { + TravelTimeDataArray data = this.linkData.get(linkId); + if ((null == data) && createIfMissing) { + data = this.createTravelTimeData(linkId); + this.linkData.put(linkId, data); + } + return data; + } + + private TravelTimeDataArray getLinkToLinkTravelTimeData( Tuple, Id> fromLinkToLink ) { + TravelTimeDataArray data = this.linkToLinkData.get(fromLinkToLink); if ( null == data ) { - data = this.ttDataFactory.createTravelTimeData(fromLinkToLink.getFirst()) ; + data = this.createTravelTimeData(fromLinkToLink.getFirst()) ; this.linkToLinkData.put(fromLinkToLink, data); } return data; } - /* - * Use the link as argument here! In case the DataContainer is array-based and the link is from a routing network, - * the DataContainer uses the link's index to access its data structures instead of performing a map lookup, which - * increases the router performance by 20-30%! - * cdobler, aug'17 - */ - private double getLinkTravelTime(final Link link, final double time) { + private TravelTimeDataArray createTravelTimeData(Id linkId) { + return new TravelTimeDataArray(this.network.getLinks().get(linkId), this.numSlots); + } + + private double getLinkTravelTime(final Id linkId, final double time) { if (this.calculateLinkTravelTimes) { - TravelTimeData data = this.dataContainerProvider.getTravelTimeData(link, true); + TravelTimeData data = this.getTravelTimeData(linkId, true); if ( data.isNeedingConsolidation() ) { consolidateData(data); } return this.travelTimeGetter.getTravelTime( data, time ); - - /* - * Workaround for jumps in returned travel times due to time bin approach? - * Should not be necessary when using linear interpolated travel times. - */ - // DataContainer data = this.dataContainerProvider.getTravelTimeInfo(link, true); - // if (data.needsConsolidation) { - // consolidateData(data); - // } - // double travelTime = this.aggregator.getTravelTime(data, time); - // - // // in case there is no previous time bin - // if (time <= this.timeSlice) return travelTime; - // - // int index = this.aggregator.getTimeSlotIndex(time); - // double previousBinEndTime = index * this.timeSlice; - // - // // calculate travel time when starting at the last second of the previous time slot - // double previousTravelTime = this.aggregator.getTravelTime(data, time - this.timeSlice); - // - // double prev = previousBinEndTime + previousTravelTime; - // double now = time + travelTime; - // if (now >= prev) { - // return travelTime; - // } - // else { - // return prev - time; // ensure travel time not shorter than travel time from the previous bin - // } } throw new IllegalStateException("No link travel time is available " + "if calculation is switched off by config option!"); @@ -511,7 +455,7 @@ public double getLinkTravelTime(Link link, double time, Person person, Vehicle v linkTtimeFromVehicle = link.getLength() / vehicleType.getMaximumVelocity(); } } - double linkTTimeFromObservation = TravelTimeCalculator.this.getLinkTravelTime(link, time); + double linkTTimeFromObservation = TravelTimeCalculator.this.getLinkTravelTime(link.getId(), time); return Math.max( linkTtimeFromVehicle, linkTTimeFromObservation) ; // yyyyyy should this not be min? kai/janek, may'19 // No, it is correct. It is preventing the router to route with an empirical speed from @@ -548,9 +492,4 @@ public double getLinkToLinkTravelTime(Link fromLink, Link toLink, double time, P }; } - @Deprecated // use builder.configure(config) instead. kai, feb'19 - public void setTtDataFactory( TravelTimeDataFactory ttDataFactory ){ - // yyyyyy this is currently here for a test, but should be removed. kai, feb'19 - this.ttDataFactory = ttDataFactory; - } } diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorModule.java b/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorModule.java index 08eccd999b6..687cc456271 100644 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorModule.java +++ b/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorModule.java @@ -37,7 +37,6 @@ import jakarta.inject.Inject; import jakarta.inject.Provider; -import java.util.Map; /** @@ -60,7 +59,7 @@ public void install() { } // go through all modes: // for (final String mode : CollectionUtils.stringToSet(getConfig().travelTimeCalculator().getAnalyzedModesAsString() )) { - for (final String mode : getConfig().plansCalcRoute().getNetworkModes() ) { + for (final String mode : getConfig().routing().getNetworkModes() ) { // generate and bind the observer: bind(TravelTimeCalculator.class).annotatedWith(Names.named(mode)).toProvider(new SingleModeTravelTimeCalculatorProvider(mode)).in(Singleton.class); @@ -89,7 +88,7 @@ public void install() { // bind the TravelTime objects. In this case, this just passes on the same information from TravelTimeCalculator to each individual mode: if (getConfig().travelTimeCalculator().isCalculateLinkTravelTimes()) { // for (String mode : CollectionUtils.stringToSet(getConfig().travelTimeCalculator().getAnalyzedModesAsString() )) { - for ( String mode : getConfig().plansCalcRoute().getNetworkModes() ) { + for ( String mode : getConfig().routing().getNetworkModes() ) { addTravelTimeBinding(mode).toProvider(ObservedLinkTravelTimes.class); } } diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataArray.java b/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataArray.java index d469ff9dac9..1e2a267aad0 100644 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataArray.java +++ b/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataArray.java @@ -26,7 +26,7 @@ /** * Implementation of {@link TravelTimeData} that stores the data per time bin - * in simple arrays. Useful if not too many empty time bins (time bins with + * in simple arrays. Useful if not too many empty time bins (time bins with * no traffic on a link) exist, so no memory is wasted. * * @author mrieser @@ -111,7 +111,7 @@ public double getTravelTime(final int timeSlot, final double now) { double ttime = traveltime(val); if (ttime >= 0.0) return ttime; // negative values are invalid. - // ttime can only be <0 if it never accumulated anything, i.e. if cnt == 9, so just use freespeed + // ttime can only be <0 if it never accumulated anything, i.e. if cnt == 0, so just use freespeed double freespeed = this.link.getLength() / this.link.getFreespeed(now); this.data[timeSlot] = encode(0, freespeed); return freespeed; diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataHashMap.java b/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataHashMap.java deleted file mode 100644 index 64775e96edb..00000000000 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeDataHashMap.java +++ /dev/null @@ -1,97 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TravelTimeRoleHashMap.java - * * - * *********************************************************************** * - * * - * 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.core.trafficmonitoring; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.matsim.api.core.v01.network.Link; -import org.matsim.core.network.NetworkUtils; -import org.matsim.core.utils.misc.IntegerCache; - -/** - * Implementation of {@link TravelTimeData} that stores the travel time data in - * a HashMap. This has the advantage that no memory is used if no vehicle travels - * over a link, and thus no data is available to be stored. Especially useful with - * short time bins as there the probability to have empty time bins is higher. - * - * @author mrieser - * @author glaemmel - */ -class TravelTimeDataHashMap extends TravelTimeData { - private final Map travelTimes; - - protected final Link link; - - public TravelTimeDataHashMap(final Link link) { - this.travelTimes = new ConcurrentHashMap<>(); - this.link = link; -// resetTravelTimes(); - } - - @Override - public void resetTravelTimes() { - this.travelTimes.clear(); - } - - @Override - public void setTravelTime( final int timeSlice, final double traveltime ) { - TimeStruct curr = this.travelTimes.get(IntegerCache.getInteger(timeSlice)); - if (curr != null) { - curr.cnt = 1; - curr.timeSum = traveltime; - } else { - this.travelTimes.put(IntegerCache.getInteger(timeSlice), new TimeStruct(traveltime,1)); - } - } - - @Override - public void addTravelTime(final int timeSlice, final double traveltime) { - TimeStruct curr = this.travelTimes.get(IntegerCache.getInteger(timeSlice)); - if (curr != null) { - curr.cnt += 1; - curr.timeSum += traveltime; - } else { - this.travelTimes.put(IntegerCache.getInteger(timeSlice), new TimeStruct(traveltime,1)); - } - } - - @Override - public double getTravelTime(final int timeSlice, final double now) { - - TimeStruct ts = this.travelTimes.get(IntegerCache.getInteger(timeSlice)); - if (ts == null) { - Link r = ((Link)this.link); - return NetworkUtils.getFreespeedTravelTime(r, now) ; - } - return ts.timeSum / ts.cnt; - } - - private static class TimeStruct { - public double timeSum; - public int cnt; - public TimeStruct(final double timeSum, final int cnt) { - this.cnt = cnt; - this.timeSum = timeSum; - } - } - -} diff --git a/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileReader.java b/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileReader.java index c401aa351f9..33bb84d6982 100644 --- a/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileReader.java +++ b/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileReader.java @@ -31,7 +31,6 @@ import org.geotools.geometry.jts.ReferencedEnvelope; import org.matsim.core.api.internal.MatsimSomeReader; import org.matsim.core.gbl.Gbl; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.Counter; import org.opengis.feature.Feature; import org.opengis.feature.simple.SimpleFeature; @@ -40,6 +39,7 @@ import java.io.File; import java.io.IOException; +import java.io.UncheckedIOException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; @@ -213,7 +213,7 @@ public SimpleFeatureType getSchema() { public Collection getFeatureSet() { return featureSet; } - + public CoordinateReferenceSystem getCoordinateSystem(){ return this.crs; } diff --git a/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileWriter.java b/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileWriter.java index f0257086934..2bb2650f814 100644 --- a/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileWriter.java +++ b/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileWriter.java @@ -26,12 +26,12 @@ import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.feature.DefaultFeatureCollection; import org.matsim.core.api.internal.MatsimSomeWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import java.io.File; import java.io.IOException; +import java.io.UncheckedIOException; import java.net.URL; import java.util.Collection; /** @@ -43,10 +43,10 @@ public class ShapeFileWriter implements MatsimSomeWriter { private static final Logger log = LogManager.getLogger(ShapeFileWriter.class); - + public static void writeGeometries(final Collection features, final String filename) { if (features.isEmpty()) { - throw new UncheckedIOException("Cannot write empty collection"); + throw new UncheckedIOException(new IOException("Cannot write empty collection")); } log.info("Writing shapefile to " + filename); try { @@ -58,7 +58,7 @@ public static void writeGeometries(final Collection features, fin DefaultFeatureCollection coll = new DefaultFeatureCollection(); coll.addAll(features); - + SimpleFeatureType featureType = features.iterator().next().getFeatureType(); datastore.createSchema(featureType); SimpleFeatureStore featureSource = (SimpleFeatureStore) datastore.getFeatureSource(); diff --git a/matsim/src/main/java/org/matsim/core/utils/io/AbstractMatsimWriter.java b/matsim/src/main/java/org/matsim/core/utils/io/AbstractMatsimWriter.java index f8bd823b167..76508d882e8 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/AbstractMatsimWriter.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/AbstractMatsimWriter.java @@ -24,6 +24,7 @@ import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; +import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.zip.GZIPOutputStream; @@ -75,7 +76,7 @@ protected final void openFile(final String filename) throws UncheckedIOException /** * Uses the specified OutputStream for writing. - * + * */ protected final void openOutputStream(OutputStream outputStream) { assertNotAlreadyOpen(); diff --git a/matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java b/matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java index e787add1b2b..e8667ea8c22 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java @@ -44,6 +44,7 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; +import java.io.UncheckedIOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; @@ -61,39 +62,39 @@ /** * This class provides helper methods for input/output in MATSim. - * + * * The whole I/O infrastructure is based on URLs, which allows more flexibility * than String-based paths or URLs. The structure follows three levels: Stream * level, writer/reader level, and convenience methods. - * + * *

    Stream level

    - * + * * The two main methods on the stream level are {@link #getInputStream(URL)} and * {@link #getOutputStream(URL, boolean)}. Their use is rather obvious, the * boolean argument of the output stream is whether it is an appending output * stream. Depending on the extension of the reference file of the URL, * compression will be detected automatically. See below for a list of active * compression algorithms. - * + * *

    Reader/Writer level

    - * + * * Use {@link #getBufferedWriter(URL, Charset, boolean)} and its simplified * versions to obtained a BufferedWriter object. Use * {@link #getBufferedReader(URL)} to obtain a BufferedReader. These functions * should be used preferredly, because they allow for future movements of files * to servers etc. - * + * *

    Convenience methods

    - * + * * Two convenience methods exist: {@link #getBufferedReader(String)} and * {@link #getBufferedReader(String)}, which take a String-based path as input. * They intentionally do not allow for much flexibility (e.g. choosing the * character set of the files). If this is needed, please use the reader/writer * level methods and construct the URL via the helper functions that are * documented below. - * + * *

    URL handling

    - * + * * To convert a file name to a URL, use {@link #getFileUrl(String)}. This is * mostly useful to determine the URL for an output file. If you are working * with input files, the best is to make use of @@ -101,13 +102,13 @@ * certain file in the file system and then in the class path (i.e. in the Java * resources). This makes it easy to write versatile code that can work with * local files and resources at the same time. - * + * *

    Compression

    - * + * * Compressed files are automatically assumed if certain file types are * encountered. Currently, the following patterns match certain compression * algorithms: - * + * *
      *
    • *.gz: GZIP compression
    • *
    • *.lz4: LZ4 compression
    • @@ -190,7 +191,7 @@ public static void setZstdCompressionLevel(int level) { /** * This function takes a path and tries to find the file in the file system or * in the resource path. The order of resolution is as follows: - * + * *
        *
      1. Find path in file system
      2. *
      3. Find path in file system with compression extension (e.g. *.gz)
      4. @@ -200,7 +201,7 @@ public static void setZstdCompressionLevel(int level) { * * In case the filename is a URL (i.e. starting with "file:" or "jar:file:"), * then no resolution is done but the provided filename returned as URL. - * + * * @throws UncheckedIOException */ public static URL resolveFileOrResource(String filename) throws UncheckedIOException { @@ -274,7 +275,7 @@ private static CompressionType getCompression(URL url) { * Opens an input stream for a given URL. If the URL has a compression * extension, the method will try to open the compressed file using the proper * decompression algorithm. - * + * * @throws UncheckedIOException */ public static InputStream getInputStream(URL url) throws UncheckedIOException { @@ -303,8 +304,10 @@ public static InputStream getInputStream(URL url) throws UncheckedIOException { } return new UnicodeInputStream(new BufferedInputStream(inputStream)); - } catch (IOException | CompressorException | GeneralSecurityException e) { + } catch (IOException e) { throw new UncheckedIOException(e); + } catch (CompressorException | GeneralSecurityException e) { + throw new UncheckedIOException(new IOException(e)); } } @@ -312,7 +315,7 @@ public static InputStream getInputStream(URL url) throws UncheckedIOException { * Creates a reader for an input URL. If the URL has a compression extension, * the method will try to open the compressed file using the proper * decompression algorithm. A given character set is used for the reader. - * + * * @throws UncheckedIOException */ public static BufferedReader getBufferedReader(URL url, Charset charset) throws UncheckedIOException { @@ -323,7 +326,7 @@ public static BufferedReader getBufferedReader(URL url, Charset charset) throws /** * See {@link #getBufferedReader(URL, Charset)}. UTF-8 is assumed as the * character set. - * + * * @throws UncheckedIOException */ public static BufferedReader getBufferedReader(URL url) throws UncheckedIOException { @@ -335,21 +338,21 @@ public static BufferedReader getBufferedReader(URL url) throws UncheckedIOExcept * extension, the method will try to open the compressed file using the proper * decompression algorithm. Note that compressed files cannot be appended and * that it is only possible to write to the file system (i.e. file:// protocol). - * + * * @throws UncheckedIOException */ @SuppressWarnings("resource") public static OutputStream getOutputStream(URL url, boolean append) throws UncheckedIOException { try { if (!url.getProtocol().equals("file")) { - throw new UncheckedIOException("Can only write to file:// protocol URLs"); + throw new UncheckedIOException(new IOException("Can only write to file:// protocol URLs")); } File file = new File(url.toURI()); CompressionType compression = getCompression(url); if ((compression != null && compression != CompressionType.ZSTD) && append && file.exists()) { - throw new UncheckedIOException("Cannot append to compressed files."); + throw new UncheckedIOException(new IOException("Cannot append to compressed files.")); } OutputStream outputStream = new FileOutputStream(file, append); @@ -372,8 +375,10 @@ public static OutputStream getOutputStream(URL url, boolean append) throws Unche } return new BufferedOutputStream(outputStream); - } catch (IOException | CompressorException | URISyntaxException e) { + } catch (IOException e) { throw new UncheckedIOException(e); + } catch (CompressorException | URISyntaxException e) { + throw new UncheckedIOException(new IOException(e)); } } @@ -382,8 +387,6 @@ public static OutputStream getOutputStream(URL url, boolean append) throws Unche * the method will try to open the compressed file using the proper * decompression algorithm. Note that compressed files cannot be appended and * that it is only possible to write to the file system (i.e. file:// protocol). - * - * @throws UncheckedIOException */ public static BufferedWriter getBufferedWriter(URL url, Charset charset, boolean append) throws UncheckedIOException { @@ -394,7 +397,7 @@ public static BufferedWriter getBufferedWriter(URL url, Charset charset, boolean /** * See {@link #getBufferedWriter(URL, Charset, boolean)}. UTF-8 is assumed as * the character set and non-appending mode is used. - * + * * @throws UncheckedIOException */ public static BufferedWriter getBufferedWriter(URL url) throws UncheckedIOException { @@ -404,7 +407,7 @@ public static BufferedWriter getBufferedWriter(URL url) throws UncheckedIOExcept /** * Wrapper function for {@link #getBufferedWriter(URL)} that creates a * PrintStream. - * + * * @throws UncheckedIOException */ public static PrintStream getPrintStream(URL url) throws UncheckedIOException { @@ -416,7 +419,7 @@ public static PrintStream getPrintStream(URL url) throws UncheckedIOException { * * @param fromStream The stream containing the data to be copied * @param toStream The stream the data should be written to - * + * * @throws UncheckedIOException */ public static void copyStream(final InputStream fromStream, final OutputStream toStream) @@ -438,7 +441,7 @@ public static void copyStream(final InputStream fromStream, final OutputStream t * should not be any accidents like following symbolic links. * * @param path The directory to be deleted - * + * * @throws UncheckedIOException */ public static void deleteDirectoryRecursively(Path path) throws UncheckedIOException { @@ -463,10 +466,10 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOEx /** * Compares two InputStreams. - * + * * Source: * http://stackoverflow.com/questions/4245863/fast-way-to-compare-inputstreams - * + * * @throws UncheckedIOException */ public static boolean isEqual(InputStream first, InputStream second) throws UncheckedIOException { @@ -491,9 +494,9 @@ public static boolean isEqual(InputStream first, InputStream second) throws Unch /** * Returns a URL for a (not necessarily existing) file path. - * + * * @param filename File name. - * + * * @throws UncheckedIOException */ public static URL getFileUrl(String filename) throws UncheckedIOException { @@ -506,10 +509,10 @@ public static URL getFileUrl(String filename) throws UncheckedIOException { /** * Given a base URL, returns the extended URL. - * + * * @param context Base URL, e.g. from the Config object. * @param extension Extended path specification. - * + * * @throws UncheckedIOException */ public static URL extendUrl(URL context, String extension) throws UncheckedIOException { @@ -527,7 +530,7 @@ public static URL extendUrl(URL context, String extension) throws UncheckedIOExc /** * Convenience wrapper, see {@link #getBufferedReader(URL, Charset)}. - * + * * Note, that in general you should rather use URLs and the respective * {@link #getBufferedReader(URL)} function. You can obtain URLs for your file * paths either using {@link #resolveFileOrResource(String)} for an existing diff --git a/matsim/src/main/java/org/matsim/core/utils/io/MatsimFileTypeGuesser.java b/matsim/src/main/java/org/matsim/core/utils/io/MatsimFileTypeGuesser.java index c98380c2b0e..f8869bbb6f6 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/MatsimFileTypeGuesser.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/MatsimFileTypeGuesser.java @@ -21,6 +21,7 @@ package org.matsim.core.utils.io; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.Locale; import javax.xml.parsers.ParserConfigurationException; @@ -139,9 +140,9 @@ private void guessFileTypeXml(final String fileName) throws UncheckedIOException } catch (IOException e) { throw new UncheckedIOException(e); } catch (SAXException e) { - throw new UncheckedIOException(e); + throw new UncheckedIOException(new IOException(e)); } catch (ParserConfigurationException e) { - throw new UncheckedIOException(e); + throw new UncheckedIOException(new IOException (e)); } catch (XMLTypeDetectionException e) { this.xmlPublicId = e.publicId; this.xmlSystemId = e.systemId; diff --git a/matsim/src/main/java/org/matsim/core/utils/io/MatsimXmlParser.java b/matsim/src/main/java/org/matsim/core/utils/io/MatsimXmlParser.java index 23f3753e48d..b245805efbc 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/MatsimXmlParser.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/MatsimXmlParser.java @@ -35,6 +35,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.URL; import java.net.URLConnection; import java.util.Stack; @@ -224,8 +225,10 @@ public final void parse(final InputSource input) throws UncheckedIOException { parser.parse(input, this); } } - } catch (SAXException | ParserConfigurationException | IOException e) { + } catch (IOException e) { throw new UncheckedIOException(e); + } catch (SAXException | ParserConfigurationException e) { + throw new UncheckedIOException(new IOException(e)); } } diff --git a/matsim/src/main/java/org/matsim/core/utils/io/MatsimXmlWriter.java b/matsim/src/main/java/org/matsim/core/utils/io/MatsimXmlWriter.java index c5bba306501..0b115e866ee 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/MatsimXmlWriter.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/MatsimXmlWriter.java @@ -24,6 +24,7 @@ import org.matsim.core.utils.misc.Time; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.List; import static org.matsim.core.utils.io.XmlUtils.encodeAttributeValue; diff --git a/matsim/src/main/java/org/matsim/core/utils/io/OsmNetworkReader.java b/matsim/src/main/java/org/matsim/core/utils/io/OsmNetworkReader.java index f967adccf76..f8e3f27c3f0 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/OsmNetworkReader.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/OsmNetworkReader.java @@ -22,6 +22,7 @@ import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; diff --git a/matsim/src/main/java/org/matsim/counts/CountsControlerListener.java b/matsim/src/main/java/org/matsim/counts/CountsControlerListener.java index 670af0ea897..ddff27eca43 100644 --- a/matsim/src/main/java/org/matsim/counts/CountsControlerListener.java +++ b/matsim/src/main/java/org/matsim/counts/CountsControlerListener.java @@ -26,7 +26,7 @@ import org.matsim.api.core.v01.IdMap; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.CountsConfigGroup; import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -63,7 +63,7 @@ class CountsControlerListener implements StartupListener, IterationEndsListener private GlobalConfigGroup globalConfigGroup; private Network network; - private ControlerConfigGroup controlerConfigGroup; + private ControllerConfigGroup controllerConfigGroup; private final CountsConfigGroup config; private final Set analyzedModes; private final VolumesAnalyzer volumesAnalyzer; @@ -77,10 +77,10 @@ class CountsControlerListener implements StartupListener, IterationEndsListener private int iterationsUsed = 0; @Inject - CountsControlerListener(GlobalConfigGroup globalConfigGroup, Network network, ControlerConfigGroup controlerConfigGroup, CountsConfigGroup countsConfigGroup, VolumesAnalyzer volumesAnalyzer, IterationStopWatch iterationStopwatch, OutputDirectoryHierarchy controlerIO) { + CountsControlerListener(GlobalConfigGroup globalConfigGroup, Network network, ControllerConfigGroup controllerConfigGroup, CountsConfigGroup countsConfigGroup, VolumesAnalyzer volumesAnalyzer, IterationStopWatch iterationStopwatch, OutputDirectoryHierarchy controlerIO) { this.globalConfigGroup = globalConfigGroup; this.network = network; - this.controlerConfigGroup = controlerConfigGroup; + this.controllerConfigGroup = controllerConfigGroup; this.config = countsConfigGroup; this.volumesAnalyzer = volumesAnalyzer; this.analyzedModes = CollectionUtils.stringToSet(this.config.getAnalyzedModes()); @@ -100,7 +100,7 @@ public void notifyStartup(final StartupEvent controlerStartupEvent) { @Override public void notifyIterationEnds(final IterationEndsEvent event) { if (counts != null && this.config.getWriteCountsInterval() > 0) { - if (useVolumesOfIteration(event.getIteration(), controlerConfigGroup.getFirstIteration())) { + if (useVolumesOfIteration(event.getIteration(), controllerConfigGroup.getFirstIteration())) { addVolumes(volumesAnalyzer); } diff --git a/matsim/src/main/java/org/matsim/facilities/FacilitiesFromPopulation.java b/matsim/src/main/java/org/matsim/facilities/FacilitiesFromPopulation.java index 6bd51412034..62ba74d01d3 100644 --- a/matsim/src/main/java/org/matsim/facilities/FacilitiesFromPopulation.java +++ b/matsim/src/main/java/org/matsim/facilities/FacilitiesFromPopulation.java @@ -41,8 +41,8 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.api.core.v01.population.Population; import org.matsim.core.config.groups.FacilitiesConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.gbl.Gbl; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PopulationUtils; @@ -67,7 +67,7 @@ public final class FacilitiesFromPopulation { private String idPrefix = ""; private Network network = null; private boolean removeLinksAndCoordinates = true; - private PlanCalcScoreConfigGroup planCalcScoreConfigGroup = null; + private ScoringConfigGroup scoringConfigGroup = null; private boolean addEmptyActivityOptions = false; public FacilitiesFromPopulation(final ActivityFacilities facilities) { @@ -86,7 +86,7 @@ public FacilitiesFromPopulation( Scenario scenario ) { this.addEmptyActivityOptions = true ; this.facilitiesSource = facilityConfigGroup.getFacilitiesSource(); this.network = scenario.getNetwork() ; - this.planCalcScoreConfigGroup = scenario.getConfig().planCalcScore() ; + this.scoringConfigGroup = scenario.getConfig().scoring() ; this.scenario = scenario; } public void setFacilitiesSource( final FacilitiesSource facilitiesSource ) { @@ -137,14 +137,14 @@ public void setRemoveLinksAndCoordinates(final boolean doRemoval) { this.removeLinksAndCoordinates = doRemoval; } - public void assignOpeningTimes( final PlanCalcScoreConfigGroup calcScoreConfigGroup ) { + public void assignOpeningTimes( final ScoringConfigGroup calcScoreConfigGroup ) { Gbl.assertNotNull( calcScoreConfigGroup ); - this.planCalcScoreConfigGroup = calcScoreConfigGroup ; + this.scoringConfigGroup = calcScoreConfigGroup ; } public void run(final Population population) { handleActivities(population); - if (this.planCalcScoreConfigGroup != null ) { + if (this.scoringConfigGroup != null ) { if (this.addEmptyActivityOptions) { this.assignOpeningTimes(); } else{ @@ -269,7 +269,7 @@ private void assignOpeningTimes() { for (ActivityFacility af : this.facilities.getFacilities().values()) { for (ActivityOption ao : af.getActivityOptions().values()) { String actType = ao.getType(); - ActivityParams params = this.planCalcScoreConfigGroup.getActivityParams(actType); + ActivityParams params = this.scoringConfigGroup.getActivityParams(actType); if (params == null) { if (missingActTypes.add(actType)) { log.error("No information for activity type " + actType + " found in given configuration."); diff --git a/matsim/src/main/java/org/matsim/guice/DependencyGraphControlerListener.java b/matsim/src/main/java/org/matsim/guice/DependencyGraphControlerListener.java index 8f0c94b3a82..37492d3f785 100644 --- a/matsim/src/main/java/org/matsim/guice/DependencyGraphControlerListener.java +++ b/matsim/src/main/java/org/matsim/guice/DependencyGraphControlerListener.java @@ -32,7 +32,7 @@ import com.google.inject.grapher.NodeId; import com.google.inject.spi.ProviderBinding; import com.google.inject.util.Types; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.events.StartupEvent; import org.matsim.core.controler.listener.ControlerListener; @@ -68,7 +68,7 @@ class DependencyGraphControlerListener implements StartupListener { } public void notifyStartup(StartupEvent event) { - if (event.getServices().getConfig().controler().isCreateGraphs()) { + if (event.getServices().getConfig().controller().isCreateGraphs()) { try (PrintWriter out = new PrintWriter(new File(controlerIO.getOutputFilename("modules.dot")))) { MatsimGrapher grapher = new MatsimGrapher(new AbstractInjectorGrapher.GrapherParameters() .setAliasCreator(bindings -> { @@ -82,7 +82,7 @@ public void notifyStartup(StartupEvent event) { allAliases.addAll(getMapBinderAliases(String.class, TravelTime.class, bindings)); allAliases.addAll(getMapBinderAliases(String.class, TravelDisutilityFactory.class, bindings)); allAliases.addAll(getMapBinderAliases(String.class, RoutingModule.class, bindings)); - allAliases.addAll(getMapBinderAliases(StrategyConfigGroup.StrategySettings.class, PlanStrategy.class, bindings)); + allAliases.addAll(getMapBinderAliases(ReplanningConfigGroup.StrategySettings.class, PlanStrategy.class, bindings)); allAliases.addAll(getMultibinderAliases(ControlerListener.class, bindings)); allAliases.addAll(getMultibinderAliases(SnapshotWriter.class, bindings)); allAliases.addAll(getMultibinderAliases(MobsimListener.class, bindings)); diff --git a/matsim/src/main/java/org/matsim/households/HouseholdsWriterV10.java b/matsim/src/main/java/org/matsim/households/HouseholdsWriterV10.java index 9416e7f2a80..b7c18924a10 100644 --- a/matsim/src/main/java/org/matsim/households/HouseholdsWriterV10.java +++ b/matsim/src/main/java/org/matsim/households/HouseholdsWriterV10.java @@ -26,15 +26,14 @@ 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 org.matsim.core.utils.misc.Counter; import org.matsim.households.algorithms.HouseholdAlgorithm; import org.matsim.utils.objectattributes.AttributeConverter; -import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesXmlWriterDelegate; import org.matsim.vehicles.Vehicle; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -46,7 +45,7 @@ */ public class HouseholdsWriterV10 extends MatsimXmlWriter implements HouseholdAlgorithm{ private static final Logger log = LogManager.getLogger( HouseholdsWriterV10.class ) ; - + private List> atts = new ArrayList<>(); private Households households; private final Map,AttributeConverter> attributeConverters = new HashMap<>(); @@ -75,14 +74,14 @@ public void writeFile(String filename) throws UncheckedIOException { this.writeXmlHead(); this.writeHeader(); } - + /*package*/ void writeEndAndCloseFile(){ - + this.writeEndTag(HouseholdsSchemaV10Names.HOUSEHOLDS); this.close(); } - - + + private void writeHeader(){ atts.clear(); atts.add(createTuple(XMLNS, MatsimXmlWriter.MATSIM_NAMESPACE)); @@ -90,7 +89,7 @@ private void writeHeader(){ atts.add(createTuple("xsi:schemaLocation", MATSIM_NAMESPACE + " " + DEFAULT_DTD_LOCATION + "households_v1.0.xsd")); this.writeStartTag(HouseholdsSchemaV10Names.HOUSEHOLDS, atts); } - + private void writeHouseholds(Households basicHouseholds) throws UncheckedIOException { Counter counter = new Counter("[HouseholdsWriter] wrote household # "); for (Household h : basicHouseholds.getHouseholds().values()) { diff --git a/matsim/src/main/java/org/matsim/pt/PtConstants.java b/matsim/src/main/java/org/matsim/pt/PtConstants.java index 2247f2709f0..4a252332dbe 100644 --- a/matsim/src/main/java/org/matsim/pt/PtConstants.java +++ b/matsim/src/main/java/org/matsim/pt/PtConstants.java @@ -24,11 +24,11 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.Activity; import org.matsim.core.api.internal.MatsimParameters; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; /** * An abstract class containing some constants used for public transportation. - * + * * @author mrieser */ public abstract class PtConstants implements MatsimParameters { @@ -36,11 +36,11 @@ public abstract class PtConstants implements MatsimParameters { /** * Type of an activity that somehow interacts with pt, e.g. to connect a walk leg * to a pt leg, or to connect two pt legs together where agents have to change lines. - * + * * @see Activity#setType(String) */ - public final static String TRANSIT_ACTIVITY_TYPE = PlanCalcScoreConfigGroup.createStageActivityType(TransportMode.pt); - + public final static String TRANSIT_ACTIVITY_TYPE = ScoringConfigGroup.createStageActivityType(TransportMode.pt); + // this is currently used for wait2link events where the mode is not clear (bus, rail...?!), theresa sep'2015 public final static String NETWORK_MODE = "pt unspecified"; diff --git a/matsim/src/main/java/org/matsim/pt/ReconstructingUmlaufBuilder.java b/matsim/src/main/java/org/matsim/pt/ReconstructingUmlaufBuilder.java index ba65434100f..a35eddeb6c5 100644 --- a/matsim/src/main/java/org/matsim/pt/ReconstructingUmlaufBuilder.java +++ b/matsim/src/main/java/org/matsim/pt/ReconstructingUmlaufBuilder.java @@ -31,8 +31,6 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; -import org.matsim.api.core.v01.network.Network; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; import org.matsim.core.gbl.Gbl; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.TransitLine; @@ -68,7 +66,7 @@ public int compare(UmlaufStueck o1, UmlaufStueck o2) { @Inject public ReconstructingUmlaufBuilder( Scenario scenario ) { // (normal constructor used from TransitQSimEngine for testing :-(. kai, mar'20) yy change - this.umlaufInterpolator = new UmlaufInterpolator(scenario.getNetwork(), scenario.getConfig().planCalcScore()); + this.umlaufInterpolator = new UmlaufInterpolator(scenario.getNetwork(), scenario.getConfig().scoring()); this.transitLines = scenario.getTransitSchedule().getTransitLines().values(); this.vehicles = scenario.getTransitVehicles(); this.umlaufIdsByVehicleId = new HashMap<>(); @@ -103,11 +101,11 @@ private void createUmlaeufe(){ printStatus(cnt); } } - + private Id getUmlaufIdForVehicleId(Id vehId){ return this.umlaufIdsByVehicleId.get(vehId); } - + private Id createUmlaufIdFromVehicle(Vehicle vehicle){ Id id = Id.create(vehicle.getId().toString() + "_" + vehicle.getType().getId().toString(), Umlauf.class); this.umlaufIdsByVehicleId.put(vehicle.getId(), id); @@ -146,7 +144,7 @@ private void createUmlaufStuecke() { log.info("... done generating UmlaufStuecke"); Collections.sort(this.umlaufStuecke, departureTimeComparator); } - + private void printStatus(int cnt){ if ( cnt%100==0 ) { System.out.print('.'); diff --git a/matsim/src/main/java/org/matsim/pt/UmlaufInterpolator.java b/matsim/src/main/java/org/matsim/pt/UmlaufInterpolator.java index 1555772b3ba..794bcb6a61c 100644 --- a/matsim/src/main/java/org/matsim/pt/UmlaufInterpolator.java +++ b/matsim/src/main/java/org/matsim/pt/UmlaufInterpolator.java @@ -27,7 +27,7 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; @@ -41,7 +41,7 @@ public final class UmlaufInterpolator { private final Network network; private final LeastCostPathCalculator routingAlgo; - public UmlaufInterpolator(Network network, final PlanCalcScoreConfigGroup config) { + public UmlaufInterpolator(Network network, final ScoringConfigGroup config) { super(); this.network = network; FreespeedTravelTimeAndDisutility travelTimes = new FreespeedTravelTimeAndDisutility(config); diff --git a/matsim/src/main/java/org/matsim/pt/config/TransitConfigGroup.java b/matsim/src/main/java/org/matsim/pt/config/TransitConfigGroup.java index 742ef7d945a..fa2be75da28 100644 --- a/matsim/src/main/java/org/matsim/pt/config/TransitConfigGroup.java +++ b/matsim/src/main/java/org/matsim/pt/config/TransitConfigGroup.java @@ -51,7 +51,7 @@ public class TransitConfigGroup extends ReflectiveConfigGroup { private static final String INSISTING_ON_USING_DEPRECATED_ATTRIBUTE_FILE = "insistingOnUsingDeprecatedAttributeFiles" ; private static final String USING_TRANSIT_IN_MOBSIM = "usingTransitInMobsim" ; - public enum TransitRoutingAlgorithmType {DijkstraBased, SwissRailRaptor} + public enum TransitRoutingAlgorithmType {@Deprecated DijkstraBased, SwissRailRaptor} public static final String TRANSIT_ATTRIBUTES_DEPRECATION_MESSAGE = "using the separate transit stops and lines attribute files is deprecated." + " Add the information directly into each stop or line, using " + @@ -67,7 +67,7 @@ public enum TransitRoutingAlgorithmType {DijkstraBased, SwissRailRaptor} private Set transitModes; private TransitRoutingAlgorithmType routingAlgorithmType = TransitRoutingAlgorithmType.SwissRailRaptor; - + // --- private static final String USE_TRANSIT = "useTransit"; private boolean useTransit = false; @@ -159,7 +159,7 @@ public Set getTransitModes() { public String getTransitLinesAttributesFile() { return transitLinesAttributesFile; } - + @StringSetter( TRANSIT_LINES_ATTRIBUTES ) public void setTransitLinesAttributesFile(final String transitLinesAttributesFile) { this.transitLinesAttributesFile = transitLinesAttributesFile; @@ -172,12 +172,12 @@ public String getTransitStopsAttributesFile() { public URL getTransitStopsAttributesFileURL(URL context) { return ConfigGroup.getInputFileURL(context, getTransitStopsAttributesFile()) ; } - + @StringSetter( TRANSIT_STOPS_ATTRIBUTES ) public void setTransitStopsAttributesFile(final String transitStopsAttributesFile) { this.transitStopsAttributesFile = transitStopsAttributesFile; } - + @StringGetter( USE_TRANSIT ) public boolean isUseTransit() { return this.useTransit; @@ -207,7 +207,7 @@ public String getInputScheduleCRS() { public void setInputScheduleCRS(String inputScheduleCRS) { this.inputScheduleCRS = inputScheduleCRS; } - + public static final String BOARDING_ACCEPTANCE_CMT="under which conditions agent boards transit vehicle" ; public enum BoardingAcceptance { checkLineAndStop, checkStopOnly } private BoardingAcceptance boardingAcceptance = BoardingAcceptance.checkLineAndStop ; @@ -217,7 +217,7 @@ public BoardingAcceptance getBoardingAcceptance() { public void setBoardingAcceptance(BoardingAcceptance boardingAcceptance) { this.boardingAcceptance = boardingAcceptance; } - + private boolean usingTransitInMobsim = true ; @StringSetter( USING_TRANSIT_IN_MOBSIM ) public final void setUsingTransitInMobsim( boolean val ) { diff --git a/matsim/src/main/java/org/matsim/pt/counts/OccupancyAnalyzer.java b/matsim/src/main/java/org/matsim/pt/counts/OccupancyAnalyzer.java deleted file mode 100644 index 46f103ab0f0..00000000000 --- a/matsim/src/main/java/org/matsim/pt/counts/OccupancyAnalyzer.java +++ /dev/null @@ -1,326 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * CalcTrRouteStats.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.pt.counts; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.IdMap; -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.core.api.experimental.events.VehicleArrivesAtFacilityEvent; -import org.matsim.core.api.experimental.events.VehicleDepartsAtFacilityEvent; -import org.matsim.core.api.experimental.events.handler.VehicleArrivesAtFacilityEventHandler; -import org.matsim.core.api.experimental.events.handler.VehicleDepartsAtFacilityEventHandler; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.vehicles.Vehicle; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -/** - * @author yChen - * @author mrieser / senozon - */ -public class OccupancyAnalyzer implements PersonEntersVehicleEventHandler, PersonLeavesVehicleEventHandler, - VehicleArrivesAtFacilityEventHandler, VehicleDepartsAtFacilityEventHandler, TransitDriverStartsEventHandler { - - private static final Logger log = LogManager.getLogger(OccupancyAnalyzer.class); - - private final int timeBinSize, maxSlotIndex; - private final double maxTime; - /** Map< stopFacilityId,value[]> */ - private Map, int[]> boards, alights, occupancies; - - /** Map< vehId,stopFacilityId> */ -// private final IdMap> vehStops = new IdMap<>(Vehicle.class, Id.class); - private final Map, Id> vehStops = new HashMap<>(); - /** Map */ - private final Map, Integer> vehPassengers = new HashMap<>(); - private StringBuffer occupancyRecord = new StringBuffer("time\tvehId\tStopId\tno.ofPassengersInVeh\n"); - private final Set> transitDrivers = new HashSet<>(); - private final Set> transitVehicles = new HashSet<>(); - - public OccupancyAnalyzer(final int timeBinSize, final double maxTime) { - this.timeBinSize = timeBinSize; - this.maxTime = maxTime; - this.maxSlotIndex = ((int) this.maxTime) / this.timeBinSize + 1; - this.boards = new IdMap<>(TransitStopFacility.class); - this.alights = new IdMap<>(TransitStopFacility.class); - this.occupancies = new IdMap<>(TransitStopFacility.class); - } - - public void setBoards(Map, int[]> boards) { - this.boards = boards; - } - - public void setAlights(Map, int[]> alights) { - this.alights = alights; - } - - public void setOccupancies(Map, int[]> occupancies) { - this.occupancies = occupancies; - } - - public int getTimeSlotIndex(final double time) { - if (time > this.maxTime) { - return this.maxSlotIndex; - } - return ((int) time / this.timeBinSize); - } - - @Override - public void reset(int iteration) { - this.boards.clear(); - this.alights.clear(); - this.occupancies.clear(); - this.vehStops.clear(); - this.vehPassengers.clear(); - this.occupancyRecord = new StringBuffer("time\tvehId\tStopId\tno.ofPassengersInVeh\n"); - this.transitDrivers.clear(); - this.transitVehicles.clear(); - } - - @Override - public void handleEvent(TransitDriverStartsEvent event) { - this.transitDrivers.add(event.getDriverId()); - this.transitVehicles.add(event.getVehicleId()); - } - - @Override - public void handleEvent(PersonEntersVehicleEvent event) { - if (this.transitDrivers.contains(event.getPersonId()) || !this.transitVehicles.contains(event.getVehicleId())) { - return; // ignore transit drivers or persons entering non-transit vehicles - } - - Id vehId = event.getVehicleId(); - Id stopId = this.vehStops.get(vehId); - double time = event.getTime(); - // --------------------------getOns--------------------------- - int[] getOn = this.boards.get(stopId); - if (getOn == null) { - getOn = new int[this.maxSlotIndex + 1]; - this.boards.put(stopId, getOn); - } - getOn[getTimeSlotIndex(time)]++; - // ------------------------veh_passenger--------------------------- - 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(PersonLeavesVehicleEvent event) { - if (this.transitDrivers.contains(event.getPersonId()) || !this.transitVehicles.contains(event.getVehicleId())) { - return; // ignore transit drivers or persons entering non-transit vehicles - } - - Id vehId = event.getVehicleId(); - Id stopId = this.vehStops.get(vehId); - double time = event.getTime(); - // --------------------------getDowns--------------------------- - int[] getDown = this.alights.get(stopId); - if (getDown == null) { - getDown = new int[this.maxSlotIndex + 1]; - this.alights.put(stopId, getDown); - } - getDown[getTimeSlotIndex(time)]++; - // ------------------------veh_passenger--------------------------- - Integer nPassengers = this.vehPassengers.get(vehId); - if (nPassengers == null) { - log.error( "tests for `null' but exception says 'negative'??? kai, oct'10 ") ; - throw new RuntimeException("negative passenger-No. in vehicle?"); - } - this.vehPassengers.put(vehId, nPassengers - 1); - if (this.vehPassengers.get(vehId).intValue() == 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(VehicleArrivesAtFacilityEvent event) { - Id stopId = event.getFacilityId(); - this.vehStops.put(event.getVehicleId(), stopId); - } - - @Override - public void handleEvent(VehicleDepartsAtFacilityEvent event) { - Id stopId = event.getFacilityId(); - Id vehId = event.getVehicleId(); - this.vehStops.remove(vehId); - // -----------------------occupancy-------------------------------- - int[] occupancyAtStop = this.occupancies.get(stopId); - - 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(stopId, 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(stopId); - this.occupancyRecord.append("\t"); - this.occupancyRecord.append(noPassengersInVeh); - this.occupancyRecord.append("\n"); - } - } - - /** - * @param stopId - * @return Array containing the number of agents boarding at the stop - * stopId per time bin, starting with time bin 0 from 0 - * seconds to (timeBinSize-1)seconds. - */ - public int[] getBoardVolumesForStop(final Id stopId) { - int[] values = this.boards.get(stopId); - if (values == null) { - return new int[this.maxSlotIndex + 1]; - } - return values; - } - - /** - * @param stopId - * @return Array containing the number of agents alighting at the stop - * {@code stopId} per time bin, starting with time bin 0 from 0 - * seconds to (timeBinSize-1)seconds. - */ - public int[] getAlightVolumesForStop(final Id stopId) { - int[] values = this.alights.get(stopId); - if (values == null) { - return new int[this.maxSlotIndex + 1]; - } - return values; - } - - /** - * @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. - */ - public int[] getOccupancyVolumesForStop(final Id stopId) { - int[] values = this.occupancies.get(stopId); - if (values == null) { - return new int[this.maxSlotIndex + 1]; - } - return values; - } - - /** - * @return Set of {@code Id}s containing all stop ids, where the agents - * boarded, for which counting-values are available. - */ - public Set> getBoardStopIds() { - return this.boards.keySet(); - } - - /** - * @return Set of {@code Id}s containing all stop ids, where the agents - * alit, for which counting-values are available. - */ - public Set> getAlightStopIds() { - return this.alights.keySet(); - } - - public Set> getOccupancyStopIds() { - return this.occupancies.keySet(); - } - - /** - * @return Set of {@code Id}s containing all stop ids, where the agents alit - * or/and boarded, for which counting-values are available. - */ - public Set> getAllStopIds() { - Set> allStopIds = new TreeSet<>(); - allStopIds.addAll(getBoardStopIds()); - allStopIds.addAll(getAlightStopIds()); - allStopIds.addAll(getOccupancyStopIds()); - return allStopIds; - } - - public void write(String filename) { - SimpleWriter writer = new SimpleWriter(filename); - // write filehead - writer.write("stopId\t"); - for (int i = 0; i < 24; i++) { - writer.write("bo" + i + "-" + (i + 1) + "\t"); - } - for (int i = 0; i < 24; i++) { - writer.write("al" + i + "-" + (i + 1) + "\t"); - } - for (int i = 0; i < 24; i++) { - writer.write("oc" + i + "-" + (i + 1) + "\t"); - } - writer.writeln(); - // write content - for (Id stopId : getAllStopIds()) { - writer.write(stopId + "\t"); - - int[] board = this.boards.get(stopId); - if (board == null){ - log.debug("stopId:\t" + stopId + "\thas null boards!"); - } - for (int i = 0; i < 24; i++) { - writer.write((board != null ? board[i] : 0) + "\t"); - } - - int[] alight = this.alights.get(stopId); - if (alight == null) { - log.debug("stopId:\t" + stopId + "\thas null alights!"); - } - for (int i = 0; i < 24; i++) { - writer.write((alight != null ? alight[i] : 0) + "\t"); - } - - int[] ocuppancy = this.occupancies.get(stopId); - if (ocuppancy == null) { - log.debug("stopId:\t" + stopId + "\tthere aren't passengers in Bus after the transfer!"); - } - for (int i = 0; i < 24; i++) { - writer.write((ocuppancy != null ? ocuppancy[i] : 0) + "\t"); - } - writer.writeln(); - } - writer.write(this.occupancyRecord.toString()); - writer.close(); - } -} diff --git a/matsim/src/main/java/org/matsim/pt/counts/PtCountControlerListener.java b/matsim/src/main/java/org/matsim/pt/counts/PtCountControlerListener.java deleted file mode 100644 index 703930250d9..00000000000 --- a/matsim/src/main/java/org/matsim/pt/counts/PtCountControlerListener.java +++ /dev/null @@ -1,195 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * CountControlerListener.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007 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.pt.counts; - -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.network.Network; -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.CountSimComparison; -import org.matsim.counts.Counts; -import org.matsim.counts.MatsimCountsReader; -import org.matsim.counts.algorithms.CountsComparisonAlgorithm; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -import jakarta.inject.Inject; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -public class PtCountControlerListener implements StartupListener, IterationEndsListener, -BeforeMobsimListener, AfterMobsimListener { - - private EventsManager eventsManager; - private OutputDirectoryHierarchy controlerIO; - private IterationStopWatch iterationStopWatch; - private Network network; - - private static enum CountType { Boarding, Alighting, Occupancy } - - private static final Logger log = LogManager.getLogger(PtCountControlerListener.class); - - /* - * String used to identify the operation in the IterationStopWatch. - */ - public static final String OPERATION_COMPAREPTCOUNTS = "compare with pt counts"; - - private final static String MODULE_NAME = "ptCounts"; - // yy the above should be removed; the commands should be replaced by the "typed" commands. kai, oct'10 - - private final Config config; - private final Counts boardCounts, alightCounts,occupancyCounts; - private final OccupancyAnalyzer occupancyAnalyzer; - - @Inject - PtCountControlerListener(final Config config, EventsManager eventsManager, OutputDirectoryHierarchy controlerIO, IterationStopWatch iterationStopWatch, Network network) { - this.eventsManager = eventsManager; - this.controlerIO = controlerIO; - this.iterationStopWatch = iterationStopWatch; - this.network = network; - log.info("Using pt counts."); - this.config = config; - this.boardCounts = new Counts(); - this.alightCounts = new Counts(); - this.occupancyCounts = new Counts(); - this.occupancyAnalyzer = new OccupancyAnalyzer(3600, 24 * 3600 - 1) ; - } - - @Override - public void notifyStartup(final StartupEvent controlerStartupEvent) { - PtCountsConfigGroup ptCounts = this.config.ptCounts(); - String boardCountsFilename = ptCounts.getBoardCountsFileName(); - String alightCountsFilename = ptCounts.getAlightCountsFileName(); - String occupancyCountsFilename = ptCounts.getOccupancyCountsFileName(); - if (boardCountsFilename == null || alightCountsFilename == null || occupancyCountsFilename == null) { - throw new RuntimeException("for pt counts, at this point all three files must be given!"); - } - new MatsimCountsReader(this.alightCounts).readFile(alightCountsFilename); - new MatsimCountsReader(this.boardCounts).readFile(boardCountsFilename); - new MatsimCountsReader(this.occupancyCounts).readFile(occupancyCountsFilename); - } - - @Override - public void notifyBeforeMobsim(BeforeMobsimEvent event) { - int iter = event.getIteration(); - if ( isActiveInThisIteration( iter ) ) { - occupancyAnalyzer.reset(iter); - eventsManager.addHandler(occupancyAnalyzer); - } - } - - @Override - public void notifyAfterMobsim(AfterMobsimEvent event) { - int it = event.getIteration(); - if ( isActiveInThisIteration( it ) ) { - eventsManager.removeHandler(occupancyAnalyzer); - occupancyAnalyzer.write(controlerIO.getIterationFilename(it, "occupancyAnalysis.txt")); - } - } - - private boolean isActiveInThisIteration( int iter ) { - return iter % config.ptCounts().getPtCountsInterval() == 0 && iter >= config.controler().getFirstIteration(); - } - - @Override - public void notifyIterationEnds(final IterationEndsEvent event) { - int iter = event.getIteration(); - if ( isActiveInThisIteration( iter ) ) { - - iterationStopWatch.beginOperation(OPERATION_COMPAREPTCOUNTS); - - double countsScaleFactor = Double.parseDouble(this.config.getParam(MODULE_NAME, "countsScaleFactor")); - - Map cca = new HashMap(); - cca.put( CountType.Boarding, new CountsComparisonAlgorithm(new CountsComparisonAlgorithm.VolumesForId() { - - @Override - public double[] getVolumesForStop(Id locationId) { - return copyFromIntArray(occupancyAnalyzer.getBoardVolumesForStop(locationId)); - } - }, this.boardCounts, network, countsScaleFactor)) ; - cca.put( CountType.Alighting, new CountsComparisonAlgorithm(new CountsComparisonAlgorithm.VolumesForId() { - - @Override - public double[] getVolumesForStop(Id locationId) { - return copyFromIntArray(occupancyAnalyzer.getAlightVolumesForStop(locationId)); - } - }, this.alightCounts, network, countsScaleFactor) ) ; - cca.put( CountType.Occupancy, new CountsComparisonAlgorithm(new CountsComparisonAlgorithm.VolumesForId() { - - @Override - public double[] getVolumesForStop(Id locationId) { - return copyFromIntArray(occupancyAnalyzer.getOccupancyVolumesForStop(locationId)); - } - }, this.occupancyCounts, network, countsScaleFactor) ) ; - - String distanceFilterStr = this.config.findParam(MODULE_NAME, "distanceFilter"); - String distanceFilterCenterNodeId = this.config.findParam(MODULE_NAME, "distanceFilterCenterNode"); - - if ((distanceFilterStr != null) && (distanceFilterCenterNodeId != null)) { - - - for ( CountsComparisonAlgorithm algo : cca.values() ) { - algo.setCountCoordUsingDistanceFilter(Double.parseDouble(distanceFilterStr), distanceFilterCenterNodeId) ; - } - } - for ( CountsComparisonAlgorithm algo : cca.values() ) { - algo.setCountsScaleFactor(countsScaleFactor); - algo.run(); - } - - String outputFormat = this.config.findParam(MODULE_NAME, "outputformat"); - if (outputFormat.contains("txt") || outputFormat.contains("all")) { - for ( Entry entry : cca.entrySet() ) { - CountsComparisonAlgorithm algo = entry.getValue() ; - new PtCountSimComparisonTableWriter(algo.getComparison()).write(controlerIO.getIterationFilename(iter, "simCountCompare" + entry.getKey().toString() + ".txt")); - } - } - - iterationStopWatch.endOperation(OPERATION_COMPAREPTCOUNTS); - } - } - - private static double[] copyFromIntArray(int[] source) { - double[] dest = new double[source.length]; - for(int i=0; i countSimCompList; - - public PtCountSimComparisonTableWriter(List countSimCompList) { - this.countSimCompList = countSimCompList; - } - - @Override - public void write(String filename) { - SimpleWriter simpleWriter = null; - try { - simpleWriter = new SimpleWriter(filename); - Id lastStopId = null; - // Sorted by stopId - for (CountSimComparison count : countSimCompList) { - Id stopId = Id.create(count.getId(), TransitStopFacility.class); - if (!stopId.equals(lastStopId)) { - simpleWriter.write("StopId :\t"); - simpleWriter.write(stopId.toString()); - simpleWriter.write("\nhour\tsimVal\tscaledSimVal\tcountVal\n"); - lastStopId = stopId; - } - simpleWriter.write(count.getHour()); - simpleWriter.write('\t'); - - double countValue = count.getCountValue(); - double simValue = count.getSimulationValue(); - - simpleWriter.write(simValue); - simpleWriter.write('\t'); - - simpleWriter.write(simValue); - simpleWriter.write('\t'); - simpleWriter.write(countValue); - simpleWriter.write('\n'); - - } - } finally { - if (simpleWriter != null) { - simpleWriter.close(); - } - } - } - -} diff --git a/matsim/src/main/java/org/matsim/pt/counts/PtCountsLoadCurveGraphCreator.java b/matsim/src/main/java/org/matsim/pt/counts/PtCountsLoadCurveGraphCreator.java deleted file mode 100644 index 536cda45fe6..00000000000 --- a/matsim/src/main/java/org/matsim/pt/counts/PtCountsLoadCurveGraphCreator.java +++ /dev/null @@ -1,83 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtCountsLoadCurveGraphCreator.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2010 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.pt.counts; - -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; -import org.matsim.counts.CountSimComparison; -import org.matsim.counts.algorithms.graphs.CountsGraph; -import org.matsim.counts.algorithms.graphs.CountsGraphsCreator; -import org.matsim.counts.algorithms.graphs.CountsLoadCurveGraph; -import org.matsim.counts.algorithms.graphs.helper.MyURL; - -public class PtCountsLoadCurveGraphCreator extends CountsGraphsCreator { - - /** - * @param sectionTitle - */ - public PtCountsLoadCurveGraphCreator(String sectionTitle) { - super(sectionTitle); - } - @Override - public List createGraphs(List ccl, - int iteration) { - List graphList=new Vector(); - - Iterator l_it = ccl.iterator(); - CountSimComparison cc_last=null; - while (l_it.hasNext()) { - CountsLoadCurveGraph lcg=new CountsLoadCurveGraph(ccl, iteration, "dummy"); - if (cc_last!=null) { - lcg.add2LoadCurveDataSets(cc_last); - } - CountSimComparison cc= l_it.next(); - Id stopId = cc.getId(); - while (cc.getId().equals(stopId)) { - if (l_it.hasNext()) { - lcg.add2LoadCurveDataSets(cc); - cc= l_it.next(); - } - else { - lcg.add2LoadCurveDataSets(cc); - break; - } - } - lcg.setChartTitle("Stop "+stopId); - lcg.setFilename("stop"+stopId); - lcg.setLinkId(stopId.toString()); - lcg.createChart(0); - graphList.add(lcg); - this.section.addURL(new MyURL("stop"+stopId+".html", "stop"+stopId)); - cc_last=cc; - }//while - - - return graphList; - } - -} diff --git a/matsim/src/main/java/org/matsim/pt/counts/PtCountsModule.java b/matsim/src/main/java/org/matsim/pt/counts/PtCountsModule.java deleted file mode 100644 index df66130b507..00000000000 --- a/matsim/src/main/java/org/matsim/pt/counts/PtCountsModule.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * *********************************************************************** * - * * project: org.matsim.* - * * PtCountsModule.java - * * * - * * *********************************************************************** * - * * * - * * copyright : (C) 2014 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.pt.counts; - -import org.matsim.core.controler.AbstractModule; - -public class PtCountsModule extends AbstractModule { - @Override - public void install() { - if (getConfig().transit().isUseTransit()) { - if (getConfig().ptCounts().getAlightCountsFileName() != null) { - // only works when all three files are defined! kai, oct'10 - addControlerListenerBinding().to(PtCountControlerListener.class); - } - } - } -} diff --git a/matsim/src/main/java/org/matsim/pt/counts/SimpleWriter.java b/matsim/src/main/java/org/matsim/pt/counts/SimpleWriter.java deleted file mode 100644 index 0eab92583e4..00000000000 --- a/matsim/src/main/java/org/matsim/pt/counts/SimpleWriter.java +++ /dev/null @@ -1,112 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * 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.pt.counts; - -import java.io.BufferedWriter; -import java.io.Closeable; -import java.io.Flushable; -import java.io.IOException; - -import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; - -/** - * a small and simple writer, in order to avoid copious "try" and "catch" for - * "Exception" - * - * @author yChen - * - */ -public class SimpleWriter implements Closeable, Flushable { - - private final BufferedWriter writer; - - public SimpleWriter(final String outputFilename) { - writer = IOUtils.getBufferedWriter(outputFilename); - } - - public void write(char[] c) { - if (writer != null) - try { - writer.write(c); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - public void write(char c) { - if (writer != null) - try { - writer.write(c); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - public void write(String s) { - if (writer != null) { - try { - writer.write(s); - } catch (IOException e) { - System.err.println("writer was not initialized yet!"); - throw new UncheckedIOException(e); - } - } - } - - public void write(Object o) { - write(o.toString()); - } - - public void writeln(String s) { - write(s + "\n"); - } - - public void writeln(Object o) { - write(o + "\n"); - } - - public void writeln() { - write('\n'); - } - - @Override - public void close() { - try { - writer.close(); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - @Override - public void flush() { - try { - writer.flush(); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - public void writeln(StringBuffer line) { - writeln(line.toString()); - } - -} diff --git a/matsim/src/main/java/org/matsim/pt/counts/obsolete/PtBiasErrorGraph.java b/matsim/src/main/java/org/matsim/pt/counts/obsolete/PtBiasErrorGraph.java deleted file mode 100644 index 2b29bf12005..00000000000 --- a/matsim/src/main/java/org/matsim/pt/counts/obsolete/PtBiasErrorGraph.java +++ /dev/null @@ -1,143 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtBiasErrorGraph.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2010 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.pt.counts.obsolete; - -import java.awt.Font; -import java.util.List; - -import org.jfree.chart.ChartFactory; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.axis.AxisLocation; -import org.jfree.chart.axis.CategoryAxis; -import org.jfree.chart.axis.NumberAxis; -import org.jfree.chart.axis.ValueAxis; -import org.jfree.chart.labels.StandardCategoryToolTipGenerator; -import org.jfree.chart.plot.CategoryPlot; -import org.jfree.chart.plot.DatasetRenderingOrder; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.chart.renderer.category.LineAndShapeRenderer; -import org.jfree.data.category.DefaultCategoryDataset; -import org.matsim.counts.ComparisonErrorStatsCalculator; -import org.matsim.counts.CountSimComparison; -import org.matsim.counts.algorithms.graphs.CountsGraph; - -/** - * @author yu - * - */ -public final class PtBiasErrorGraph extends CountsGraph { - private ComparisonErrorStatsCalculator errorStats; - private String chartTitle; - - /** - * @param ccl - * @param iteration - * @param filename - * @param chartTitle - */ - @Deprecated // use standard counts package - public PtBiasErrorGraph(List ccl, int iteration, - String filename, String chartTitle) { - super(ccl, iteration, filename, chartTitle); - this.chartTitle = chartTitle; - } - - @Override - @Deprecated // use standard counts package - public JFreeChart createChart(final int nbr) { - DefaultCategoryDataset dataset0 = new DefaultCategoryDataset(); - DefaultCategoryDataset dataset1 = new DefaultCategoryDataset(); - - this.errorStats = new ComparisonErrorStatsCalculator(this.ccl_); - - double[] meanRelError = errorStats.getMeanRelError(); - // double[] meanAbsError = errorStats.getMeanAbsError(); - double[] meanAbsBias = errorStats.getMeanBias(); - - for (int h = 0; h < 24; h++) { - dataset0.addValue(meanRelError[h], "Mean rel error", Integer - .toString(h + 1)); - // dataset1.addValue(meanAbsError[h], "Mean abs error", - // Integer.toString(h + 1)); - dataset1.addValue(meanAbsBias[h], "Mean bias", Integer - .toString(h + 1)); - } - - this.chart_ = ChartFactory.createLineChart(this.chartTitle, "Hour", - "Mean rel error [%]", dataset0, PlotOrientation.VERTICAL, true, // legend? - true, // tooltips? - false // URLs? - ); - CategoryPlot plot = this.chart_.getCategoryPlot(); - plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_RIGHT); - plot.setDataset(1, dataset1); - plot.mapDatasetToRangeAxis(1, 1); - - final LineAndShapeRenderer renderer = new LineAndShapeRenderer(); - renderer.setSeriesToolTipGenerator(0, - new StandardCategoryToolTipGenerator()); - plot.setRenderer(0, renderer); - - final CategoryAxis axis1 = new CategoryAxis("Hour"); - axis1.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 7)); - plot.setDomainAxis(axis1); - - // final ValueAxis axis2 = new - // NumberAxis("Mean abs {bias, error} [veh/h]"); - final ValueAxis axis2 = new NumberAxis("Mean abs bias [veh/h]"); - plot.setRangeAxis(1, axis2); - - final ValueAxis axis3 = plot.getRangeAxis(0); - axis3.setRange(0.0, 100.0); - - final LineAndShapeRenderer renderer2 = new LineAndShapeRenderer(); - renderer2.setSeriesToolTipGenerator(0, - new StandardCategoryToolTipGenerator()); - renderer2.setSeriesToolTipGenerator(1, - new StandardCategoryToolTipGenerator()); - // renderer2.setSeriesPaint(0, Color.black); - plot.setRenderer(1, renderer2); - plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE); - - return this.chart_; - } - - @Deprecated // use standard counts package - public double[] getMeanRelError() { - if (this.errorStats == null) { - throw new RuntimeException( - "Object not initialized correctly. Call createChart(..) first!"); - } - return this.errorStats.getMeanRelError(); - } - - @Deprecated // use standard counts package - public double[] getMeanAbsBias() { - if (this.errorStats == null) { - throw new RuntimeException( - "Object not initialized correctly. Call createChart(..) first!"); - } - return this.errorStats.getMeanBias(); - } -} \ No newline at end of file diff --git a/matsim/src/main/java/org/matsim/pt/counts/obsolete/PtCountSimComparisonWriter.java b/matsim/src/main/java/org/matsim/pt/counts/obsolete/PtCountSimComparisonWriter.java deleted file mode 100644 index 86e14b88b1d..00000000000 --- a/matsim/src/main/java/org/matsim/pt/counts/obsolete/PtCountSimComparisonWriter.java +++ /dev/null @@ -1,67 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtCountSimComparisonWriter.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2010 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.pt.counts.obsolete; - -import java.util.List; - -import org.matsim.core.api.internal.MatsimSomeWriter; -import org.matsim.counts.CountSimComparison; -import org.matsim.counts.algorithms.CountSimComparisonTimeFilter; - -@Deprecated // we should try to rather make CountSimComparisonKMLWriter more general. kai, dec'13 -public abstract class PtCountSimComparisonWriter implements MatsimSomeWriter { - public enum PtCountsType { - Boarding, Alighting, Occupancy - } - - @Deprecated // we should try to rather make CountSimComparisonKMLWriter more general. kai, dec'13 - protected int iter; - - @Deprecated // we should try to rather make CountSimComparisonKMLWriter more general. kai, dec'13 - protected CountSimComparisonTimeFilter boardCountComparisonFilter, alightCountComparisonFilter, occupancyCountComparisonFilter; - - /** - * - */ - @Deprecated // we should try to rather make CountSimComparisonKMLWriter more general. kai, dec'13 - public PtCountSimComparisonWriter(final List boardCountSimCompList, final List alightCountSimCompList, final List occupancyCountSimCompList) { - if ( boardCountSimCompList != null ) { - this.boardCountComparisonFilter = new CountSimComparisonTimeFilter(boardCountSimCompList); - } - if ( alightCountSimCompList!=null ) { - this.alightCountComparisonFilter = new CountSimComparisonTimeFilter(alightCountSimCompList); - } - if ( occupancyCountSimCompList != null ) { - this.occupancyCountComparisonFilter = new CountSimComparisonTimeFilter(occupancyCountSimCompList); - } - } - - @Deprecated // we should try to rather make CountSimComparisonKMLWriter more general. kai, dec'13 - public abstract void writeFile(final String filename); - - @Deprecated // we should try to rather make CountSimComparisonKMLWriter more general. kai, dec'13 - public void setIterationNumber(int iter) { - this.iter = iter; - } -} diff --git a/matsim/src/main/java/org/matsim/pt/counts/obsolete/PtCountsSimRealPerHourGraph.java b/matsim/src/main/java/org/matsim/pt/counts/obsolete/PtCountsSimRealPerHourGraph.java deleted file mode 100644 index 9a50b9a232c..00000000000 --- a/matsim/src/main/java/org/matsim/pt/counts/obsolete/PtCountsSimRealPerHourGraph.java +++ /dev/null @@ -1,234 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * CountsSimRealPerHourGraph.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007 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.pt.counts.obsolete; - -import java.awt.Color; -import java.awt.Font; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import org.jfree.chart.ChartFactory; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.annotations.XYTextAnnotation; -import org.jfree.chart.axis.LogarithmicAxis; -import org.jfree.chart.labels.CustomXYToolTipGenerator; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.chart.plot.XYPlot; -import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; -import org.jfree.chart.urls.CustomXYURLGenerator; -import org.jfree.data.xy.DefaultXYDataset; -import org.jfree.data.xy.XYSeries; -import org.jfree.data.xy.XYSeriesCollection; -import org.matsim.counts.CountSimComparison; -import org.matsim.counts.algorithms.graphs.CountsGraph; -import org.matsim.counts.algorithms.graphs.helper.Comp; -import org.matsim.counts.algorithms.graphs.helper.MyComparator; -import org.matsim.pt.counts.obsolete.PtCountSimComparisonWriter.PtCountsType; - -public final class PtCountsSimRealPerHourGraph extends CountsGraph { - /** - * The time at which the data was measured. A value in 1..24, 1 for 0 a.m. - * to 1 a.m., 2 for 1 a.m. to 2 a.m. ... - */ - private int hour; - /** - * the String type of Counts, e.g. "board" or "alight" - */ - private PtCountsType countsType; - - @Deprecated // use standard counts package - public PtCountsSimRealPerHourGraph(final List ccl, - final int iteration, final String filename, PtCountsType countsType) { - super(ccl, iteration, filename, filename); - this.countsType = countsType; - } - - /** - * @param hour - * A value in 1..24, 1 for 0 a.m. to 1 a.m., 2 for 1 a.m. to 2 - * a.m. ... - */ - @Override - @Deprecated // use standard counts package - public JFreeChart createChart(final int hour) { - this.hour = hour; - - XYSeriesCollection dataset0 = new XYSeriesCollection(); - XYSeries series = new XYSeries("MATSim volumes"); - // easier to use another dataset - XYSeriesCollection dataset_outliers = new XYSeriesCollection(); - XYSeries series_outliers = new XYSeries("MATSim outliers"); - - CustomXYURLGenerator url_gen = new CustomXYURLGenerator(); - CustomXYToolTipGenerator tt_gen = new CustomXYToolTipGenerator(); - - final ArrayList urls = new ArrayList(); - final ArrayList tooltips = new ArrayList(); - List comps = new Vector(); - - Iterator l_it = this.ccl_.iterator(); - // int elementCounter=0; - while (l_it.hasNext()) { - CountSimComparison cc = l_it.next(); - - /* - * values with simVal==0.0 or countVal==0.0 are drawn on the x==1 - * or/and y==1-line Such values are the result of a poor simulation - * run, but they can also represent a valid result (closing summer - * road during winter time) - */ - if (cc.getHour() == hour) { - // elementCounter++; - double realVal = 1.0; - double simVal = 1.0; - if (cc.getCountValue() > 0.0 && cc.getSimulationValue() > 0.0) { - realVal = cc.getCountValue(); - simVal = cc.getSimulationValue(); - series.add(realVal, simVal); - comps.add(new Comp(realVal, "link" + cc.getId() + ".html", - "Link " + cc.getId() + "; " + "Count: " + realVal - + ", Sim: " + simVal)); - } else { - realVal = Math.max(1.0, cc.getCountValue()); - simVal = Math.max(1.0, cc.getSimulationValue()); - series_outliers.add(realVal, simVal); - } - - }// if - }// while - dataset0.addSeries(series); - dataset_outliers.addSeries(series_outliers); - - /* - * first we have to sort the vector according to the rendering ordering - * (which is the x value). REALLY??? After hours of searching no better - * solution found! please help! - */ - - Collections.sort(comps, new MyComparator()); - - for (Iterator iter = comps.iterator(); iter.hasNext();) { - Comp cp = iter.next(); - urls.add(cp.getURL()); - tooltips.add(cp.getTooltip()); - } - - url_gen.addURLSeries(urls); - tt_gen.addToolTipSeries(tooltips); - - String title = "[" + this.countsType + "]\tVolumes " + (hour - 1) - + ":00 - " + (hour) + ":00, Iteration: " + this.iteration_; - this.setChartTitle(title); - this.chart_ = ChartFactory.createXYLineChart(title, - "Count Volumes [veh/h]", // x axis label - "Sim Volumes [veh/h]", // y axis label - dataset0, // data - PlotOrientation.VERTICAL, false, // include legend - true, // tooltips - true // urls - ); - XYPlot plot = this.chart_.getXYPlot(); - final LogarithmicAxis axis_x = new LogarithmicAxis( - "Count Volumes [veh/h]"); - final LogarithmicAxis axis_y = new LogarithmicAxis( - "Sim Volumes [veh/h]"); - axis_x.setAllowNegativesFlag(false); - axis_y.setAllowNegativesFlag(false); - - // regular values - XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); - renderer.setDefaultLinesVisible(false); - renderer.setURLGenerator(url_gen); - renderer.setSeriesPaint(0, Color.black); - renderer.setSeriesToolTipGenerator(0, tt_gen); - renderer - .setSeriesShape(0, new Rectangle2D.Double(-1.5, -1.5, 3.0, 3.0)); - - // outliers - XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(); - renderer2.setDefaultLinesVisible(false); - renderer2.setSeriesPaint(0, Color.red); - renderer2.setSeriesShape(0, new Ellipse2D.Double(-3.0, -3.0, 6.0, 6.0)); - - // error band - DefaultXYDataset dataset1 = new DefaultXYDataset(); - dataset1.addSeries("f1x", new double[][] { { 1.0, 10000.0 }, - { 1.0, 10000.0 } }); - dataset1.addSeries("f2x", new double[][] { { 1.0, 10000.0 }, - { 2.0, 20000.0 } }); - dataset1.addSeries("f05x", new double[][] { { 2.0, 10000.0 }, - { 1.0, 5000.0 } }); - - XYLineAndShapeRenderer renderer3 = new XYLineAndShapeRenderer(); - renderer3.setDefaultShapesVisible(false); - renderer3.setSeriesPaint(0, Color.blue); - renderer3.setSeriesPaint(1, Color.blue); - renderer3.setSeriesPaint(2, Color.blue); - renderer3.setDefaultSeriesVisibleInLegend(false); - renderer3.setSeriesItemLabelsVisible(0, true); - renderer3.setSeriesItemLabelsVisible(1, false); - renderer3.setSeriesItemLabelsVisible(2, false); - - XYTextAnnotation annotation0 = new XYTextAnnotation("2.0 count", - 12000.0, 15500.0); - annotation0.setFont(new Font("SansSerif", Font.BOLD, 11)); - plot.addAnnotation(annotation0); - XYTextAnnotation annotation1 = new XYTextAnnotation("count", 13000.0, - 10000.0); - annotation1.setFont(new Font("SansSerif", Font.BOLD, 11)); - plot.addAnnotation(annotation1); - XYTextAnnotation annotation2 = new XYTextAnnotation("0.5 count", - 11000.0, 3500.0); - annotation2.setFont(new Font("SansSerif", Font.BOLD, 11)); - plot.addAnnotation(annotation2); - - plot.setDomainAxis(axis_x); - plot.setRangeAxis(axis_y); - plot.setRenderer(0, renderer); - - plot.setRenderer(1, renderer2); - plot.setDataset(1, dataset_outliers); - - plot.setRenderer(2, renderer3); - plot.setDataset(2, dataset1); - - plot.getRangeAxis().setRange(1.0, 19000.0); - plot.getDomainAxis().setRange(1.0, 19000.0); - - return this.chart_; - }// drawGraph - - /** - * The time at which the data was measured. - * - * @return A value in 1..24, 1 for 0 a.m. to 1 a.m., 2 for 1 a.m. to 2 a.m. - * ... - */ - @Deprecated // use standard counts package - public int getHour() { - return this.hour; - } -} diff --git a/matsim/src/main/java/org/matsim/pt/router/AbstractTransitRouter.java b/matsim/src/main/java/org/matsim/pt/router/AbstractTransitRouter.java deleted file mode 100644 index 87639032e8f..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/AbstractTransitRouter.java +++ /dev/null @@ -1,208 +0,0 @@ - -/* *********************************************************************** * - * project: org.matsim.* - * AbstractTransitRouter.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2019 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - - package org.matsim.pt.router; - -import java.util.ArrayList; -import java.util.List; - -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.TransportMode; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Person; -import org.matsim.api.core.v01.population.Route; -import org.matsim.core.network.NetworkUtils; -import org.matsim.core.population.PopulationUtils; -import org.matsim.core.population.routes.RouteUtils; -import org.matsim.core.router.TripStructureUtils; -import org.matsim.core.utils.misc.OptionalTime; -import org.matsim.pt.routes.DefaultTransitPassengerRoute; -import org.matsim.pt.routes.TransitPassengerRoute; - -public class AbstractTransitRouter { - - private TransitRouterConfig trConfig; - private TransitTravelDisutility travelDisutility; - - protected AbstractTransitRouter (TransitRouterConfig transitRouterConfig){ - this.trConfig = transitRouterConfig; - } - - protected AbstractTransitRouter(TransitRouterConfig config, TransitTravelDisutility transitTravelDisutility){ - this.trConfig = config; - this.travelDisutility = transitTravelDisutility; - } - - // a setter is required for default PT router, I dont see any other way to make AbstractTransitRouter 'general purpose'. - protected void setTransitTravelDisutility(TransitTravelDisutility transitTravelDisutility){ - this.travelDisutility = transitTravelDisutility; - } - - // methods - protected final double getWalkTime(Person person, Coord coord, Coord toCoord) { - return getTravelDisutility().getWalkTravelTime(person, coord, toCoord); - } - - protected final double getTransferTime(Person person, Coord coord, Coord toCoord) { - return getTravelDisutility().getWalkTravelTime(person, coord, toCoord) + this.getConfig().getAdditionalTransferTime(); - } - - /** - * TODO: Replace by FallbackRoutingModule?! - gl-nov'19 - */ - @Deprecated - protected final List createDirectWalkLegList(Person person, Coord fromCoord, Coord toCoord) { - List legs = new ArrayList<>(); - Leg leg = PopulationUtils.createLeg(TransportMode.walk); - double walkTime = getWalkTime(person, fromCoord, toCoord); - leg.setTravelTime(walkTime); - TripStructureUtils.setRoutingMode(leg, TransportMode.pt); - Route walkRoute = RouteUtils.createGenericRouteImpl(null, null); - walkRoute.setTravelTime(walkTime); - leg.setRoute(walkRoute); - legs.add(leg); - return legs; - } - - private Leg createAccessTransitWalkLeg(Coord fromCoord, RouteSegment routeSegement) { - Leg leg = this.createTransitWalkLeg(fromCoord, routeSegement.fromStop.getCoord()); - Route walkRoute = RouteUtils.createGenericRouteImpl(null, routeSegement.fromStop.getLinkId()); - walkRoute.setTravelTime(leg.getTravelTime().seconds()); - walkRoute.setDistance(trConfig.getBeelineDistanceFactor() * NetworkUtils.getEuclideanDistance(fromCoord, routeSegement.fromStop.getCoord())); - leg.setRoute(walkRoute); - return leg; - } - - private Leg createEgressTransitWalkLeg(RouteSegment routeSegement, Coord toCoord) { - Leg leg = this.createTransitWalkLeg(routeSegement.toStop.getCoord(), toCoord); - Route walkRoute = RouteUtils.createGenericRouteImpl(routeSegement.toStop.getLinkId(), null); - walkRoute.setTravelTime(leg.getTravelTime().seconds()); - walkRoute.setDistance(trConfig.getBeelineDistanceFactor() * NetworkUtils.getEuclideanDistance(routeSegement.toStop.getCoord(), toCoord)); - leg.setRoute(walkRoute); - return leg; - } - - private Leg createTransferTransitWalkLeg(RouteSegment routeSegement) { - Leg leg = this.createTransitWalkLeg(routeSegement.getFromStop().getCoord(), routeSegement.getToStop().getCoord()); - Route walkRoute = RouteUtils.createGenericRouteImpl(routeSegement.getFromStop().getLinkId(), routeSegement.getToStop().getLinkId()); -// walkRoute.setTravelTime(leg.getTravelTime() ); - // transit walk leg should include additional transfer time; Amit, Aug'17 - leg.setTravelTime( getTransferTime(null, routeSegement.getFromStop().getCoord(), routeSegement.getToStop().getCoord()) ); - walkRoute.setTravelTime(getTransferTime(null, routeSegement.getFromStop().getCoord(), routeSegement.getToStop().getCoord()) ); - walkRoute.setDistance(trConfig.getBeelineDistanceFactor() * NetworkUtils.getEuclideanDistance(routeSegement.fromStop.getCoord(), routeSegement.toStop.getCoord())); - leg.setRoute(walkRoute); - - return leg; - } - - protected List convertPassengerRouteToLegList(double departureTime, InternalTransitPassengerRoute p, Coord fromCoord, Coord toCoord, Person person) { - // convert the route into a sequence of legs - List legs = new ArrayList<>(); - - // access leg - Leg accessLeg; - // check if first leg extends walking distance - if (p.getRoute().get(0).getRouteTaken() == null) { - // route starts with transfer - extend initial walk to that stop - //TODO: what if first leg extends the walking distance to more than first routeSegment i.e., (accessLeg, transfer, transfer ...). Amit Jan'18 -// accessLeg = createTransitWalkLeg(fromCoord, p.getRoute().get(0).getToStop().getCoord()); - accessLeg = createAccessTransitWalkLeg(fromCoord, p.getRoute().get(0)); - p.getRoute().remove(0); - } else { - // do not extend it - add a regular walk leg - // -// accessLeg = createTransitWalkLeg(fromCoord, p.getRoute().get(0).getFromStop().getCoord()); - accessLeg = createAccessTransitWalkLeg(fromCoord, p.getRoute().get(0)); - } - - // egress leg - Leg egressLeg; - // check if first leg extends walking distance - if (p.getRoute().get(p.getRoute().size() - 1).getRouteTaken() == null) { - // route starts with transfer - extend initial walk to that stop -// egressLeg = createTransitWalkLeg(p.getRoute().get(p.getRoute().size() - 1).getFromStop().getCoord(), toCoord); - egressLeg = createEgressTransitWalkLeg(p.getRoute().get(p.getRoute().size() - 1), toCoord); - p.getRoute().remove(p.getRoute().size() - 1); - } else { - // do not extend it - add a regular walk leg - // access leg -// egressLeg = createTransitWalkLeg(p.getRoute().get(p.getRoute().size() - 1).getToStop().getCoord(), toCoord); - egressLeg = createEgressTransitWalkLeg(p.getRoute().get(p.getRoute().size() - 1), toCoord); - } - - - // add very first leg - legs.add(accessLeg); - - // route segments are now in pt-walk-pt sequence - for (RouteSegment routeSegement : p.getRoute()) { - if (routeSegement.getRouteTaken() == null) {// transfer - if (!routeSegement.fromStop.equals(routeSegement.toStop)) { // same to/from stop => no transfer. Amit Feb'18 - legs.add(createTransferTransitWalkLeg(routeSegement)); - } - } else { - // pt leg - legs.add(createTransitLeg(routeSegement)); - } - } - - // add last leg - legs.add(egressLeg); - - return legs; - } - - private Leg createTransitLeg(RouteSegment routeSegment) { - Leg leg = PopulationUtils.createLeg(TransportMode.pt); - - TransitPassengerRoute ptRoute = new DefaultTransitPassengerRoute( // - routeSegment.getFromStop().getLinkId(), routeSegment.getToStop().getLinkId(), // - routeSegment.getFromStop().getId(), routeSegment.getToStop().getId(), // - routeSegment.getLineTaken(), routeSegment.getRouteTaken() - ); - - ptRoute.setTravelTime(routeSegment.travelTime); - leg.setRoute(ptRoute); - - leg.setTravelTime(routeSegment.getTravelTime()); - return leg; - } - - private Leg createTransitWalkLeg(Coord fromCoord, Coord toCoord) { - Leg leg = PopulationUtils.createLeg(TransportMode.walk); - double walkTime = getWalkTime(null, fromCoord, toCoord); - leg.setTravelTime(walkTime); - return leg; - } - - protected final TransitRouterConfig getConfig() { - return trConfig; - } - - protected final double getWalkDisutility(Person person, Coord coord, Coord toCoord) { - return getTravelDisutility().getWalkTravelDisutility(person, coord, toCoord); - } - - protected final TransitTravelDisutility getTravelDisutility() { - return travelDisutility; - } - -} \ No newline at end of file diff --git a/matsim/src/main/java/org/matsim/pt/router/CustomDataManager.java b/matsim/src/main/java/org/matsim/pt/router/CustomDataManager.java deleted file mode 100644 index 52ced005624..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/CustomDataManager.java +++ /dev/null @@ -1,73 +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.pt.router; - -import java.util.HashMap; - -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Node; - -/** - * A helper class to store custom data for {@link TransitTravelDisutility} which can be used - * to e.g. keep track of paid fares during the routing process. - * The stored data will be invalidated for each new routing request. - * - * @author mrieser / senozon - */ -public class CustomDataManager { - - private final HashMap data = new HashMap(); - private Node fromNode = null; - private Node toNode = null; - - private Object tmpToNodeData = null; - - public void setToNodeCustomData(final Object data) { - this.tmpToNodeData = data; - } - - /** - * @param node - * @return the stored data for the given node, or null if there is no data stored yet. - */ - public Object getFromNodeCustomData() { - return this.data.get(this.fromNode); - } - - public void initForLink(final Link link) { - this.fromNode = link.getFromNode(); - this.toNode = link.getToNode(); - this.tmpToNodeData = null; - } - - public void storeTmpData() { - if (this.tmpToNodeData != null) { - this.data.put(this.toNode, this.tmpToNodeData); - } - } - - public void reset() { - this.data.clear(); - this.fromNode = null; - this.toNode = null; - this.tmpToNodeData = null; - } - -} diff --git a/matsim/src/main/java/org/matsim/pt/router/MultiNodeDijkstra.java b/matsim/src/main/java/org/matsim/pt/router/MultiNodeDijkstra.java deleted file mode 100644 index 40c1258214a..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/MultiNodeDijkstra.java +++ /dev/null @@ -1,70 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TransitDijkstra.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 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.pt.router; - -import java.util.HashMap; -import java.util.Map; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.router.InitialNode; -import org.matsim.core.router.util.LeastCostPathCalculator.Path; -import org.matsim.core.router.util.TravelTime; - -public class MultiNodeDijkstra /*extends Dijkstra*/ { - - /** - * The network on which we find routes. - */ - protected Network network; - - /** - * The cost calculator. Provides the cost for each link and time step. - */ - private final TransitTravelDisutility costFunction; - - /** - * The travel time calculator. Provides the travel time for each link and time step. - */ - private final TravelTime timeFunction; - - public MultiNodeDijkstra(final Network network, final TransitTravelDisutility costFunction, final TravelTime timeFunction) { - this.network = network; - this.costFunction = costFunction; - this.timeFunction = timeFunction; - } - - @SuppressWarnings("unchecked") - public Path calcLeastCostPath(final Map fromNodes, final Map toNodes, final Person person) { - Map swapedToNodes = swapNodes(toNodes); - TransitLeastCostPathTree tree = new TransitLeastCostPathTree(network, costFunction, timeFunction, swapNodes(fromNodes), swapedToNodes, person); - return tree.getPath(swapedToNodes); - } - - private Map swapNodes(final Map original) { - Map result = new HashMap<>(); - for (Map.Entry entry : original.entrySet()) { - result.put(entry.getKey(), new InitialNode(entry.getValue().initialCost, entry.getValue().initialTime)); - } - return result; - } - -} diff --git a/matsim/src/main/java/org/matsim/pt/router/PreparedTransitSchedule.java b/matsim/src/main/java/org/matsim/pt/router/PreparedTransitSchedule.java index 0de8829631f..35a9c3c4131 100644 --- a/matsim/src/main/java/org/matsim/pt/router/PreparedTransitSchedule.java +++ b/matsim/src/main/java/org/matsim/pt/router/PreparedTransitSchedule.java @@ -29,19 +29,21 @@ import org.matsim.pt.transitSchedule.api.TransitSchedule; /** - * + * * Allows fast queries of a TransitSchedule for the next departure of a given route at a given stop, from a given point * in time. If you need further queries of a TransitSchedule, put them here! - * + * * (I renamed this class and put the TransitSchedule in the constructor to make the purpose clear. michaz '13) - * + * * Thread-safe. - * + * * @author mrieser * */ public class PreparedTransitSchedule { - + + final static double MIDNIGHT = 24.0*3600; + /* * This needs to be a ConcurrentHashMap since multiple threads might add * data concurrently. Alternatively, the map could be filled with data @@ -55,7 +57,7 @@ public class PreparedTransitSchedule { * Conceptually, an instance of this class wraps a TransitSchedule to optimize a function of it. */ public PreparedTransitSchedule(TransitSchedule schedule) { - + } @Deprecated @@ -65,20 +67,20 @@ public PreparedTransitSchedule(TransitSchedule schedule) { public PreparedTransitSchedule() { } - + public double getNextDepartureTime(final TransitRoute route, final TransitRouteStop stop, final double depTime) { - + double earliestDepartureTimeAtTerminus = depTime - stop.getDepartureOffset().seconds(); // This shifts my time back to the terminus. - - if (earliestDepartureTimeAtTerminus >= TransitRouterNetworkTravelTimeAndDisutility.MIDNIGHT) { - earliestDepartureTimeAtTerminus = earliestDepartureTimeAtTerminus % TransitRouterNetworkTravelTimeAndDisutility.MIDNIGHT; + + if (earliestDepartureTimeAtTerminus >= MIDNIGHT) { + earliestDepartureTimeAtTerminus = earliestDepartureTimeAtTerminus % MIDNIGHT; } if (earliestDepartureTimeAtTerminus < 0) { // this may happen when depTime < departureOffset, e.g. I want to start at 24:03, but the bus departs at 23:55 at terminus - earliestDepartureTimeAtTerminus += TransitRouterNetworkTravelTimeAndDisutility.MIDNIGHT; + earliestDepartureTimeAtTerminus += MIDNIGHT; } - + // this will search for the terminus departure that corresponds to my departure at the stop: double[] cache = sortedDepartureCache.get(route); if (cache == null) { @@ -102,14 +104,14 @@ public double getNextDepartureTime(final TransitRoute route, final TransitRouteS } double bestDepartureTime = cache[pos]; // (departure time at terminus) - + bestDepartureTime += stop.getDepartureOffset().seconds(); // (resulting departure time at stop) - + while (bestDepartureTime < depTime) { - bestDepartureTime += TransitRouterNetworkTravelTimeAndDisutility.MIDNIGHT; + bestDepartureTime += MIDNIGHT; // (add enough "MIDNIGHT"s until we are _after_ the desired departure time) } return bestDepartureTime; } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/pt/router/RouteSegment.java b/matsim/src/main/java/org/matsim/pt/router/RouteSegment.java deleted file mode 100644 index f3a9199504c..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/RouteSegment.java +++ /dev/null @@ -1,73 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * 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 * - * * - * *********************************************************************** */ - -package org.matsim.pt.router; - -import org.matsim.api.core.v01.Id; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -/** - * - * @author aneumann - * - */ -public class RouteSegment { - - final TransitStopFacility fromStop; - final TransitStopFacility toStop; - final double travelTime; - final Id lineTaken; - final Id routeTaken; - - public RouteSegment(TransitStopFacility fromStop, TransitStopFacility toStop, double travelTime, Id lineTaken, Id routeTaken) { - this.fromStop = fromStop; - this.toStop = toStop; - this.travelTime = travelTime; - this.lineTaken = lineTaken; - this.routeTaken = routeTaken; - } - - @Override - public String toString() { - return "From: " + fromStop.getId() + " to " + toStop.getId() + " in " + travelTime + "s via " + routeTaken; - } - - public double getTravelTime() { - return travelTime; - } - - public TransitStopFacility getFromStop() { - return fromStop; - } - - public TransitStopFacility getToStop() { - return toStop; - } - - public Id getLineTaken() { - return lineTaken; - } - - public Id getRouteTaken() { - return routeTaken; - } -} - diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitLeastCostPathTree.java b/matsim/src/main/java/org/matsim/pt/router/TransitLeastCostPathTree.java deleted file mode 100644 index 92a8f0202e2..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/TransitLeastCostPathTree.java +++ /dev/null @@ -1,534 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TransitDijkstra.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 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.pt.router; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.router.InitialNode; -import org.matsim.core.router.util.DijkstraNodeData; -import org.matsim.core.router.util.LeastCostPathCalculator.Path; -import org.matsim.core.router.util.TravelTime; -import org.matsim.core.utils.collections.PseudoRemovePriorityQueue; -import org.matsim.core.utils.collections.RouterPriorityQueue; -import org.matsim.pt.router.TransitRouterNetwork.TransitRouterNetworkLink; -import org.matsim.pt.router.TransitRouterNetwork.TransitRouterNetworkNode; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.vehicles.Vehicle; - -/** - * This class is based on and similar to org.matsim.pt.router.MultiNodeDijkstra - * - * In contrast to org.matsim.pt.router.MultiNodeDijkstra, however, it stores the last - * LeastCostPathTree. It is, therefore, much faster than it, in cases where many routes - * starting with the same fromNode are calculated subsequently as every route from that - * fromCoord can be retrieved now without having to compute the tree again. - * - * Call createLeastCostPathTree(fromNodes, person, fromCoord) in order to create and cache the - * LeastCostPathTree. Every following call of getPath(toNodes) will return the leastCostPath - * from the fromNodes to the toNodes. - * - * The fromCoord you passed in createLeastCostPathTree operates as a primary key to determine - * if you are working with the LeastCostPathTree you think you are. You can just pass the - * original requested origin here. - * - * Please keep in mind, that you are responsible to order all queries in a way such that all - * those originating in the same fromCoord are done subsequently. Otherwise, the mentioned - * efficiency gain with not take effect. - * - * @author gthunig - */ -public class TransitLeastCostPathTree { - - /** - * The network on which we find routes. - */ - protected Network network; - - /** - * The cost calculator. Provides the cost for each link and time step. - */ - private final TransitTravelDisutility costFunction; - - /** - * The travel time calculator. Provides the travel time for each link and time step. - */ - private final TravelTime timeFunction; - - private final HashMap, DijkstraNodeData> nodeData; - private Person person = null; - private Vehicle vehicle = null; - private CustomDataManager customDataManager = new CustomDataManager(); - private Map fromNodes = null; - - private RouterPriorityQueue pendingNodes; - - public TransitLeastCostPathTree(final Network network, final TransitTravelDisutility costFunction, - final TravelTime timeFunction, - final Map fromNodes, final Person person) { - this.network = network; - this.costFunction = costFunction; - this.timeFunction = timeFunction; - - this.nodeData = new HashMap<>((int)(network.getNodes().size() * 1.1), 0.95f); - - //create tree - this.resetNetworkVisited(); - this.person = person; - this.customDataManager.reset(); - this.fromNodes = fromNodes; - - pendingNodes = (RouterPriorityQueue) createRouterPriorityQueue(); - for (Map.Entry entry : fromNodes.entrySet()) { - DijkstraNodeData data = getData(entry.getKey()); - visitNode(entry.getKey(), data, pendingNodes, entry.getValue().initialTime, entry.getValue().initialCost, null); - } - - // do the real work - while (pendingNodes.size() > 0) { - Node outNode = pendingNodes.poll(); - relaxNode(outNode, pendingNodes); - } - } - - public TransitLeastCostPathTree(final Network network, final TransitTravelDisutility costFunction, - final TravelTime timeFunction, - final Map fromNodes, final Map toNodes, - final Person person) { - this.network = network; - this.costFunction = costFunction; - this.timeFunction = timeFunction; - - this.nodeData = new HashMap<>((int)(network.getNodes().size() * 1.1), 0.95f); - - //create tree - this.resetNetworkVisited(); - this.person = person; - this.customDataManager.reset(); - this.fromNodes = fromNodes; - - pendingNodes = (RouterPriorityQueue) createRouterPriorityQueue(); - for (Map.Entry entry : fromNodes.entrySet()) { - DijkstraNodeData data = getData(entry.getKey()); - visitNode(entry.getKey(), data, pendingNodes, entry.getValue().initialTime, entry.getValue().initialCost, null); - } - - expandNodeData(toNodes); - } - - private int getIterationId() { -// TODO could delete all the now unnecessary occurrences of the IterationID especially in DijkstraNodeData and -// TODO replace it with a flag visited but that would interfere the useage of the MultiNodeDijkstra - return 0; - } - - /** - * Resets all nodes in the network as if they have not been visited yet. - */ - private void resetNetworkVisited() { - for (Node node : this.network.getNodes().values()) { - DijkstraNodeData data = getData(node); - data.resetVisited(); - } - } - - private void expandNodeData(final Map toNodes) { - Set endNodes = new HashSet<>(toNodes.keySet()); - double minCost = Double.POSITIVE_INFINITY; - - // do the real work - while (endNodes.size() > 0) { - Node outNode = pendingNodes.poll(); - - if (outNode == null) { - // seems we have no more nodes left, but not yet reached all endNodes... - endNodes.clear(); - } else { - DijkstraNodeData data = getData(outNode); - boolean isEndNode = endNodes.remove(outNode); - if (isEndNode) { - InitialNode initData = toNodes.get(outNode); - double cost = data.getCost() + initData.initialCost; - if (cost < minCost) { - minCost = cost; - } - } - if (data.getCost() > minCost) { - endNodes.clear(); // we can't get any better now - } else { - relaxNode(outNode, pendingNodes); - } - } - } - } - - /** - * Method to request the passenger route from the (cached) fromNodes to the passed toNodes. - * Should only be requested after calling createTransitLeastCostPathTree(). - * - * @param toNodes - * The nodes that are the next stops to the toCoord and you like to route to. - * - * @return - * the transitPassengerRoute between the fromNode and the toNode. - * Will be null if the route could not be found. - */ - public InternalTransitPassengerRoute getTransitPassengerRoute(final Map toNodes) { - //find the best node - double minCost = Double.POSITIVE_INFINITY; - Node minCostNode = null; - for (Map.Entry e : toNodes.entrySet()) { - Node currentNode = e.getKey(); - DijkstraNodeData r = this.nodeData.get(currentNode.getId()); - if (r == null) { - expandNodeData(toNodes); - } - DijkstraNodeData data = getData(currentNode); - InitialNode initData = e.getValue(); - double cost = data.getCost() + initData.initialCost; - if (data.getCost() != 0.0 || fromNodes.containsKey(currentNode)) { - if (cost < minCost) { - minCost = cost; - minCostNode = currentNode; - } - } - } - - if (minCostNode == null) { - return null; - } - - // now construct route segments, which are required for TransitPassengerRoute - List routeSegments = new ArrayList<>(); - - TransitRouterNetworkLink link = (TransitRouterNetworkLink) getData(minCostNode).getPrevLink(); - TransitRouterNetworkLink downstreamLink = null; - Node previousFromNode = minCostNode; - double transferCost = 0.; - - while (link != null) { - TransitRouterNetworkNode fromNode = link.fromNode; - TransitRouterNetworkNode toNode = link.toNode; - - double travelTime = getData(toNode).getTime() - getData(fromNode).getTime(); - Id transitLineId = null; - Id routeId = null; - - boolean isTransferLeg = false; - if (link.line==null) isTransferLeg = true; - else { - transitLineId = link.line.getId(); - routeId = link.route.getId(); - } - - if (downstreamLink==null && isTransferLeg) { - // continuous transfers: see TransitRouterImplTest.testDoubleWalk. - // Another possibility is that trip start with transfer itself, see TransitRouterImplTest.testDoubleWalkOnly. - double tempTravelTime = 0.; - TransitStopFacility toStop = null; - - if (routeSegments.size()==0) { // very first leg starts with transfer - toStop = toNode.stop.getStopFacility(); - } else { - RouteSegment routeSegment = routeSegments.remove(0); - travelTime = routeSegment.travelTime; - toStop = routeSegment.toStop; - } - - routeSegments.add(0, - new RouteSegment(fromNode.stop.getStopFacility(), - toStop, - tempTravelTime+travelTime, - transitLineId, - routeId)); - //not sure, if transferCost will be included for every transfer or not. Currently, transfer cost will be accumulated for every transfer. Amit Sep'17 - } else if (downstreamLink == null // very first pt leg or first pt leg after transfer - || isTransferLeg ) { - routeSegments.add(0, new RouteSegment( fromNode.stop.getStopFacility(), - toNode.stop.getStopFacility(), - travelTime, - transitLineId, - routeId - )); - } else if (downstreamLink.line.getId() == link.line.getId() && downstreamLink.route.getId() == link.route.getId() ){ - //same route --> update the top routeSegment - RouteSegment routeSegment = routeSegments.remove(0); - routeSegments.add(0, new RouteSegment(fromNode.stop.getStopFacility(), - routeSegment.toStop, - routeSegment.travelTime+travelTime, - transitLineId, - routeId)); - } - - if (isTransferLeg) { - // transfer cost - if ( ! (this.costFunction instanceof TransitRouterNetworkTravelTimeAndDisutility) ) { - throw new RuntimeException("TransitTravelDisutility is not instance of "+TransitRouterNetworkTravelTimeAndDisutility.class.getSimpleName() - +". An acc "); - } - - transferCost += ((TransitRouterNetworkTravelTimeAndDisutility) this.costFunction).defaultTransferCost(link, - Double.NEGATIVE_INFINITY,null,null); - - downstreamLink = null; - } else { - downstreamLink = link; - } - - previousFromNode = fromNode; - link = (TransitRouterNetworkLink) getData(fromNode).getPrevLink(); - } - - DijkstraNodeData startNodeData = getData(previousFromNode); - DijkstraNodeData toNodeData = getData(minCostNode); - - double cost = toNodeData.getCost() - startNodeData.getCost() - + this.fromNodes.get(previousFromNode).initialCost - + toNodes.get(minCostNode).initialCost - + transferCost; - - // if there is no connection found, getPath(...) return a path with nothing in it, however, I (and AN) think that it should throw null. Amit Sep'17 - if (routeSegments.size()==0) return null; - else return new InternalTransitPassengerRoute(cost, routeSegments); - } - - /** - * Method to request the path from the (cached) fromNodes to the passed toNodes. - * Should only be requested after calling createTransitLeastCostPathTree(). - * - * @param toNodes - * The nodes that are the next stops to the toCoord and you like to route to. - * - * @return - * the leastCostPath between the fromNode and the toNode. - * Will be null if the path could not be found. - */ - public Path getPath(final Map toNodes) { - - //find the best node - double minCost = Double.POSITIVE_INFINITY; - Node minCostNode = null; - for (Map.Entry e : toNodes.entrySet()) { - Node currentNode = e.getKey(); - DijkstraNodeData r = this.nodeData.get(currentNode.getId()); - if (r == null) { - expandNodeData(toNodes); - } - DijkstraNodeData data = getData(currentNode); - InitialNode initData = e.getValue(); - double cost = data.getCost() + initData.initialCost; - if (data.getCost() != 0.0 || fromNodes.containsKey(currentNode)) { - if (cost < minCost) { - minCost = cost; - minCostNode = currentNode; - } - } - } - - if (minCostNode == null) { - return null; - } - - // now construct the path - List nodes = new LinkedList<>(); - List links = new LinkedList<>(); - - nodes.add(0, minCostNode); - Link tmpLink = getData(minCostNode).getPrevLink(); - while (tmpLink != null) { - links.add(0, tmpLink); - nodes.add(0, tmpLink.getFromNode()); - tmpLink = getData(tmpLink.getFromNode()).getPrevLink(); - } - - DijkstraNodeData startNodeData = getData(nodes.get(0)); - DijkstraNodeData toNodeData = getData(minCostNode); - - return new Path(nodes, links, toNodeData.getTime() - startNodeData.getTime(), - toNodeData.getCost() - startNodeData.getCost()); - } - - /** - * Allow replacing the RouterPriorityQueue. - */ - @SuppressWarnings("static-method") - /*package*/ RouterPriorityQueue createRouterPriorityQueue() { - return new PseudoRemovePriorityQueue<>(500); - } - - /** - * Inserts the given Node n into the pendingNodes queue and updates its time - * and cost information. - * - * @param n - * The Node that is revisited. - * @param data - * The data for n. - * @param pendingNodes - * The nodes visited and not processed yet. - * @param time - * The time of the visit of n. - * @param cost - * The accumulated cost at the time of the visit of n. - * @param outLink - * The node from which we came visiting n. - */ - protected void visitNode(final Node n, final DijkstraNodeData data, - final RouterPriorityQueue pendingNodes, final double time, final double cost, - final Link outLink) { - data.visit(outLink, cost, time, getIterationId()); - pendingNodes.add(n, getPriority(data)); - } - - /** - * Expands the given Node in the routing algorithm; may be overridden in - * sub-classes. - * - * @param outNode - * The Node to be expanded. - * @param pendingNodes - * The set of pending nodes so far. - */ - protected void relaxNode(final Node outNode, final RouterPriorityQueue pendingNodes) { - - DijkstraNodeData outData = getData(outNode); - double currTime = outData.getTime(); - double currCost = outData.getCost(); - for (Link l : outNode.getOutLinks().values()) { - relaxNodeLogic(l, pendingNodes, currTime, currCost); - } - } - - /** - * Logic that was previously located in the relaxNode(...) method. - * By doing so, the FastDijkstra can overwrite relaxNode without copying the logic. - */ - /*package*/ void relaxNodeLogic(final Link l, final RouterPriorityQueue pendingNodes, - final double currTime, final double currCost) { - addToPendingNodes(l, l.getToNode(), pendingNodes, currTime, currCost); - } - - /** - * Adds some parameters to the given Node then adds it to the set of pending - * nodes. - * - * @param l - * The link from which we came to this Node. - * @param n - * The Node to add to the pending nodes. - * @param pendingNodes - * The set of pending nodes. - * @param currTime - * The time at which we started to traverse l. - * @param currCost - * The cost at the time we started to traverse l. - * @return true if the node was added to the pending nodes, false otherwise - * (e.g. when the same node already has an earlier visiting time). - */ - protected boolean addToPendingNodes(final Link l, final Node n, - final RouterPriorityQueue pendingNodes, final double currTime, - final double currCost) { - - this.customDataManager.initForLink(l); - double travelTime = this.timeFunction.getLinkTravelTime(l, currTime, this.person, this.vehicle); - double travelCost = this.costFunction.getLinkTravelDisutility(l, currTime, this.person, this.vehicle, this.customDataManager); - DijkstraNodeData data = getData(n); - double nCost = data.getCost(); - if (!data.isVisited(getIterationId())) { - visitNode(n, data, pendingNodes, currTime + travelTime, currCost + travelCost, l); - this.customDataManager.storeTmpData(); - return true; - } - double totalCost = currCost + travelCost; - if (totalCost < nCost) { - revisitNode(n, data, pendingNodes, currTime + travelTime, totalCost, l); - this.customDataManager.storeTmpData(); - return true; - } - - return false; - } - - /** - * Changes the position of the given Node n in the pendingNodes queue and - * updates its time and cost information. - * - * @param n - * The Node that is revisited. - * @param data - * The data for n. - * @param pendingNodes - * The nodes visited and not processed yet. - * @param time - * The time of the visit of n. - * @param cost - * The accumulated cost at the time of the visit of n. - * @param outLink - * The link from which we came visiting n. - */ - void revisitNode(final Node n, final DijkstraNodeData data, - final RouterPriorityQueue pendingNodes, final double time, final double cost, - final Link outLink) { - pendingNodes.remove(n); - - data.visit(outLink, cost, time, getIterationId()); - pendingNodes.add(n, getPriority(data)); - } - - /** - * The value used to sort the pending nodes during routing. - * This implementation compares the total effective travel cost - * to sort the nodes in the pending nodes queue during routing. - */ - private double getPriority(final DijkstraNodeData data) { - return data.getCost(); - } - - /** - * Returns the data for the given node. Creates a new NodeData if none exists - * yet. - * - * @param n - * The Node for which to return the data. - * @return The data for the given Node - */ - protected DijkstraNodeData getData(final Node n) { - DijkstraNodeData r = this.nodeData.get(n.getId()); - if (null == r) { - r = new DijkstraNodeData(); - this.nodeData.put(n.getId(), r); - } - return r; - } - -} \ No newline at end of file diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitRouter.java b/matsim/src/main/java/org/matsim/pt/router/TransitRouter.java index 7fbe8110802..a2318e18052 100644 --- a/matsim/src/main/java/org/matsim/pt/router/TransitRouter.java +++ b/matsim/src/main/java/org/matsim/pt/router/TransitRouter.java @@ -29,6 +29,6 @@ */ public interface TransitRouter { - public abstract List calcRoute(RoutingRequest request); + List calcRoute(RoutingRequest request); } diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitRouterConfig.java b/matsim/src/main/java/org/matsim/pt/router/TransitRouterConfig.java index 6ae4c9cd7af..e18700156bf 100644 --- a/matsim/src/main/java/org/matsim/pt/router/TransitRouterConfig.java +++ b/matsim/src/main/java/org/matsim/pt/router/TransitRouterConfig.java @@ -25,9 +25,9 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.core.api.internal.MatsimParameters; 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.PlansCalcRouteConfigGroup.TeleportedModeParams; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup.TeleportedModeParams; import org.matsim.core.config.groups.VspExperimentalConfigGroup; import org.matsim.core.gbl.Gbl; import org.matsim.pt.config.TransitRouterConfigGroup; @@ -91,7 +91,7 @@ public class TransitRouterConfig implements MatsimParameters { private double marginalUtilityOfWaitingPt_utl_s; private double marginalUtilityOfTravelDistanceWalk_utl_m; - + private double marginalUtilityOfTravelDistanceTransit_utl_m; private double utilityOfLineSwitch_utl; @@ -99,24 +99,24 @@ public class TransitRouterConfig implements MatsimParameters { private Double beelineDistanceFactor; private final double directWalkFactor ; - + private boolean cacheTree; public TransitRouterConfig(final Config config) { - this(config.planCalcScore(), config.plansCalcRoute(), config.transitRouter(), config.vspExperimental()); + this(config.scoring(), config.routing(), config.transitRouter(), config.vspExperimental()); } - - public TransitRouterConfig(final PlanCalcScoreConfigGroup pcsConfig, final PlansCalcRouteConfigGroup pcrConfig, - final TransitRouterConfigGroup trConfig, final VspExperimentalConfigGroup vspConfig ) + + public TransitRouterConfig(final ScoringConfigGroup pcsConfig, final RoutingConfigGroup pcrConfig, + final TransitRouterConfigGroup trConfig, final VspExperimentalConfigGroup vspConfig ) { pcsConfig.setLocked(); pcrConfig.setLocked() ; trConfig.setLocked() ; vspConfig.setLocked() ; - + if (pcsConfig.getScoringParametersPerSubpopulation().size()>1){ LogManager.getLogger(getClass()).warn("More than one subpopulation is used in plansCalcScore. " + "This is not currently implemented in the TransitRouter (but should work for scoring)," + " so the values for the \"default\" subpopulation will be used. (jb, Feb 2018)"); } - + // walk: { TeleportedModeParams params = pcrConfig.getModeRoutingParams().get( TransportMode.walk ); @@ -126,13 +126,13 @@ public TransitRouterConfig(final PlanCalcScoreConfigGroup pcsConfig, final Plans } // yyyyyy the two above need to be moved away from walk since otherwise one is not able to move walk routing to network routing!!!!!! Now trying access_walk ... kai, // apr'19 - + this.marginalUtilityOfTravelTimeWalk_utl_s = pcsConfig.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() /3600.0 - pcsConfig.getPerforming_utils_hr()/3600. ; - + this.marginalUtilityOfTravelDistanceWalk_utl_m = pcsConfig.getMarginalUtilityOfMoney() * pcsConfig.getModes().get(TransportMode.walk).getMonetaryDistanceRate() + pcsConfig.getModes().get(TransportMode.walk).getMarginalUtilityOfDistance(); - + // pt: this.marginalUtilityOfTravelTimeTransit_utl_s = pcsConfig.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() /3600.0 - pcsConfig.getPerforming_utils_hr()/3600. ; @@ -177,11 +177,11 @@ public double getMarginalUtilityOfTravelTimeWalk_utl_s() { public void setMarginalUtilityOfTravelTimePt_utl_s(final double marginalUtilityOfTravelTimeTransit_utl_s) { this.marginalUtilityOfTravelTimeTransit_utl_s = marginalUtilityOfTravelTimeTransit_utl_s; } - + public void setMarginalUtilityOfTravelDistanceWalk_utl_m(final double marginalUtilityOfTravelDistanceWalk_utl_m) { this.marginalUtilityOfTravelDistanceWalk_utl_m = marginalUtilityOfTravelDistanceWalk_utl_m; } - + /** * @return the marginal utility of travel time by public transit. */ @@ -212,7 +212,7 @@ public double getMarginalUtilityOfTravelDistancePt_utl_m() { public double getMarginalUtilityOfTravelDistanceWalk_utl_m() { return this.marginalUtilityOfTravelDistanceWalk_utl_m; } - + public void setBeelineWalkSpeed(final double beelineWalkSpeed) { this.beelineWalkSpeed = beelineWalkSpeed; } diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitRouterImpl.java b/matsim/src/main/java/org/matsim/pt/router/TransitRouterImpl.java deleted file mode 100644 index 716490a972f..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/TransitRouterImpl.java +++ /dev/null @@ -1,188 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TranitRouter.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 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.pt.router; - -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Person; -import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.core.router.InitialNode; -import org.matsim.core.router.RoutingRequest; -import org.matsim.core.router.util.TravelTime; -import org.matsim.core.utils.geometry.CoordUtils; -import org.matsim.facilities.Facility; -import org.matsim.pt.transitSchedule.api.TransitSchedule; - -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Not thread-safe because MultiNodeDijkstra is not. Does not expect the TransitSchedule to change once constructed! michaz '13 - * - * @author mrieser - */ -public class TransitRouterImpl extends AbstractTransitRouter implements TransitRouter { - - private final TransitRouterNetwork transitNetwork; - private final TravelTime travelTime; - private final TransitTravelDisutility travelDisutility; - private final PreparedTransitSchedule preparedTransitSchedule; - - private boolean cacheTree; - private TransitLeastCostPathTree tree; - private Facility previousFromFacility; - private double previousDepartureTime; - - public TransitRouterImpl(final TransitRouterConfig trConfig, final TransitSchedule schedule) { - super(trConfig); - this.transitNetwork = TransitRouterNetwork.createFromSchedule(schedule, - trConfig.getBeelineWalkConnectionDistance()); - this.preparedTransitSchedule = new PreparedTransitSchedule(schedule); - TransitRouterNetworkTravelTimeAndDisutility transitRouterNetworkTravelTimeAndDisutility = new TransitRouterNetworkTravelTimeAndDisutility( - trConfig, - new PreparedTransitSchedule(schedule)); - this.travelDisutility = transitRouterNetworkTravelTimeAndDisutility; - this.travelTime = transitRouterNetworkTravelTimeAndDisutility; - setTransitTravelDisutility(this.travelDisutility); - - this.cacheTree = trConfig.isCacheTree(); - } - - public TransitRouterImpl( - final TransitRouterConfig trConfig, - final PreparedTransitSchedule preparedTransitSchedule, - final TransitRouterNetwork routerNetwork, - final TravelTime travelTime, - final TransitTravelDisutility travelDisutility) { - - super(trConfig, travelDisutility); - - this.transitNetwork = routerNetwork; - this.preparedTransitSchedule = preparedTransitSchedule; - this.travelDisutility = travelDisutility; - this.travelTime = travelTime; - - this.cacheTree = trConfig.isCacheTree(); - } - - private Map locateWrappedNearestTransitNodes(Person person, Coord coord, double departureTime) { - Collection nearestNodes = getTransitRouterNetwork().getNearestNodes( - coord, - this.getConfig().getSearchRadius()); - if (nearestNodes.size() < 2) { - // also enlarge search area if only one stop found, maybe a second one is near the border of the search area - TransitRouterNetwork.TransitRouterNetworkNode nearestNode = this.getTransitRouterNetwork() - .getNearestNode(coord); - if (nearestNode != null) { // transit schedule might be completely empty! - double distance = CoordUtils.calcEuclideanDistance(coord, - nearestNode.stop.getStopFacility().getCoord()); - nearestNodes = this.getTransitRouterNetwork() - .getNearestNodes(coord, distance + this.getConfig().getExtensionRadius()); - } - } - Map wrappedNearestNodes = new LinkedHashMap<>(); - for (TransitRouterNetwork.TransitRouterNetworkNode node : nearestNodes) { - Coord toCoord = node.stop.getStopFacility().getCoord(); - double initialTime = getWalkTime(person, coord, toCoord); - double initialCost = getWalkDisutility(person, coord, toCoord); - wrappedNearestNodes.put(node, new InitialNode(initialCost, initialTime + departureTime)); - } - return wrappedNearestNodes; - } - - @Override - public List calcRoute( final RoutingRequest request ) { - final Facility fromFacility = request.getFromFacility(); - final Facility toFacility = request.getToFacility(); - final double departureTime = request.getDepartureTime(); - final Person person = request.getPerson(); - - // find possible start stops - Map wrappedFromNodes = this.locateWrappedNearestTransitNodes(person, - fromFacility.getCoord(), - departureTime); - - - // find possible end stops - Map wrappedToNodes = this.locateWrappedNearestTransitNodes(person, - toFacility.getCoord(), - departureTime); - - InternalTransitPassengerRoute transitPassengerRoute = null; - - if (cacheTree) { - if ((fromFacility != previousFromFacility) && (departureTime != previousDepartureTime)) { // Compute tree only if fromFacility and departure time are different from previous request. - tree = new TransitLeastCostPathTree(getTransitRouterNetwork(), - getTravelDisutility(), - getTravelTime(), - wrappedFromNodes, - person); - } - } else { // Compute new tree for every routing request - tree = new TransitLeastCostPathTree(getTransitRouterNetwork(), - getTravelDisutility(), - getTravelTime(), - wrappedFromNodes, - wrappedToNodes, - person); - // yyyyyy This sounds like it is doing the full tree. But I think it is not. Kai, nov'16 - // Yes, only if you leave out the wrappedToNodes from the argument list, it does compute the full tree. See the new case above. dz, june'18 - } - - // find routes between start and end stop - transitPassengerRoute = tree.getTransitPassengerRoute(wrappedToNodes); - - if (transitPassengerRoute == null) { - return null; // TripRouter / FallbackRoutingModule will create a direct walk leg - } - double pathCost = transitPassengerRoute.getTravelCost(); - - double directWalkCost = getWalkDisutility(person, fromFacility.getCoord(), toFacility.getCoord()); - - if (directWalkCost * getConfig().getDirectWalkFactor() < pathCost) { - return null; // TripRouter / FallbackRoutingModule will create a direct walk leg - } - - previousFromFacility = fromFacility; - previousDepartureTime = departureTime; - - return convertPassengerRouteToLegList(departureTime, - transitPassengerRoute, - fromFacility.getCoord(), - toFacility.getCoord(), - person); - } - - public TransitRouterNetwork getTransitRouterNetwork() { - return transitNetwork; - } - - TravelTime getTravelTime() { - return travelTime; - } - - PreparedTransitSchedule getPreparedTransitSchedule() { - return preparedTransitSchedule; - } -} diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitRouterImplFactory.java b/matsim/src/main/java/org/matsim/pt/router/TransitRouterImplFactory.java deleted file mode 100644 index 9842e1b09ac..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/TransitRouterImplFactory.java +++ /dev/null @@ -1,73 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TransitRouterImplFactory.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2010 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.pt.router; - -import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.config.Config; -import org.matsim.pt.transitSchedule.api.TransitSchedule; - -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.inject.Singleton; - -/** - * @author mrieser - */ -@Singleton -public class TransitRouterImplFactory implements Provider { - - private final TransitRouterConfig config; - private final TransitSchedule transitSchedule; - private TransitRouterNetwork routerNetwork; - private PreparedTransitSchedule preparedTransitSchedule; - - @Inject - TransitRouterImplFactory(final TransitSchedule schedule, final EventsManager events, final Config config) { - this(schedule, new TransitRouterConfig( - config.planCalcScore(), - config.plansCalcRoute(), - config.transitRouter(), - config.vspExperimental())); - events.addHandler((TransitScheduleChangedEventHandler) event -> { - routerNetwork = null; - preparedTransitSchedule = null; - }); - } - - public TransitRouterImplFactory(final TransitSchedule schedule, final TransitRouterConfig config) { - this.config = config; - this.transitSchedule = schedule; - } - - @Override - public TransitRouter get() { - if (this.routerNetwork == null) { - this.routerNetwork = TransitRouterNetwork.createFromSchedule(transitSchedule, this.config.getBeelineWalkConnectionDistance()); - } - if (this.preparedTransitSchedule == null) { - this.preparedTransitSchedule = new PreparedTransitSchedule(transitSchedule); - } - - TransitRouterNetworkTravelTimeAndDisutility ttCalculator = new TransitRouterNetworkTravelTimeAndDisutility(this.config, this.preparedTransitSchedule); - return new TransitRouterImpl(this.config, this.preparedTransitSchedule, this.routerNetwork, ttCalculator, ttCalculator); - } - -} diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitRouterModule.java b/matsim/src/main/java/org/matsim/pt/router/TransitRouterModule.java index ea6102825c8..95b724568f6 100644 --- a/matsim/src/main/java/org/matsim/pt/router/TransitRouterModule.java +++ b/matsim/src/main/java/org/matsim/pt/router/TransitRouterModule.java @@ -32,8 +32,7 @@ public void install() { if (getConfig().transit().isUseTransit()) { switch (getConfig().transit().getRoutingAlgorithmType()) { case DijkstraBased: - bind(TransitRouter.class).toProvider(TransitRouterImplFactory.class); - break; + throw new RuntimeException("'DijkstraBased' is no longer supported as a transit routing algorithm. Use 'SwissRailRaptor' instead."); case SwissRailRaptor: install(new SwissRailRaptorModule()); break; diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitRouterNetwork.java b/matsim/src/main/java/org/matsim/pt/router/TransitRouterNetwork.java deleted file mode 100644 index 3ecc02f77dd..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/TransitRouterNetwork.java +++ /dev/null @@ -1,488 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TransitRouterNetwork.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 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.pt.router; - -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -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.Coord; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.network.NetworkFactory; -import org.matsim.api.core.v01.network.Node; -import org.matsim.core.utils.collections.IdentifiableArrayMap; -import org.matsim.core.utils.collections.QuadTree; -import org.matsim.core.utils.collections.Tuple; -import org.matsim.core.utils.geometry.CoordUtils; -import org.matsim.core.utils.misc.Counter; -import org.matsim.core.utils.misc.Time; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitRouteStop; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.utils.objectattributes.attributable.Attributes; - -/** - * Converting the TransitRouterNetwork into a {@link org.matsim.core.router.util.RoutingNetwork} might - * speed up the routing and additionally reduce the memory consumption (e.g. by using array for a nodes - * in- and outgoing links). cdobler, nov'12 - * - * @author mrieser - * @author nagel - */ -public final class TransitRouterNetwork implements Network { - - private final static Logger log = LogManager.getLogger(TransitRouterNetwork.class); - - private final Map, TransitRouterNetworkLink> links = new LinkedHashMap<>(); - private final Map, TransitRouterNetworkNode> nodes = new LinkedHashMap<>(); - private QuadTree qtNodes = null; - - private long nextNodeId = 0; - private long nextLinkId = 0; - - - public static final class TransitRouterNetworkNode implements Node { - - public final TransitRouteStop stop; - public final TransitRoute route; - public final TransitLine line; - final Id id; - final Map, TransitRouterNetworkLink> ingoingLinks = new IdentifiableArrayMap<>(); - final Map, TransitRouterNetworkLink> outgoingLinks = new IdentifiableArrayMap<>(); - - public TransitRouterNetworkNode(final Id id, final TransitRouteStop stop, final TransitRoute route, final TransitLine line) { - this.id = id; - this.stop = stop; - this.route = route; - this.line = line; - } - - @Override - public Map, ? extends Link> getInLinks() { - return this.ingoingLinks; - } - - @Override - public Map, ? extends Link> getOutLinks() { - return this.outgoingLinks; - } - - @Override - public boolean addInLink(final Link link) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addOutLink(final Link link) { - throw new UnsupportedOperationException(); - } - - @Override - public Coord getCoord() { - return this.stop.getStopFacility().getCoord(); - } - - @Override - public Id getId() { - return this.id; - } - - public TransitRouteStop getStop() { - return stop; - } - - public TransitRoute getRoute() { - return route; - } - - public TransitLine getLine() { - return line; - } - - @Override - public String toString() { - return this.id.toString(); - } - - @Override - public Link removeInLink(Id linkId) { - throw new RuntimeException("not implemented") ; - } - - @Override - public Link removeOutLink(Id outLinkId) { - throw new RuntimeException("not implemented") ; - } - - @Override - public void setCoord(Coord coord) { - throw new RuntimeException("not implemented") ; - } - - @Override - public Attributes getAttributes() { - throw new UnsupportedOperationException(); - } - } - - /** - * Looks to me like an implementation of the Link interface, with get(Transit)Route and get(Transit)Line on top. - * To recall: TransitLine is something like M44. But it can have more than one route, e.g. going north, going south, - * long route, short route. That is, presumably we have one such TransitRouterNetworkLink per TransitRoute. kai/manuel, feb'12 - */ - public static final class TransitRouterNetworkLink implements Link { - - public final TransitRouterNetworkNode fromNode; - public final TransitRouterNetworkNode toNode; - final TransitRoute route; - final TransitLine line; - final Id id; - private final double length; - - public TransitRouterNetworkLink(final Id id, final TransitRouterNetworkNode fromNode, final TransitRouterNetworkNode toNode, final TransitRoute route, final TransitLine line, double length) { - this.id = id; - this.fromNode = fromNode; - this.toNode = toNode; - this.route = route; - this.line = line; - this.length = length; - } - - public TransitRouterNetworkLink(final Id id, final TransitRouterNetworkNode fromNode, final TransitRouterNetworkNode toNode, final TransitRoute route, final TransitLine line) { - this(id, fromNode, toNode, route, line, CoordUtils.calcEuclideanDistance(toNode.stop.getStopFacility().getCoord(), fromNode.stop.getStopFacility().getCoord())); - } - - @Override - public TransitRouterNetworkNode getFromNode() { - return this.fromNode; - } - - @Override - public TransitRouterNetworkNode getToNode() { - return this.toNode; - } - - @Override - public double getCapacity() { - return 9999; - } - - @Override - public double getCapacity(final double time) { - return getCapacity(); - } - - @Override - public double getFreespeed() { - return 10; - } - - @Override - public double getFreespeed(final double time) { - return getFreespeed(); - } - - @Override - public Id getId() { - return this.id; - } - - @Override - public double getNumberOfLanes() { - return 1; - } - - @Override - public double getNumberOfLanes(final double time) { - return getNumberOfLanes(); - } - - @Override - public double getLength() { - return this.length; - } - - @Override - public void setCapacity(final double capacity) { - throw new UnsupportedOperationException(); - } - - @Override - public void setFreespeed(final double freespeed) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean setFromNode(final Node node) { - throw new UnsupportedOperationException(); - } - - @Override - public void setNumberOfLanes(final double lanes) { - throw new UnsupportedOperationException(); - } - - @Override - public void setLength(final double length) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean setToNode(final Node node) { - throw new UnsupportedOperationException(); - } - - @Override - public Coord getCoord() { - throw new UnsupportedOperationException(); - } - - @Override - public Set getAllowedModes() { - return null; - } - - @Override - public void setAllowedModes(final Set modes) { - throw new UnsupportedOperationException(); - } - - public TransitRoute getRoute() { - return route; - } - - public TransitLine getLine() { - return line; - } - - @Override - public String toString() { - return "[" + this.id.toString() + " (" + this.getFromNode().id + " > " + this.getToNode().id + ")]"; - } - - @Override - public double getCapacityPeriod() { - throw new UnsupportedOperationException(); - } - - @Override - public Attributes getAttributes() { - throw new UnsupportedOperationException(); - } - } - - public TransitRouterNetworkNode createNode(final TransitRouteStop stop, final TransitRoute route, final TransitLine line) { - final TransitRouterNetworkNode node = new TransitRouterNetworkNode(Id.create(this.nextNodeId++, Node.class), stop, route, line); - this.nodes.put(node.getId(), node); - return node; - } - - public TransitRouterNetworkLink createLink(final TransitRouterNetworkNode fromNode, final TransitRouterNetworkNode toNode, final TransitRoute route, final TransitLine line) { - final TransitRouterNetworkLink link = new TransitRouterNetworkLink(Id.create(this.nextLinkId++, Link.class), fromNode, toNode, route, line); - this.links.put(link.getId(), link); - fromNode.outgoingLinks.put(link.getId(), link); - toNode.ingoingLinks.put(link.getId(), link); - return link; - } - - @Override - public Map, ? extends TransitRouterNetworkNode> getNodes() { - return this.nodes; - } - - @Override - public Map, ? extends TransitRouterNetworkLink> getLinks() { - return this.links; - } - - public void finishInit() { - double minX = Double.POSITIVE_INFINITY; - double minY = Double.POSITIVE_INFINITY; - double maxX = Double.NEGATIVE_INFINITY; - double maxY = Double.NEGATIVE_INFINITY; - - for (TransitRouterNetworkNode node : this.nodes.values()) { - Coord c = node.stop.getStopFacility().getCoord(); - if (c.getX() < minX) { - minX = c.getX(); - } - if (c.getY() < minY) { - minY = c.getY(); - } - if (c.getX() > maxX) { - maxX = c.getX(); - } - if (c.getY() > maxY) { - maxY = c.getY(); - } - } - - QuadTree quadTree = new QuadTree(minX, minY, maxX, maxY); - for (TransitRouterNetworkNode node : this.nodes.values()) { - Coord c = node.stop.getStopFacility().getCoord(); - quadTree.put(c.getX(), c.getY(), node); - } - this.qtNodes = quadTree; - } - - public Collection getNearestNodes(final Coord coord, final double distance) { - return this.qtNodes.getDisk(coord.getX(), coord.getY(), distance); - } - - public TransitRouterNetworkNode getNearestNode(final Coord coord) { - return this.qtNodes.getClosest(coord.getX(), coord.getY()); - } - - @Override - public double getCapacityPeriod() { - return 3600.0; - } - - @Override - public NetworkFactory getFactory() { - return null; - } - - @Override - public double getEffectiveLaneWidth() { - return 3; - } - - @Override - public void addNode(Node nn) { - throw new UnsupportedOperationException(); - } - - @Override - public void addLink(Link ll) { - throw new UnsupportedOperationException(); - } - - @Override - public Link removeLink(Id linkId) { - throw new UnsupportedOperationException(); - } - - @Override - public Node removeNode(Id nodeId) { - throw new UnsupportedOperationException(); - } - - public static TransitRouterNetwork createFromSchedule(final TransitSchedule schedule, final double maxBeelineWalkConnectionDistance) { - log.info("start creating transit network"); - final TransitRouterNetwork network = new TransitRouterNetwork(); - final Counter linkCounter = new Counter(" link #"); - final Counter nodeCounter = new Counter(" node #"); - // build nodes and links connecting the nodes according to the transit routes - for (TransitLine line : schedule.getTransitLines().values()) { - for (TransitRoute route : line.getRoutes().values()) { - TransitRouterNetworkNode prevNode = null; - for (TransitRouteStop stop : route.getStops()) { - TransitRouterNetworkNode node = network.createNode(stop, route, line); - nodeCounter.incCounter(); - if (prevNode != null) { - network.createLink(prevNode, node, route, line); - linkCounter.incCounter(); - } - prevNode = node; - } - } - } - network.finishInit(); // not nice to call "finishInit" here before we added all links... - // in my view, it would be possible to completely do without finishInit: do the - // additions to the central data structures as items come in, not near the end. I would - // prefer that because nobody could forget the "finishInit". kai, apr'10 - // well, not really. finishInit creates the quadtree, for this, the extent must be known, - // which is not at the very start, so the quadtree data structure cannot be updated as - // links come in. mrieser, dec'10 - log.info("add transfer links"); - - List> toBeAdded = new LinkedList>(); - // connect all stops with walking links if they're located less than beelineWalkConnectionDistance from each other - for (TransitRouterNetworkNode node : network.getNodes().values()) { - if (node.getInLinks().size() > 0) { // only add links from this node to other nodes if agents actually can arrive here - for (TransitRouterNetworkNode node2 : network.getNearestNodes(node.stop.getStopFacility().getCoord(), maxBeelineWalkConnectionDistance)) { - if ((node != node2) && (node2.getOutLinks().size() > 0)) { // only add links to other nodes when agents can depart there - if ((node.line != node2.line) || (node.stop.getStopFacility() != node2.stop.getStopFacility())) { - // do not yet add them to the network, as this would change in/out-links - toBeAdded.add(new Tuple(node, node2)); - } - } - } - } - } - log.info(toBeAdded.size() + " transfer links to be added."); - for (Tuple tuple : toBeAdded) { - network.createLink(tuple.getFirst(), tuple.getSecond(), null, null); - linkCounter.incCounter(); - } - - log.info("transit router network statistics:"); - log.info(" # nodes: " + network.getNodes().size()); - log.info(" # links total: " + network.getLinks().size()); - log.info(" # transfer links: " + toBeAdded.size()); - - return network; - } - - @Override - public void setCapacityPeriod(double capPeriod) { - throw new RuntimeException("not implemented") ; - } - - @Override - public void setEffectiveCellSize(double effectiveCellSize) { - throw new RuntimeException("not implemented") ; - } - - @Override - public void setEffectiveLaneWidth(double effectiveLaneWidth) { - throw new RuntimeException("not implemented") ; - } - - @Override - public void setName(String name) { - throw new RuntimeException("not implemented") ; - } - - @Override - public String getName() { - throw new RuntimeException("not implemented") ; - } - - @Override - public double getEffectiveCellSize() { - throw new RuntimeException("not implemented") ; - } - - @Override - public Attributes getAttributes() { - throw new UnsupportedOperationException(); - } -} diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitRouterNetworkTravelTimeAndDisutility.java b/matsim/src/main/java/org/matsim/pt/router/TransitRouterNetworkTravelTimeAndDisutility.java deleted file mode 100644 index 79de4237b65..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/TransitRouterNetworkTravelTimeAndDisutility.java +++ /dev/null @@ -1,219 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TransitRouterNetworkCost.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 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.pt.router; - -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.router.util.TravelTime; -import org.matsim.core.utils.geometry.CoordUtils; -import org.matsim.pt.router.TransitRouterNetwork.TransitRouterNetworkLink; -import org.matsim.pt.transitSchedule.api.TransitRouteStop; -import org.matsim.vehicles.Vehicle; - -/** - * TravelTime and TravelCost calculator to be used with the transit network used for transit routing. - * - * This class is NOT thread-safe! - * - * @author mrieser - */ -public class TransitRouterNetworkTravelTimeAndDisutility implements TravelTime, TransitTravelDisutility { - - final static double MIDNIGHT = 24.0*3600; - - protected final TransitRouterConfig config; - private Link previousLink = null; - private double previousTime = Double.NaN; - private double cachedTravelTime = Double.NaN; - - private final PreparedTransitSchedule preparedTransitSchedule; - - /* - * If this constructor is used, every instance use its own PreparedTransitSchedule which might - * consume a lot of memory. - * - * cdobler, nov'12 - */ - @Deprecated - public TransitRouterNetworkTravelTimeAndDisutility(final TransitRouterConfig config) { - this(config, new PreparedTransitSchedule()); - } - - public TransitRouterNetworkTravelTimeAndDisutility(final TransitRouterConfig config, PreparedTransitSchedule preparedTransitSchedule) { - this.config = config; - this.preparedTransitSchedule = preparedTransitSchedule; - } - - @Override - public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle, final CustomDataManager dataManager) { - double cost; - if (((TransitRouterNetworkLink) link).getRoute() == null) { - // "route" here means "pt route". If no pt route is attached, it means that it is a transfer link. - - cost = defaultTransferCost(link, time, person, vehicle); - - } else { - double offVehWaitTime = offVehicleWaitTime(link, time); - double inVehTime = getLinkTravelTime(link,time, person, vehicle) - offVehWaitTime; - cost = - inVehTime * this.config.getMarginalUtilityOfTravelTimePt_utl_s() - -offVehWaitTime * this.config.getMarginalUtilityOfWaitingPt_utl_s() - -link.getLength() * this.config.getMarginalUtilityOfTravelDistancePt_utl_m(); - - } - return cost; - } - - /** - * method to allow inclusion of offVehicleWaitTime without code replication. kai, oct'12 - * - * @param link - * @param time - * @return - */ - protected double offVehicleWaitTime(final Link link, final double time) { - double offVehWaitTime=0; - double nextVehArrivalTime = getVehArrivalTime(link, time); - if (time < nextVehArrivalTime){ // it means the agent waits outside the veh - offVehWaitTime = nextVehArrivalTime-time; - } - return offVehWaitTime; - - } - - /** - * convenience method for derived classes in order to bring Manuel's version closer to this one here. - * kai, oct'12 - */ - protected final double defaultTransferCost(final Link link, final double time, - final Person person, final Vehicle vehicle) { - double cost; - double transfertime = getLinkTravelTime(link, time, person, vehicle); - double waittime = this.config.getAdditionalTransferTime(); - - // say that the effective walk time is the transfer time minus some "buffer" - double walktime = transfertime - waittime; - // (this looks like walktime might become negative. But at least in the default version, the additional transfer time is always - // _added_ to the walk time (see getLinkTravelTime below) so at least in that case this cannot happen. kai, triggered by cd, may'16) - if ( walktime < 0. ) { - throw new RuntimeException( "negative walk time; should not happen; needs to be repaired" ) ; - } - - double walkDistance = link.getLength(); - - // weigh this "buffer" not with the walk time disutility, but with the wait time disutility: - // (note that this is the same "additional disutl of wait" as in the scoring function. Its default is zero. - // only if you are "including the opportunity cost of time into the router", then the disutility of waiting will - // be the same as the marginal opprotunity cost of time). kai, nov'11 - cost = - walktime * this.config.getMarginalUtilityOfTravelTimeWalk_utl_s() - - walkDistance * this.config.getMarginalUtilityOfTravelDistanceWalk_utl_m() - - waittime * this.config.getMarginalUtilityOfWaitingPt_utl_s() - - this.config.getUtilityOfLineSwitch_utl(); - return cost; - } - - @Override - public double getLinkTravelTime(final Link link, final double time, Person person, Vehicle vehicle) { - if ((link == this.previousLink) && (time == this.previousTime)) { - return this.cachedTravelTime; - } - this.previousLink = link; - this.previousTime = time; - - TransitRouterNetworkLink wrapped = (TransitRouterNetworkLink) link; - TransitRouteStop fromStop = wrapped.fromNode.stop; - TransitRouteStop toStop = wrapped.toNode.stop; - if (wrapped.route != null) { - // (agent stays on the same route, so use transit line travel time) - - // get the next departure time: - double bestDepartureTime = preparedTransitSchedule.getNextDepartureTime(wrapped.route, fromStop, time); - - // the travel time on the link is - // the time until the departure (``dpTime - now'') - // + the travel time on the link (there.arrivalTime - here.departureTime) - // But quite often, we only have the departure time at the next stop. Then we use that: - double arrivalOffset = toStop.getArrivalOffset().or(toStop::getDepartureOffset).seconds(); - double time2 = (bestDepartureTime - time) + (arrivalOffset - fromStop.getDepartureOffset().seconds()); - if (time2 < 0) { - // ( this can only happen, I think, when ``bestDepartureTime'' is after midnight but ``time'' was before ) - time2 += MIDNIGHT; - } - this.cachedTravelTime = time2; - return time2; - } - // different transit routes, so it must be a line switch - double distance = wrapped.getLength(); - double time2 = distance / this.config.getBeelineWalkSpeed() + this.config.getAdditionalTransferTime(); - this.cachedTravelTime = time2; - return time2; - } - - //variables for caching offVehWaitTime - Link previousWaitLink; - double previousWaitTime; - double cachedVehArrivalTime; - - public double getVehArrivalTime(final Link link, final double now){ - if ((link == this.previousWaitLink) && (now == this.previousWaitTime)) { - return this.cachedVehArrivalTime; - } - this.previousWaitLink = link; - this.previousWaitTime = now; - - //first find out vehicle arrival time to fromStop according to transit schedule - TransitRouterNetworkLink wrapped = (TransitRouterNetworkLink) link; - if (wrapped.getRoute() == null) { - throw new RuntimeException("should not happen") ; - } - TransitRouteStop fromStop = wrapped.fromNode.stop; - - double nextDepartureTime = preparedTransitSchedule.getNextDepartureTime(wrapped.getRoute(), fromStop, now); - - double fromStopDepartureOffset = fromStop.getDepartureOffset().seconds(); - double fromStopArrivalOffset = fromStop.getArrivalOffset().orElse(fromStopDepartureOffset); - double vehWaitAtStopTime = fromStopDepartureOffset - fromStopArrivalOffset; //time in which the veh stops at station - double vehArrivalTime = nextDepartureTime - vehWaitAtStopTime; - cachedVehArrivalTime = vehArrivalTime ; - return vehArrivalTime ; - } - - @Override - public double getWalkTravelDisutility(Person person, Coord coord, Coord toCoord) { - // getMarginalUtilityOfTravelTimeWalk INCLUDES the opportunity cost of time. kai, dec'12 - double timeCost = - getWalkTravelTime(person, coord, toCoord) * config.getMarginalUtilityOfTravelTimeWalk_utl_s() ; - // (sign: margUtl is negative; overall it should be positive because it is a cost.) - - double distanceCost = - CoordUtils.calcEuclideanDistance(coord,toCoord) * - config.getBeelineDistanceFactor() * config.getMarginalUtilityOfTravelDistanceWalk_utl_m(); - // (sign: same as above) - - return timeCost + distanceCost ; - } - - @Override - public double getWalkTravelTime(Person person, Coord coord, Coord toCoord) { - double distance = CoordUtils.calcEuclideanDistance(coord, toCoord); - double initialTime = distance / config.getBeelineWalkSpeed(); - return initialTime; - } - -} diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitTravelDisutility.java b/matsim/src/main/java/org/matsim/pt/router/TransitTravelDisutility.java deleted file mode 100644 index e069df124b4..00000000000 --- a/matsim/src/main/java/org/matsim/pt/router/TransitTravelDisutility.java +++ /dev/null @@ -1,54 +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.pt.router; - -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.population.Person; -import org.matsim.vehicles.Vehicle; - -/** - * @author mrieser / senozon - */ -public interface TransitTravelDisutility { - - /** - * Returns the disutility to travel on the specified link at the specified time. - * - * @param link The link for which the travel disutility is calculated. - * @param time The departure time (in seconds since 00:00) at the beginning of the link for which the disutility is calculated. - * @param person The person that wants to travel along the link. Note that this parameter can be null! - * @param vehicle The vehicle with which the person wants to travel along the link. Note that this parameter can be null! - * @param dataManager A helper class to enable the cost calculator store arbitrary data during one routing request. - * @return The disutility to travel over the link link, departing at time time. - */ - public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle, final CustomDataManager dataManager); - - /** - * This is used for walking to and from the nearest transit stop from the start and end location, - * as well as for the "direct" walk from start to finish without using a pt line at all. - * It is not used for transfer links (these are handled by the transitTravelDisutility). - */ - double getWalkTravelTime(Person person, Coord coord, Coord toCoord); - - double getWalkTravelDisutility(Person person, Coord coord, Coord toCoord); - - -} diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleUtils.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleUtils.java index dca8c47a25b..e06377d0351 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleUtils.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleUtils.java @@ -29,43 +29,44 @@ /** * Helper class for commonly used operations on TransitSchedules - * + * * @author Thibaut Dubernet, gleich * */ public final class TransitScheduleUtils { - // Logic gotten from PopulationUtils, but I am actually a bit unsure about the value of those methods now that - // attributable is the only way to get attributes... - public static Object getStopFacilityAttribute(TransitStopFacility facility, String key) { - return facility.getAttributes().getAttribute( key ); + public final static String ACCESSTIME_ATTRIBUTE = "accessTime"; + public final static String EGRESSTIME_ATTRIBUTE = "egressTime"; + private TransitScheduleUtils() { } - public static void putStopFacilityAttribute(TransitStopFacility facility, String key, Object value ) { - facility.getAttributes().putAttribute( key, value ) ; + public static double getStopAccessTime(TransitStopFacility stopFacility){ + Object accessTime = stopFacility.getAttributes().getAttribute(ACCESSTIME_ATTRIBUTE); + return accessTime!=null?(double) accessTime:0.0; } - public static Object removeStopFacilityAttribute( TransitStopFacility facility, String key ) { - return facility.getAttributes().removeAttribute( key ); + public static void setStopAccessTime(TransitStopFacility stopFacility, double stopAccessTime){ + stopFacility.getAttributes().putAttribute(ACCESSTIME_ATTRIBUTE,stopAccessTime); } - public static Object getLineAttribute(TransitLine facility, String key) { - return facility.getAttributes().getAttribute( key ); + public static double getStopEgressTime(TransitStopFacility stopFacility){ + Object egressTime = stopFacility.getAttributes().getAttribute(EGRESSTIME_ATTRIBUTE); + return egressTime!=null?(double) egressTime:0.0; } - - public static void putLineAttribute(TransitLine facility, String key, Object value ) { - facility.getAttributes().putAttribute( key, value ) ; + public static void setStopEgressTime(TransitStopFacility stopFacility, double stopEgressTime){ + stopFacility.getAttributes().putAttribute(EGRESSTIME_ATTRIBUTE,stopEgressTime); } - public static Object removeLineAttribute( TransitLine facility, String key ) { - return facility.getAttributes().removeAttribute( key ); + public static void setSymmetricStopAccessEgressTime(TransitStopFacility stopFacility, double stopAccessEgressTime){ + setStopAccessTime(stopFacility,stopAccessEgressTime); + setStopEgressTime(stopFacility,stopAccessEgressTime); } - - public final static QuadTree createQuadTreeOfTransitStopFacilities(TransitSchedule transitSchedule) { + + public static QuadTree createQuadTreeOfTransitStopFacilities(TransitSchedule transitSchedule) { return createQuadTreeOfTransitStopFacilities(transitSchedule.getFacilities().values()); } - - public final static QuadTree createQuadTreeOfTransitStopFacilities(Collection transitStopFacilities) { + + public static QuadTree createQuadTreeOfTransitStopFacilities(Collection transitStopFacilities) { double minX = Double.POSITIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleWriterV1.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleWriterV1.java index 0bd60a2886b..233718e146e 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleWriterV1.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleWriterV1.java @@ -20,6 +20,7 @@ package org.matsim.pt.transitSchedule; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -33,7 +34,6 @@ import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.IdentityTransformation; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleWriterV2.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleWriterV2.java index 581da9077ef..8e2c901d79d 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleWriterV2.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleWriterV2.java @@ -21,6 +21,7 @@ import java.io.IOException; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -34,7 +35,6 @@ import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.IdentityTransformation; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.MinimalTransferTimes; import org.matsim.pt.transitSchedule.api.TransitLine; diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitScheduleReader.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitScheduleReader.java index 1e5b4dc34a3..ce785546de4 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitScheduleReader.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitScheduleReader.java @@ -26,13 +26,13 @@ import org.matsim.core.utils.geometry.transformations.IdentityTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.core.utils.io.MatsimXmlParser; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.pt.transitSchedule.TransitScheduleReaderV1; import org.matsim.pt.transitSchedule.TransitScheduleReaderV2; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.URL; import java.util.Stack; diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitScheduleWriter.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitScheduleWriter.java index 83a97dde3b8..46e2049e68c 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitScheduleWriter.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitScheduleWriter.java @@ -26,10 +26,11 @@ import org.matsim.core.gbl.Gbl; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.IdentityTransformation; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.pt.transitSchedule.TransitScheduleWriterV1; import org.matsim.pt.transitSchedule.TransitScheduleWriterV2; +import java.io.UncheckedIOException; + /** * Writes {@link TransitSchedule}s to file in one of the * supported file formats. @@ -38,7 +39,7 @@ */ public class TransitScheduleWriter implements MatsimSomeWriter { private static final Logger log = LogManager.getLogger( TransitScheduleWriter.class ) ; - + private final TransitSchedule schedule; private final CoordinateTransformation transformation; diff --git a/matsim/src/main/java/org/matsim/run/Events2Snapshot.java b/matsim/src/main/java/org/matsim/run/Events2Snapshot.java index b62af9d7b2d..def875888c7 100644 --- a/matsim/src/main/java/org/matsim/run/Events2Snapshot.java +++ b/matsim/src/main/java/org/matsim/run/Events2Snapshot.java @@ -35,12 +35,11 @@ import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.core.utils.misc.ArgumentParser; import org.matsim.vis.snapshotwriters.SnapshotWriter; import org.matsim.vis.snapshotwriters.TransimsSnapshotWriter; -import static org.matsim.core.config.groups.ControlerConfigGroup.*; +import static org.matsim.core.config.groups.ControllerConfigGroup.*; /** * Converts an events file to a snapshot file. @@ -190,7 +189,7 @@ private void prepare() { this.events = EventsUtils.createEventsManager(); // create SnapshotGenerator - this.visualizer = new SnapshotGenerator(this.network, this.config.qsim().getSnapshotPeriod(), + this.visualizer = new SnapshotGenerator(this.network, this.config.qsim().getSnapshotPeriod(), this.config.qsim()); this.events.addHandler(this.visualizer); } @@ -205,7 +204,7 @@ private void loadSnapshotWriters(final String outputDir) { this.visualizer.addSnapshotWriter(this.writer); } - Collection snapshotFormats = this.config.controler().getSnapshotFormat(); + Collection snapshotFormats = this.config.controller().getSnapshotFormat(); for( SnapshotFormat snapshotFormat : snapshotFormats ){ switch( snapshotFormat ){ diff --git a/matsim/src/main/java/org/matsim/run/InitRoutes.java b/matsim/src/main/java/org/matsim/run/InitRoutes.java index 86818565166..923a94d937c 100644 --- a/matsim/src/main/java/org/matsim/run/InitRoutes.java +++ b/matsim/src/main/java/org/matsim/run/InitRoutes.java @@ -137,7 +137,7 @@ public void run(final String[] args) { final StreamingPopulationWriter plansWriter = new StreamingPopulationWriter(); Gbl.assertNotNull(this.plansfile); plansWriter.startStreaming(this.plansfile); - final FreespeedTravelTimeAndDisutility timeCostCalc = new FreespeedTravelTimeAndDisutility(config.planCalcScore()); + final FreespeedTravelTimeAndDisutility timeCostCalc = new FreespeedTravelTimeAndDisutility(config.scoring()); com.google.inject.Injector injector = Injector.createInjector(scenario.getConfig(), new AbstractModule() { @Override public void install() { diff --git a/matsim/src/main/java/org/matsim/run/RunMatsim.java b/matsim/src/main/java/org/matsim/run/RunMatsim.java index ef8e2f43618..8ceafae61db 100644 --- a/matsim/src/main/java/org/matsim/run/RunMatsim.java +++ b/matsim/src/main/java/org/matsim/run/RunMatsim.java @@ -32,31 +32,31 @@ public class RunMatsim { private final org.matsim.core.controler.Controler controler; - + public RunMatsim(final String[] args) { this.controler = new org.matsim.core.controler.Controler(args); } - + public RunMatsim(final String configFilename) { this.controler = new org.matsim.core.controler.Controler(configFilename); } - + public void setOverwriteFiles(final boolean overwriteFiles) { - this.controler.getConfig().controler().setOverwriteFileSetting( + this.controler.getConfig().controller().setOverwriteFileSetting( overwriteFiles ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists ); } - + public Scenario getScenario() { return this.controler.getScenario() ; } - + public void run() { this.controler.run(); } - + public static void main(String[] args) { new RunMatsim(args).run(); } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/run/gui/Gui.java b/matsim/src/main/java/org/matsim/run/gui/Gui.java index 8d79c2b083a..edbd65e199a 100644 --- a/matsim/src/main/java/org/matsim/run/gui/Gui.java +++ b/matsim/src/main/java/org/matsim/run/gui/Gui.java @@ -499,7 +499,7 @@ public void loadConfigFile(final File configFile) { txtConfigfilename.setText(configFilename); File par = configFile.getParentFile(); - File outputDir = new File(par, config.controler().getOutputDirectory()); + File outputDir = new File(par, config.controller().getOutputDirectory()); try { txtOutput.setText(outputDir.getCanonicalPath()); } catch (IOException e1) { diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesConverter.java b/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesConverter.java index ee7eed06f03..6c0e0afbfe3 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesConverter.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesConverter.java @@ -26,6 +26,7 @@ import org.apache.logging.log4j.Logger; import org.matsim.utils.objectattributes.attributeconverters.*; import org.matsim.api.core.v01.Coord; +import org.matsim.vehicles.PersonVehicleTypes; import org.matsim.vehicles.PersonVehicles; import java.util.*; @@ -60,6 +61,7 @@ public ObjectAttributesConverter() { this.converters.put(Coord.class.getName(), new CoordConverter()); this.converters.put(Coord[].class.getName(), new CoordArrayConverter()); this.converters.put(PersonVehicles.class.getName(), new PersonVehiclesAttributeConverter()); + this.converters.put(PersonVehicleTypes.class.getName(), new PersonVehicleTypesAttributeConverter()); } //this is for reading diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlWriter.java b/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlWriter.java index 4050cf6429c..8955547cdef 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlWriter.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlWriter.java @@ -19,12 +19,10 @@ package org.matsim.utils.objectattributes; -import java.util.HashMap; -import java.util.HashSet; +import java.io.UncheckedIOException; import java.util.LinkedList; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.TreeMap; import com.google.inject.Inject; @@ -32,12 +30,6 @@ import org.apache.logging.log4j.Logger; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; -import org.matsim.utils.objectattributes.attributeconverters.BooleanConverter; -import org.matsim.utils.objectattributes.attributeconverters.DoubleConverter; -import org.matsim.utils.objectattributes.attributeconverters.IntegerConverter; -import org.matsim.utils.objectattributes.attributeconverters.LongConverter; -import org.matsim.utils.objectattributes.attributeconverters.StringConverter; /** * Writes object attributes to a file. diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/attributable/AttributesXmlWriterDelegate.java b/matsim/src/main/java/org/matsim/utils/objectattributes/attributable/AttributesXmlWriterDelegate.java index 0423962e88d..acffcd10e40 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/attributable/AttributesXmlWriterDelegate.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/attributable/AttributesXmlWriterDelegate.java @@ -21,13 +21,13 @@ package org.matsim.utils.objectattributes.attributable; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.io.XmlUtils; import org.matsim.utils.objectattributes.AttributeConverter; import org.matsim.utils.objectattributes.ObjectAttributesConverter; import java.io.BufferedWriter; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.Map; /** diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/PersonVehicleTypesAttributeConverter.java b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/PersonVehicleTypesAttributeConverter.java new file mode 100644 index 00000000000..9c01e8ab9c6 --- /dev/null +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/PersonVehicleTypesAttributeConverter.java @@ -0,0 +1,42 @@ +package org.matsim.utils.objectattributes.attributeconverters; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.matsim.api.core.v01.Id; +import org.matsim.utils.objectattributes.AttributeConverter; +import org.matsim.vehicles.PersonVehicleTypes; +import org.matsim.vehicles.VehicleType; + +import java.util.HashMap; +import java.util.Map; + +/** + * Converter to store vehicle types as person attribute. + */ +public class PersonVehicleTypesAttributeConverter implements AttributeConverter { + + private final Logger logger = LogManager.getLogger(PersonVehicleTypesAttributeConverter.class); + + @Override + public PersonVehicleTypes convert(String value) { + PersonVehicleTypes vehicles = new PersonVehicleTypes(); + Map stringMap = new StringStringMapConverter().convert(value); + for (Map.Entry entry: stringMap.entrySet()) { + vehicles.addModeVehicleType(entry.getKey(), Id.create(entry.getValue(), VehicleType.class)); + } + return vehicles; + } + + @Override + public String convertToString(Object o) { + if(!(o instanceof PersonVehicleTypes vehicles)){ + logger.error("Object is not of type PersonVehicles: " + o.getClass()); + return null; + } + Map stringMap = new HashMap<>(); + for (Map.Entry> entry: vehicles.getModeVehicleTypes().entrySet()) { + stringMap.put(entry.getKey(), entry.getValue().toString()); + } + return new StringStringMapConverter().convertToString(stringMap); + } +} diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/PersonVehiclesAttributeConverter.java b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/PersonVehiclesAttributeConverter.java index dd5440df404..96484c502a2 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/PersonVehiclesAttributeConverter.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/PersonVehiclesAttributeConverter.java @@ -26,12 +26,11 @@ public PersonVehicles convert(String value) { @Override public String convertToString(Object o) { - if(!(o instanceof PersonVehicles)){ - logger.error("Object is not of type PersonVehicles: " + o.getClass().toString()); + if(!(o instanceof PersonVehicles vehicles)){ + logger.error("Object is not of type PersonVehicles: " + o.getClass()); return null; } - PersonVehicles vehicles = (PersonVehicles)o; - Map stringMap = new HashMap<>(); + Map stringMap = new HashMap<>(); for (Map.Entry> entry: vehicles.getModeVehicles().entrySet()) { stringMap.put(entry.getKey(), entry.getValue().toString()); } diff --git a/matsim/src/main/java/org/matsim/vehicles/MatsimVehicleWriter.java b/matsim/src/main/java/org/matsim/vehicles/MatsimVehicleWriter.java index e8883a22bee..dc757046ba0 100644 --- a/matsim/src/main/java/org/matsim/vehicles/MatsimVehicleWriter.java +++ b/matsim/src/main/java/org/matsim/vehicles/MatsimVehicleWriter.java @@ -20,17 +20,11 @@ package org.matsim.vehicles; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -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.core.gbl.Gbl; -import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.io.MatsimXmlWriter; -import org.matsim.core.utils.io.UncheckedIOException; /** * This is the new default Writer for the vehicles file. @@ -38,7 +32,7 @@ * @author kturner */ public final class MatsimVehicleWriter extends MatsimXmlWriter { - + private static final Logger log = LogManager.getLogger(MatsimVehicleWriter.class); private VehicleWriterV2 delegate; diff --git a/matsim/src/main/java/org/matsim/vehicles/PersonVehicleTypes.java b/matsim/src/main/java/org/matsim/vehicles/PersonVehicleTypes.java new file mode 100644 index 00000000000..e07198587bb --- /dev/null +++ b/matsim/src/main/java/org/matsim/vehicles/PersonVehicleTypes.java @@ -0,0 +1,33 @@ +package org.matsim.vehicles; + +import org.matsim.api.core.v01.Id; + +import java.util.HashMap; +import java.util.Map; + +/** + * Container class to store mode specific person vehicle types. + */ +public final class PersonVehicleTypes { + + private final Map> modeVehicleTypes = new HashMap<>(); + + public PersonVehicleTypes() { + } + + public void addModeVehicleType(String mode, Id vehicleType) { + modeVehicleTypes.put(mode, vehicleType); + } + + public Id getVehicleType(String mode) { + return modeVehicleTypes.get(mode); + } + + public Map> getModeVehicleTypes() { + return modeVehicleTypes; + } + + public void putModeVehicleTypes(Map> vehicleTypes) { + modeVehicleTypes.putAll(vehicleTypes); + } +} diff --git a/matsim/src/main/java/org/matsim/vehicles/VehicleUtils.java b/matsim/src/main/java/org/matsim/vehicles/VehicleUtils.java index e3594e65885..0141e814600 100644 --- a/matsim/src/main/java/org/matsim/vehicles/VehicleUtils.java +++ b/matsim/src/main/java/org/matsim/vehicles/VehicleUtils.java @@ -41,6 +41,7 @@ public final class VehicleUtils { private static final VehicleType DEFAULT_VEHICLE_TYPE = VehicleUtils.getFactory().createVehicleType(Id.create("defaultVehicleType", VehicleType.class)); private static final String VEHICLE_ATTRIBUTE_KEY = "vehicles"; + private static final String VEHICLE_TYPES_ATTRIBUTE_KEY = "vehicleTypes"; // should remain under the hood --> should remain private private static final String DOOR_OPERATION_MODE = "doorOperationMode" ; @@ -117,11 +118,11 @@ public static void copyFromTo( VehicleType in, VehicleType out ) { /** * Checks whether a person has a vehicle id for mode - without throwing an * exception if not. - * + * * @param person the person one wants to check for a vehicle id * @param mode the mode for the vehicle id to check * @return whether person has a vehicle id for that mode - * + * * @see {@link VehicleUtils#getVehicleId(Person, String)} */ public static boolean hasVehicleId(Person person, String mode) { @@ -147,6 +148,15 @@ public static Map> getVehicleIds(Person person) { return personVehicles.getModeVehicles(); } + /** + * Retrieve the optional vehicle types per mode that might be assigned to a person. + * Returns null if this is not defined. + */ + public static Map> getVehicleTypes(Person person) { + var personVehicles = (PersonVehicleTypes) person.getAttributes().getAttribute(VehicleUtils.VEHICLE_TYPES_ATTRIBUTE_KEY); + return personVehicles != null ? personVehicles.getModeVehicleTypes() : null; + } + /** * Retrieves a vehicleId from the person's attributes. * @@ -179,13 +189,32 @@ public static void insertVehicleIdsIntoAttributes(Person person, Map> modeToVehicleCopy = new HashMap<>(modeToVehicle); PersonVehicles personVehicles; if (attr == null) { - personVehicles = new PersonVehicles(modeToVehicleCopy); + personVehicles = new PersonVehicles(); } else { personVehicles = (PersonVehicles) attr; } personVehicles.addModeVehicleList(modeToVehicleCopy); person.getAttributes().putAttribute(VEHICLE_ATTRIBUTE_KEY, personVehicles); } + + /** + * Attaches vehicle types to a person, so that the router knows which vehicle to use for which mode and person. + * @param modeToVehicleType mode string mapped to vehicle type ids. The provided map is copied and stored as unmodifiable map. + */ + public static void insertVehicleTypesIntoAttributes(Person person, Map> modeToVehicleType) { + Object attr = person.getAttributes().getAttribute(VEHICLE_TYPES_ATTRIBUTE_KEY); + + Map> modeToTypesCopy = new HashMap<>(modeToVehicleType); + PersonVehicleTypes personVehiclesTypes; + if (attr == null) { + personVehiclesTypes = new PersonVehicleTypes(); + } else { + personVehiclesTypes = (PersonVehicleTypes) attr; + } + personVehiclesTypes.putModeVehicleTypes(modeToTypesCopy); + person.getAttributes().putAttribute(VEHICLE_TYPES_ATTRIBUTE_KEY, personVehiclesTypes); + } + //******** general VehicleType attributes ************ public static VehicleType.DoorOperationMode getDoorOperationMode( VehicleType vehicleType ){ diff --git a/matsim/src/main/java/org/matsim/vehicles/VehicleWriterV1.java b/matsim/src/main/java/org/matsim/vehicles/VehicleWriterV1.java index b69aedd4816..a5a443df95d 100644 --- a/matsim/src/main/java/org/matsim/vehicles/VehicleWriterV1.java +++ b/matsim/src/main/java/org/matsim/vehicles/VehicleWriterV1.java @@ -22,6 +22,7 @@ import static java.util.Comparator.comparing; import static java.util.stream.Collectors.toList; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -32,7 +33,6 @@ 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; /** * @author dgrether @@ -55,7 +55,7 @@ public VehicleWriterV1(Vehicles vehicles) { this.vehicleTypes = vehicles.getVehicleTypes(); this.vehicles = vehicles.getVehicles(); } - + public void writeFile(String filename) throws UncheckedIOException { log.info( Gbl.aboutToWrite( "vehicles", filename) ) ; this.openFile(filename); @@ -179,5 +179,5 @@ private void writeFreightCapacity(double fc) throws UncheckedIOException { this.writeStartTag(VehicleSchemaV1Names.VOLUME, atts, true); this.writeEndTag(VehicleSchemaV1Names.FREIGHTCAPACITY); } - + } diff --git a/matsim/src/main/java/org/matsim/vehicles/VehicleWriterV2.java b/matsim/src/main/java/org/matsim/vehicles/VehicleWriterV2.java index 26bbdc8126d..4d5efec3771 100644 --- a/matsim/src/main/java/org/matsim/vehicles/VehicleWriterV2.java +++ b/matsim/src/main/java/org/matsim/vehicles/VehicleWriterV2.java @@ -23,6 +23,7 @@ import static java.util.stream.Collectors.toList; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -35,7 +36,6 @@ 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 org.matsim.utils.objectattributes.AttributeConverter; import org.matsim.utils.objectattributes.attributable.AttributesXmlWriterDelegate; diff --git a/matsim/src/main/java/org/matsim/vis/snapshotwriters/SnapshotWritersModule.java b/matsim/src/main/java/org/matsim/vis/snapshotwriters/SnapshotWritersModule.java index 7b9b5d325f3..858446f845b 100644 --- a/matsim/src/main/java/org/matsim/vis/snapshotwriters/SnapshotWritersModule.java +++ b/matsim/src/main/java/org/matsim/vis/snapshotwriters/SnapshotWritersModule.java @@ -22,7 +22,7 @@ package org.matsim.vis.snapshotwriters; -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.mobsim.framework.listeners.MobsimListener; @@ -32,7 +32,7 @@ import jakarta.inject.Provider; import java.util.Collection; -import static org.matsim.core.config.groups.ControlerConfigGroup.SnapshotFormat; +import static org.matsim.core.config.groups.ControllerConfigGroup.SnapshotFormat; public class SnapshotWritersModule extends AbstractModule { @@ -40,13 +40,13 @@ public class SnapshotWritersModule extends AbstractModule { @Override public void install() { - if (getConfig().controler().getSnapshotFormat().contains(SnapshotFormat.transims)) { + if (getConfig().controller().getSnapshotFormat().contains(SnapshotFormat.transims)) { addSnapshotWriterBinding().toProvider(TransimsSnapshotWriterFactory.class); } - if (getConfig().controler().getSnapshotFormat().contains(SnapshotFormat.positionevents)) { + if (getConfig().controller().getSnapshotFormat().contains(SnapshotFormat.positionevents)) { addSnapshotWriterBinding().toProvider(PositionEventsWriterFactory.class); } - if (getConfig().controler().getWriteSnapshotsInterval() != 0) { + if (getConfig().controller().getWriteSnapshotsInterval() != 0) { addMobsimListenerBinding().toProvider(SnapshotWriterManagerProvider.class); } } @@ -54,23 +54,23 @@ public void install() { private static class SnapshotWriterManagerProvider implements Provider { private final QSimConfigGroup qSimConfigGroup; - private final ControlerConfigGroup controlerConfigGroup; + private final ControllerConfigGroup controllerConfigGroup; private final ReplanningContext iterationContext; private final Collection> snapshotWriters; @Inject - private SnapshotWriterManagerProvider(QSimConfigGroup qSimConfigGroup, ControlerConfigGroup controlerConfigGroup, + private SnapshotWriterManagerProvider(QSimConfigGroup qSimConfigGroup, ControllerConfigGroup controllerConfigGroup, ReplanningContext iterationContext, Collection> snapshotWriters) { this.qSimConfigGroup = qSimConfigGroup; - this.controlerConfigGroup = controlerConfigGroup; + this.controllerConfigGroup = controllerConfigGroup; this.iterationContext = iterationContext; this.snapshotWriters = snapshotWriters; } @Override public MobsimListener get() { - if (iterationContext.getIteration() % controlerConfigGroup.getWriteSnapshotsInterval() == 0) { + if (iterationContext.getIteration() % controllerConfigGroup.getWriteSnapshotsInterval() == 0) { SnapshotWriterManager manager = new SnapshotWriterManager((int) qSimConfigGroup.getSnapshotPeriod(), qSimConfigGroup.getFilterSnapshots()); for (com.google.inject.Provider snapshotWriter : this.snapshotWriters) { manager.addSnapshotWriter(snapshotWriter.get()); diff --git a/matsim/src/main/java/org/matsim/visum/VisumNetworkReader.java b/matsim/src/main/java/org/matsim/visum/VisumNetworkReader.java index a2daff64e36..866ff295215 100644 --- a/matsim/src/main/java/org/matsim/visum/VisumNetworkReader.java +++ b/matsim/src/main/java/org/matsim/visum/VisumNetworkReader.java @@ -22,6 +22,7 @@ import java.io.BufferedReader; import java.io.IOException; +import java.io.UncheckedIOException; import java.nio.charset.Charset; import org.apache.logging.log4j.LogManager; @@ -31,7 +32,6 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Node; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.StringUtils; import org.matsim.visum.VisumNetwork.StopPoint; import org.matsim.visum.VisumNetwork.TransitLine; @@ -304,7 +304,7 @@ private void readStopPoints(final String tableAttributes, final BufferedReader r final String[] parts = StringUtils.explode(line, ';'); VisumNetwork.StopPoint stopPt = new VisumNetwork.StopPoint(Id.create(parts[idxNo], VisumNetwork.StopPoint.class), Id.create(parts[idxStopAreaNo], VisumNetwork.StopArea.class), - parts[idxName], + parts[idxName], Id.create(parts[idxRLNo], Link.class), Id.create(parts[idxNode], Node.class)); this.network.addStopPoint(stopPt); // proceed to next line @@ -413,7 +413,7 @@ private void readTimeProfileItems(final String tableAttributes, final BufferedRe while (line != null && line.length() > 0) { final String[] parts = StringUtils.explode(line, ';'); - VisumNetwork.TimeProfileItem tpi1 = new VisumNetwork.TimeProfileItem(parts[idxLineName], parts[idxLineRouteName], + VisumNetwork.TimeProfileItem tpi1 = new VisumNetwork.TimeProfileItem(parts[idxLineName], parts[idxLineRouteName], parts[idxTPName], parts[idxDCode], parts[idxIndex], parts[idxArr], parts[idxDep], Id.create(parts[idxLRIIndex], VisumNetwork.TimeProfileItem.class)); this.network.addTimeProfileItem(tpi1); diff --git a/matsim/src/main/java/org/matsim/withinday/controller/ExampleWithinDayController.java b/matsim/src/main/java/org/matsim/withinday/controller/ExampleWithinDayController.java index b10d49a5ce8..504a6005756 100644 --- a/matsim/src/main/java/org/matsim/withinday/controller/ExampleWithinDayController.java +++ b/matsim/src/main/java/org/matsim/withinday/controller/ExampleWithinDayController.java @@ -31,7 +31,7 @@ import org.matsim.api.core.v01.network.Network; 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.events.StartupEvent; @@ -133,7 +133,7 @@ public static void main(final String[] args) { } Config config = ConfigUtils.loadConfig( args[0] , new WithinDayConfigGroup() ) ; - config.controler().setRoutingAlgorithmType( ControlerConfigGroup.RoutingAlgorithmType.Dijkstra ); + config.controller().setRoutingAlgorithmType( ControllerConfigGroup.RoutingAlgorithmType.Dijkstra ); Scenario scenario = ScenarioUtils.loadScenario( config) ; diff --git a/matsim/src/main/java/org/matsim/withinday/controller/ExecutedPlansServiceImpl.java b/matsim/src/main/java/org/matsim/withinday/controller/ExecutedPlansServiceImpl.java index eff6b0d3b57..e0c426d28c7 100644 --- a/matsim/src/main/java/org/matsim/withinday/controller/ExecutedPlansServiceImpl.java +++ b/matsim/src/main/java/org/matsim/withinday/controller/ExecutedPlansServiceImpl.java @@ -112,7 +112,7 @@ public void notifyAfterMobsim(AfterMobsimEvent event) { // write this in every iteration in order to be consistent with previous design. I think this should be changed. kai, jun'16 // as a quick fix, writing this as often as the base plans file. kai, jun'23 - if ( event.getIteration() % scenario.getConfig().controler().getWritePlansInterval() == 0 ){ + if ( event.getIteration() % scenario.getConfig().controller().getWritePlansInterval() == 0 ){ String outputFile = controlerIO.getIterationFilename( event.getIteration(), EXECUTEDPLANSFILE ); writeExecutedPlans( outputFile ); } diff --git a/matsim/src/main/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeModule.java b/matsim/src/main/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeModule.java index bf1f154ce59..da440f5385e 100644 --- a/matsim/src/main/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeModule.java +++ b/matsim/src/main/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeModule.java @@ -23,7 +23,7 @@ import jakarta.inject.Singleton; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.AbstractModule; public class WithinDayTravelTimeModule extends AbstractModule { @@ -33,7 +33,7 @@ public WithinDayTravelTimeModule() { @Override public void install() { - if (getConfig().controler().getRoutingAlgorithmType() != ControlerConfigGroup.RoutingAlgorithmType.Dijkstra) { + if (getConfig().controller().getRoutingAlgorithmType() != ControllerConfigGroup.RoutingAlgorithmType.Dijkstra) { throw new RuntimeException( "for me, in KNAccidentScenario, this works with Dijkstra (default until spring 2019), and does not work with AStarLandmarks " + "(default afterwards). I have not tried the other routing options, nor have I systematically debugged. KN, feb'19"); diff --git a/matsim/src/test/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroupTest.java b/matsim/src/test/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroupTest.java index 46e27773c85..2db9c5610db 100644 --- a/matsim/src/test/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroupTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroupTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.config; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup.IntermodalAccessEgressParameterSet; @@ -69,7 +84,7 @@ public void testConfigIO_rangeQuery() { RangeQuerySettingsParameterSet range2 = new RangeQuerySettingsParameterSet(); range2.setSubpopulations("inflexible"); - range2.setMaxEarlierDeparture(1*60); + range2.setMaxEarlierDeparture(60); range2.setMaxLaterDeparture(15*60); config1.addRangeQuerySettings(range2); } @@ -89,7 +104,7 @@ public void testConfigIO_rangeQuery() { Assert.assertNotNull(range2); Assert.assertEquals(1, range2.getSubpopulations().size()); Assert.assertEquals("inflexible", range2.getSubpopulations().iterator().next()); - Assert.assertEquals(1*60, range2.getMaxEarlierDeparture()); + Assert.assertEquals(60, range2.getMaxEarlierDeparture()); Assert.assertEquals(15*60, range2.getMaxLaterDeparture()); } diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/CapacityDependentScoringTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/CapacityDependentScoringTest.java index 30839b65d84..31ebe0fa112 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/CapacityDependentScoringTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/CapacityDependentScoringTest.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.junit.Assert; diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/FakeFacility.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/FakeFacility.java index 8eba9c75908..9eb173085d5 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/FakeFacility.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/FakeFacility.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.matsim.api.core.v01.Coord; @@ -27,7 +42,8 @@ public FakeFacility(Coord coord) { this.linkId = linkId; } - public Coord getCoord() { + @Override + public Coord getCoord() { return this.coord; } @@ -35,11 +51,13 @@ public Id getId() { throw new RuntimeException("not implemented"); } - public Map getCustomAttributes() { + @Override + public Map getCustomAttributes() { throw new RuntimeException("not implemented"); } - public Id getLinkId() { + @Override + public Id getLinkId() { return this.linkId; } } diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/Fixture.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/Fixture.java index b098fd5b318..97bdc02747a 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/Fixture.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/Fixture.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.ArrayList; @@ -85,7 +100,7 @@ public Fixture() { this.config = ConfigUtils.createConfig(); this.config.transit().setUseTransit(true); - + ScenarioBuilder scBuilder = new ScenarioBuilder(config) ; this.scenario = (MutableScenario) scBuilder.build() ; @@ -104,23 +119,23 @@ protected void init() { } protected void buildNetwork() { - this.nodes[0] = this.network.getFactory().createNode(Id.create("0", Node.class), new Coord((double) 0, (double) 5000)); - this.nodes[1] = this.network.getFactory().createNode(Id.create("1", Node.class), new Coord((double) 4000, (double) 5000)); - this.nodes[2] = this.network.getFactory().createNode(Id.create("2", Node.class), new Coord((double) 8000, (double) 5000)); - this.nodes[3] = this.network.getFactory().createNode(Id.create("3", Node.class), new Coord((double) 12000, (double) 5000)); - this.nodes[4] = this.network.getFactory().createNode(Id.create("4", Node.class), new Coord((double) 16000, (double) 5000)); - this.nodes[5] = this.network.getFactory().createNode(Id.create("5", Node.class), new Coord((double) 20000, (double) 5000)); - this.nodes[6] = this.network.getFactory().createNode(Id.create("6", Node.class), new Coord((double) 24000, (double) 5000)); - this.nodes[7] = this.network.getFactory().createNode(Id.create("7", Node.class), new Coord((double) 28000, (double) 5000)); - this.nodes[8] = this.network.getFactory().createNode(Id.create("8", Node.class), new Coord((double) 32000, (double) 5000)); - this.nodes[9] = this.network.getFactory().createNode(Id.create("9", Node.class), new Coord((double) 36000, (double) 5000)); - this.nodes[10] = this.network.getFactory().createNode(Id.create("10", Node.class), new Coord((double) 40000, (double) 5000)); - this.nodes[11] = this.network.getFactory().createNode(Id.create("11", Node.class), new Coord((double) 12000, (double) 5000)); - this.nodes[12] = this.network.getFactory().createNode(Id.create("12", Node.class), new Coord((double) 16000, (double) 10000)); - this.nodes[13] = this.network.getFactory().createNode(Id.create("13", Node.class), new Coord((double) 24000, (double) 10000)); - this.nodes[14] = this.network.getFactory().createNode(Id.create("14", Node.class), new Coord((double) 28000, (double) 5000)); - this.nodes[15] = this.network.getFactory().createNode(Id.create("15", Node.class), new Coord((double) 24000, (double) 0)); - this.nodes[16] = this.network.getFactory().createNode(Id.create("16", Node.class), new Coord((double) 16000, (double) 0)); + this.nodes[0] = this.network.getFactory().createNode(Id.create("0", Node.class), new Coord(0, 5000)); + this.nodes[1] = this.network.getFactory().createNode(Id.create("1", Node.class), new Coord(4000, 5000)); + this.nodes[2] = this.network.getFactory().createNode(Id.create("2", Node.class), new Coord(8000, 5000)); + this.nodes[3] = this.network.getFactory().createNode(Id.create("3", Node.class), new Coord(12000, 5000)); + this.nodes[4] = this.network.getFactory().createNode(Id.create("4", Node.class), new Coord(16000, 5000)); + this.nodes[5] = this.network.getFactory().createNode(Id.create("5", Node.class), new Coord(20000, 5000)); + this.nodes[6] = this.network.getFactory().createNode(Id.create("6", Node.class), new Coord(24000, 5000)); + this.nodes[7] = this.network.getFactory().createNode(Id.create("7", Node.class), new Coord(28000, 5000)); + this.nodes[8] = this.network.getFactory().createNode(Id.create("8", Node.class), new Coord(32000, 5000)); + this.nodes[9] = this.network.getFactory().createNode(Id.create("9", Node.class), new Coord(36000, 5000)); + this.nodes[10] = this.network.getFactory().createNode(Id.create("10", Node.class), new Coord(40000, 5000)); + this.nodes[11] = this.network.getFactory().createNode(Id.create("11", Node.class), new Coord(12000, 5000)); + this.nodes[12] = this.network.getFactory().createNode(Id.create("12", Node.class), new Coord(16000, 10000)); + this.nodes[13] = this.network.getFactory().createNode(Id.create("13", Node.class), new Coord(24000, 10000)); + this.nodes[14] = this.network.getFactory().createNode(Id.create("14", Node.class), new Coord(28000, 5000)); + this.nodes[15] = this.network.getFactory().createNode(Id.create("15", Node.class), new Coord(24000, 0)); + this.nodes[16] = this.network.getFactory().createNode(Id.create("16", Node.class), new Coord(16000, 0)); for (int i = 0; i < 17; i++) { this.network.addNode(this.nodes[i]); } @@ -167,30 +182,30 @@ protected void buildNetwork() { } protected void buildStops() { - this.stopFacilities[ 0] = this.builder.createTransitStopFacility(Id.create( "0", TransitStopFacility.class), new Coord((double) 4000, (double) 5002), true); - this.stopFacilities[ 1] = this.builder.createTransitStopFacility(Id.create( "1", TransitStopFacility.class), new Coord((double) 4000, (double) 4998), true); - this.stopFacilities[ 2] = this.builder.createTransitStopFacility(Id.create( "2", TransitStopFacility.class), new Coord((double) 8000, (double) 5002), true); - this.stopFacilities[ 3] = this.builder.createTransitStopFacility(Id.create( "3", TransitStopFacility.class), new Coord((double) 8000, (double) 4998), true); - this.stopFacilities[ 4] = this.builder.createTransitStopFacility(Id.create( "4", TransitStopFacility.class), new Coord((double) 12000, (double) 5002), true); - this.stopFacilities[ 5] = this.builder.createTransitStopFacility(Id.create( "5", TransitStopFacility.class), new Coord((double) 12000, (double) 4998), true); - this.stopFacilities[ 6] = this.builder.createTransitStopFacility(Id.create( "6", TransitStopFacility.class), new Coord((double) 16000, (double) 5002), true); - this.stopFacilities[ 7] = this.builder.createTransitStopFacility(Id.create( "7", TransitStopFacility.class), new Coord((double) 16000, (double) 4998), true); - this.stopFacilities[ 8] = this.builder.createTransitStopFacility(Id.create( "8", TransitStopFacility.class), new Coord((double) 20000, (double) 5002), true); - this.stopFacilities[ 9] = this.builder.createTransitStopFacility(Id.create( "9", TransitStopFacility.class), new Coord((double) 20000, (double) 4998), true); - this.stopFacilities[10] = this.builder.createTransitStopFacility(Id.create("10", TransitStopFacility.class), new Coord((double) 24000, (double) 5002), true); - this.stopFacilities[11] = this.builder.createTransitStopFacility(Id.create("11", TransitStopFacility.class), new Coord((double) 24000, (double) 4998), true); - this.stopFacilities[12] = this.builder.createTransitStopFacility(Id.create("12", TransitStopFacility.class), new Coord((double) 28000, (double) 5002), true); - this.stopFacilities[13] = this.builder.createTransitStopFacility(Id.create("13", TransitStopFacility.class), new Coord((double) 28000, (double) 4998), true); - this.stopFacilities[14] = this.builder.createTransitStopFacility(Id.create("14", TransitStopFacility.class), new Coord((double) 32000, (double) 5002), true); - this.stopFacilities[15] = this.builder.createTransitStopFacility(Id.create("15", TransitStopFacility.class), new Coord((double) 32000, (double) 4998), true); - this.stopFacilities[16] = this.builder.createTransitStopFacility(Id.create("16", TransitStopFacility.class), new Coord((double) 36000, (double) 5002), true); - this.stopFacilities[17] = this.builder.createTransitStopFacility(Id.create("17", TransitStopFacility.class), new Coord((double) 36000, (double) 4998), true); - this.stopFacilities[18] = this.builder.createTransitStopFacility(Id.create("18", TransitStopFacility.class), new Coord((double) 12000, (double) 5000), true); - this.stopFacilities[19] = this.builder.createTransitStopFacility(Id.create("19", TransitStopFacility.class), new Coord((double) 16000, (double) 10000), true); - this.stopFacilities[20] = this.builder.createTransitStopFacility(Id.create("20", TransitStopFacility.class), new Coord((double) 24000, (double) 10000), true); - this.stopFacilities[21] = this.builder.createTransitStopFacility(Id.create("21", TransitStopFacility.class), new Coord((double) 28000, (double) 5000), true); - this.stopFacilities[22] = this.builder.createTransitStopFacility(Id.create("22", TransitStopFacility.class), new Coord((double) 24000, (double) 0), true); - this.stopFacilities[23] = this.builder.createTransitStopFacility(Id.create("23", TransitStopFacility.class), new Coord((double) 16000, (double) 0), true); + this.stopFacilities[ 0] = this.builder.createTransitStopFacility(Id.create( "0", TransitStopFacility.class), new Coord(4000, 5002), true); + this.stopFacilities[ 1] = this.builder.createTransitStopFacility(Id.create( "1", TransitStopFacility.class), new Coord(4000, 4998), true); + this.stopFacilities[ 2] = this.builder.createTransitStopFacility(Id.create( "2", TransitStopFacility.class), new Coord(8000, 5002), true); + this.stopFacilities[ 3] = this.builder.createTransitStopFacility(Id.create( "3", TransitStopFacility.class), new Coord(8000, 4998), true); + this.stopFacilities[ 4] = this.builder.createTransitStopFacility(Id.create( "4", TransitStopFacility.class), new Coord(12000, 5002), true); + this.stopFacilities[ 5] = this.builder.createTransitStopFacility(Id.create( "5", TransitStopFacility.class), new Coord(12000, 4998), true); + this.stopFacilities[ 6] = this.builder.createTransitStopFacility(Id.create( "6", TransitStopFacility.class), new Coord(16000, 5002), true); + this.stopFacilities[ 7] = this.builder.createTransitStopFacility(Id.create( "7", TransitStopFacility.class), new Coord(16000, 4998), true); + this.stopFacilities[ 8] = this.builder.createTransitStopFacility(Id.create( "8", TransitStopFacility.class), new Coord(20000, 5002), true); + this.stopFacilities[ 9] = this.builder.createTransitStopFacility(Id.create( "9", TransitStopFacility.class), new Coord(20000, 4998), true); + this.stopFacilities[10] = this.builder.createTransitStopFacility(Id.create("10", TransitStopFacility.class), new Coord(24000, 5002), true); + this.stopFacilities[11] = this.builder.createTransitStopFacility(Id.create("11", TransitStopFacility.class), new Coord(24000, 4998), true); + this.stopFacilities[12] = this.builder.createTransitStopFacility(Id.create("12", TransitStopFacility.class), new Coord(28000, 5002), true); + this.stopFacilities[13] = this.builder.createTransitStopFacility(Id.create("13", TransitStopFacility.class), new Coord(28000, 4998), true); + this.stopFacilities[14] = this.builder.createTransitStopFacility(Id.create("14", TransitStopFacility.class), new Coord(32000, 5002), true); + this.stopFacilities[15] = this.builder.createTransitStopFacility(Id.create("15", TransitStopFacility.class), new Coord(32000, 4998), true); + this.stopFacilities[16] = this.builder.createTransitStopFacility(Id.create("16", TransitStopFacility.class), new Coord(36000, 5002), true); + this.stopFacilities[17] = this.builder.createTransitStopFacility(Id.create("17", TransitStopFacility.class), new Coord(36000, 4998), true); + this.stopFacilities[18] = this.builder.createTransitStopFacility(Id.create("18", TransitStopFacility.class), new Coord(12000, 5000), true); + this.stopFacilities[19] = this.builder.createTransitStopFacility(Id.create("19", TransitStopFacility.class), new Coord(16000, 10000), true); + this.stopFacilities[20] = this.builder.createTransitStopFacility(Id.create("20", TransitStopFacility.class), new Coord(24000, 10000), true); + this.stopFacilities[21] = this.builder.createTransitStopFacility(Id.create("21", TransitStopFacility.class), new Coord(28000, 5000), true); + this.stopFacilities[22] = this.builder.createTransitStopFacility(Id.create("22", TransitStopFacility.class), new Coord(24000, 0), true); + this.stopFacilities[23] = this.builder.createTransitStopFacility(Id.create("23", TransitStopFacility.class), new Coord(16000, 0), true); this.stopFacilities[ 0].setName("A"); this.stopFacilities[ 1].setName("A"); this.stopFacilities[ 2].setName("B"); @@ -445,14 +460,14 @@ protected void buildGreenLine() { route.addDeparture(this.builder.createDeparture(Id.create("g>18", Departure.class), 7.0*3600 + 51.0*60)); } } - + protected void addVehicles() { VehiclesFactory vf = transitVehicles.getFactory(); VehicleType trainType = vf.createVehicleType(Id.create("train", VehicleType.class)); trainType.getCapacity().setSeats(200); trainType.getCapacity().setStandingRoom(100); transitVehicles.addVehicleType(trainType); - + for (TransitLine line: schedule.getTransitLines().values()) { for (TransitRoute route: line.getRoutes().values()) { for (Departure dep: route.getDepartures().values()) { diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/IntermodalFixture.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/IntermodalFixture.java index 74a25a2ecee..495868e6991 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/IntermodalFixture.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/IntermodalFixture.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/OccupancyTrackerTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/OccupancyTrackerTest.java index 734c40cd43f..4e9b916dde4 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/OccupancyTrackerTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/OccupancyTrackerTest.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.routing.pt.raptor.OccupancyData.DepartureData; @@ -114,7 +133,7 @@ public void testGetNextDeparture() { @Test public void testGetDepartureData() { Fixture f = new Fixture(); - + EventsManager events = EventsUtils.createEventsManager(); OccupancyData occData = new OccupancyData(); OccupancyTracker tracker = new OccupancyTracker(occData, f.scenario, new DefaultRaptorInVehicleCostCalculator(), events, new SubpopulationScoringParameters(f.scenario)); diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/RaptorStopFinderTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/RaptorStopFinderTest.java index ff34ae992b9..9f712b2edaf 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/RaptorStopFinderTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/RaptorStopFinderTest.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; @@ -16,7 +35,7 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.router.DefaultRoutingRequest; @@ -43,8 +62,8 @@ public class RaptorStopFinderTest { - private Facility fromFac = new FakeFacility(new Coord(0, 0), Id.create("AA", Link.class)); // stop A - private Facility toFac = new FakeFacility(new Coord(100000, 0), Id.create("XX", Link.class)); // stop X + private final Facility fromFac = new FakeFacility(new Coord(0, 0), Id.create("AA", Link.class)); // stop A + private final Facility toFac = new FakeFacility(new Coord(100000, 0), Id.create("XX", Link.class)); // stop X /** Empty Initial Search Radius @@ -56,10 +75,10 @@ public class RaptorStopFinderTest { * * This functionality is tested for the two RaptorStopFinders: 1) DefaultStopFinder and 2) RandomAccessEgressModeRaptorStopFinder * For each RaptorStopFinder there is one test where StopFilterAttributes are not used to exlclude stops, and one test - * where StopFilterAttributes are used. + * where StopFilterAttributes are used. */ - - + + @Test public void testDefaultStopFinder_EmptyInitialSearchRadius() { /* General Radius includes no stops. Search_Extension_Radius is 0 @@ -88,9 +107,9 @@ public void testDefaultStopFinder_EmptyInitialSearchRadius() { List legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(this.fromFac, this.toFac, 7 * 3600, f0.dummyPerson)); Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - + } - + /* General Radius includes stop B. Search_Extension_Radius is 0. Expected: Stop Finder will only find stop B. Lines C, D, and E are set to very fast, so as to check that only stop B is included. @@ -215,9 +234,9 @@ public void testDefaultStopFinder_EmptyInitialSearchRadius_StopFilterAttributes( SwissRailRaptor raptor = new SwissRailRaptor.Builder(data, f0.scenario.getConfig()).with(stopFinder).build(); List legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(this.fromFac, this.toFac, 7 * 3600, f0.dummyPerson)); - + Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - + } /* General Radius includes stop B. Search_Extension_Radius is 0. @@ -405,9 +424,9 @@ public void testRandomAccessEgressModeRaptorStopFinder_EmptyInitialSearchRadius( List legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(this.fromFac, this.toFac, 7 * 3600, f0.dummyPerson)); Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - + } - + /* General Radius includes stop B. Search_Extension_Radius is 0. Expected: Stop Finder will only find stop B. Lines C, D, and E are set to very fast, so as to check that only stop B is included. @@ -535,7 +554,7 @@ public void testRandomAccessEgressModeRaptorStopFinder_EmptyInitialSearchRadius_ List legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(this.fromFac, this.toFac, 7 * 3600, f0.dummyPerson)); Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - + } /* General Radius includes stop B. Search_Extension_Radius is 0. @@ -709,7 +728,7 @@ Initial_Search_Radius includes B (not "walkAccessible") * * This functionality is tested for the two RaptorStopFinders: 1) DefaultStopFinder and 2) RandomAccessEgressModeRaptorStopFinder * For each RaptorStopFinder there is one test where StopFilterAttributes are not used to exlclude stops, and one test - * where StopFilterAttributes are used. + * where StopFilterAttributes are used. */ @Test public void testDefaultStopFinder_HalfFullInitialSearchRadius() { @@ -1213,7 +1232,7 @@ public void testRandomAccessEgressModeRaptorStopFinder_HalfFullInitialSearchRadi * * This functionality is tested for the two RaptorStopFinders: 1) DefaultStopFinder and 2) RandomAccessEgressModeRaptorStopFinder * For each RaptorStopFinder there is one test where StopFilterAttributes are not used to exlclude stops, and one test - * where StopFilterAttributes are used. + * where StopFilterAttributes are used. */ @Test public void testDefaultStopFinder_FullInitialSearchRadius() { @@ -1666,9 +1685,9 @@ public void testDefaultStopFinder_testMultipleModes() { routingModules.put("zoomer", new TeleportationRoutingModule("zoomer", f0.scenario, 1000., 1.)); - PlanCalcScoreConfigGroup.ModeParams modeParams = new PlanCalcScoreConfigGroup.ModeParams("zoomer"); + ScoringConfigGroup.ModeParams modeParams = new ScoringConfigGroup.ModeParams("zoomer"); modeParams.setMarginalUtilityOfTraveling(0.); - f0.scenario.getConfig().planCalcScore().addModeParams(modeParams); + f0.scenario.getConfig().scoring().addModeParams(modeParams); f0.srrConfig.setUseIntermodalAccessEgress(true); SwissRailRaptorConfigGroup.IntermodalAccessEgressParameterSet zoomerAccess = new SwissRailRaptorConfigGroup.IntermodalAccessEgressParameterSet(); @@ -1732,9 +1751,9 @@ public void testDefaultStopFinder_testMultipleModes() { routingModules.put("zoomer", new TeleportationRoutingModule("zoomer", f0.scenario, 1000., 1.)); - PlanCalcScoreConfigGroup.ModeParams modeParams = new PlanCalcScoreConfigGroup.ModeParams("zoomer"); + ScoringConfigGroup.ModeParams modeParams = new ScoringConfigGroup.ModeParams("zoomer"); modeParams.setMarginalUtilityOfTraveling(0.); - f0.scenario.getConfig().planCalcScore().addModeParams(modeParams); + f0.scenario.getConfig().scoring().addModeParams(modeParams); f0.srrConfig.setUseIntermodalAccessEgress(true); SwissRailRaptorConfigGroup.IntermodalAccessEgressParameterSet zoomerAccess = new SwissRailRaptorConfigGroup.IntermodalAccessEgressParameterSet(); diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtilsTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtilsTest.java index 89fb2dd8a4c..2a6ee7b9abc 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtilsTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtilsTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; @@ -68,4 +83,4 @@ public void testConfigLoading() { Assert.assertTrue(raptorParams2.getConfig().isUseIntermodalAccessEgress()); Assert.assertFalse(raptorParams2.getConfig().isUseModeMappingForPassengers()); } -} \ No newline at end of file +} diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCapacitiesTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCapacitiesTest.java index 2a836468cb4..a986cb26763 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCapacitiesTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCapacitiesTest.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorDataTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorDataTest.java index d00dae0f9f5..5a0a4711a2f 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorDataTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorDataTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.junit.Assert; @@ -82,4 +97,4 @@ public void testTransfersFromSchedule() { Assert.assertEquals("number of transfers should have stayed the same.", data2.transfers.length, data4.transfers.length); } -} \ No newline at end of file +} diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorInVehicleCostTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorInVehicleCostTest.java index 3ee20ba0de2..76b098fa73f 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorInVehicleCostTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorInVehicleCostTest.java @@ -1,3 +1,22 @@ +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import org.junit.Assert; diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorIntermodalTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorIntermodalTest.java index a171cf23f1c..973d16bb1f2 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorIntermodalTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorIntermodalTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; @@ -23,19 +38,16 @@ import org.matsim.api.core.v01.population.PopulationFactory; 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.routes.GenericRouteImpl; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; -import org.matsim.core.router.DefaultRoutingRequest; -import org.matsim.core.router.RoutingModule; -import org.matsim.core.router.RoutingRequest; -import org.matsim.core.router.TeleportationRoutingModule; -import org.matsim.core.router.TripRouter; +import org.matsim.core.router.*; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.facilities.Facility; import org.matsim.pt.PtConstants; +import org.matsim.pt.transitSchedule.TransitScheduleUtils; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; @@ -43,7 +55,7 @@ import org.matsim.pt.transitSchedule.api.TransitSchedule; import org.matsim.pt.transitSchedule.api.TransitScheduleFactory; import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.utils.objectattributes.attributable.Attributes; +import org.matsim.testcases.MatsimTestUtils; import org.matsim.utils.objectattributes.attributable.AttributesImpl; import java.util.ArrayList; @@ -61,9 +73,9 @@ public class SwissRailRaptorIntermodalTest { public void testIntermodalTrip() { IntermodalFixture f = new IntermodalFixture(); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); Map routingModules = new HashMap<>(); routingModules.put(TransportMode.walk, @@ -135,7 +147,7 @@ public void testIntermodalTrip_TripRouterIntegration() { TripRouter.Builder tripRouterBuilder = new TripRouter.Builder(f.config) .setRoutingModule(TransportMode.walk, walkRoutingModule) .setRoutingModule(TransportMode.bike, bikeRoutingModule); - + TripRouter tripRouter = tripRouterBuilder.build(); f.srrConfig.setUseIntermodalAccessEgress(true); @@ -153,9 +165,9 @@ public void testIntermodalTrip_TripRouterIntegration() { bikeAccess.setStopFilterValue("true"); f.srrConfig.addIntermodalAccessEgress(bikeAccess); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); SwissRailRaptorData data = SwissRailRaptorData.create(f.scenario.getTransitSchedule(), null, RaptorUtils.createStaticConfig(f.config), f.scenario.getNetwork(), null); DefaultRaptorStopFinder stopFinder = new DefaultRaptorStopFinder(new DefaultRaptorIntermodalAccessEgress(), routingModules); @@ -206,9 +218,9 @@ public void testIntermodalTrip_TripRouterIntegration() { public void testIntermodalTrip_walkOnlyNoSubpop() { IntermodalFixture f = new IntermodalFixture(); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(-8.0); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); Map routingModules = new HashMap<>(); routingModules.put(TransportMode.walk, @@ -258,9 +270,9 @@ public void testIntermodalTrip_walkOnlyNoSubpop() { public void testIntermodalTrip_withoutPt() { IntermodalFixture f = new IntermodalFixture(); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); Map routingModules = new HashMap<>(); routingModules.put(TransportMode.walk, @@ -289,18 +301,18 @@ public void testIntermodalTrip_withoutPt() { Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); } - + @Test public void testDirectWalkFactor() { IntermodalFixture f = new IntermodalFixture(); - f.config.planCalcScore().setPerforming_utils_hr(6.0); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + f.config.scoring().setPerforming_utils_hr(6.0); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(walk); - PlanCalcScoreConfigGroup.ModeParams bike = new PlanCalcScoreConfigGroup.ModeParams("bike"); + f.config.scoring().addModeParams(walk); + ScoringConfigGroup.ModeParams bike = new ScoringConfigGroup.ModeParams("bike"); bike.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(bike); + f.config.scoring().addModeParams(bike); Map routingModules = new HashMap<>(); routingModules.put(TransportMode.walk, @@ -309,7 +321,6 @@ public void testDirectWalkFactor() { new TeleportationRoutingModule(TransportMode.walk, f.scenario, 1.1, 1.3)); routingModules.put(TransportMode.bike, new TeleportationRoutingModule(TransportMode.bike, f.scenario, 3.0, 1.4)); - f.srrConfig.setUseIntermodalAccessEgress(true); IntermodalAccessEgressParameterSet walkAccess = new IntermodalAccessEgressParameterSet(); walkAccess.setMode(TransportMode.walk); @@ -326,10 +337,10 @@ public void testDirectWalkFactor() { bikeAccess.setLinkIdAttribute("accessLinkId_bike"); bikeAccess.setStopFilterValue("true"); f.srrConfig.addIntermodalAccessEgress(bikeAccess); - + f.srrConfig.setIntermodalLegOnlyHandling(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.avoid); Facility fromFac = new FakeFacility(new Coord(9000, 15000), Id.create("from", Link.class)); Facility toFac = new FakeFacility(new Coord(10500, 15000), Id.create("to", Link.class)); - + // direct walk factor off f.config.transitRouter().setDirectWalkFactor(1.0); SwissRailRaptorData data = SwissRailRaptorData.create(f.scenario.getTransitSchedule(), null, RaptorUtils.createStaticConfig(f.config), f.scenario.getNetwork(), null); @@ -346,7 +357,7 @@ public void testDirectWalkFactor() { Assert.assertEquals(TransportMode.walk, leg.getMode()); Assert.assertEquals(Id.create("from", Link.class), leg.getRoute().getStartLinkId()); Assert.assertEquals(Id.create("to", Link.class), leg.getRoute().getEndLinkId()); - + // direct walk factor on f.config.transitRouter().setDirectWalkFactor(Double.POSITIVE_INFINITY); data = SwissRailRaptorData.create(f.scenario.getTransitSchedule(), null, RaptorUtils.createStaticConfig(f.config), f.scenario.getNetwork(), null); @@ -380,20 +391,20 @@ public void testDirectWalkFactor() { Assert.assertEquals(Id.create("bike_3", Link.class), leg.getRoute().getStartLinkId()); Assert.assertEquals(Id.create("to", Link.class), leg.getRoute().getEndLinkId()); } - + @Test public void testAccessEgressModeFasterThanPt() { IntermodalFixture f = new IntermodalFixture(); - /* - * setDirectWalkFactor(Double.POSITIVE_INFINITY) leads to the case where in SwissRailRaptor.calcRoute() both the found - * route and the direct walk have cost infinity, so if we would not check for the found route to have at least one + /* + * setDirectWalkFactor(Double.POSITIVE_INFINITY) leads to the case where in SwissRailRaptor.calcRoute() both the found + * route and the direct walk have cost infinity, so if we would not check for the found route to have at least one * RoutePart, the router would return 0 legs. */ f.config.transitRouter().setDirectWalkFactor(Double.POSITIVE_INFINITY); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); Map routingModules = new HashMap<>(); routingModules.put(TransportMode.walk, @@ -423,16 +434,58 @@ public void testAccessEgressModeFasterThanPt() { Facility fromFac = new FakeFacility(new Coord(10000, 10500), Id.create("from", Link.class)); Facility toFac = new FakeFacility(new Coord(10500, 10500), Id.create("to", Link.class)); - List legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac, toFac, 7*3600, f.dummyPerson)); - - /* - * Going by access/egress mode bike from "fromFac" to stop 3 (which is bikeAccessible) and from there by bike - * to the destination is faster than any alternative including pt (because bike is extremely fast in this test). - * Therefore, the raptor returns as fastest path a v-shaped bike trip from the fromFac via stop 3 to the toFac, - * alternatives including pt are not found. This should be caught by SwissRailRaptor and it should return null. - */ - Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - } + //both directly 10000 metres from stop[3] + Facility fromFac2 = new FakeFacility(new Coord(10500, 20000), Id.create("from2", Link.class)); + Facility toFac2 = new FakeFacility(new Coord(10500, 0), Id.create("to2", Link.class)); + + + /* + * Going by access/egress mode bike from "fromFac" to stop 3 (which is bikeAccessible) and from there by bike + * to the destination is faster than any alternative including pt (because bike is extremely fast in this test). + * Therefore, the raptor returns as fastest path a v-shaped bike trip from the fromFac via stop 3 to the toFac, + * alternatives including pt are not found. Depending on the setting of intermodal legs, different outcomes should be expected. + */ + + //returnNull + data.config.setIntermodalLegOnlyHandling(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.returnNull); + List legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac, toFac, 7*3600, f.dummyPerson)); + Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); + + legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac2, toFac2, 7*3600, f.dummyPerson)); + Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); + + //forbid + data.config.setIntermodalLegOnlyHandling(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.forbid); + legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac, toFac, 7*3600, f.dummyPerson)); + Assert.assertNotNull("The router should find a pt route and not return null, but did return null", legs); + Assert.assertTrue( legs.stream().filter(Leg.class::isInstance).anyMatch(planElement -> ((Leg) planElement).getMode().equals(TransportMode.pt))); + + legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac2, toFac2, 7*3600, f.dummyPerson)); + Assert.assertNull("The router should not find a pt route and return null, but did return something else", legs); + + //avoid + data.config.setIntermodalLegOnlyHandling(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.avoid); + legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac, toFac, 7*3600, f.dummyPerson)); + Assert.assertNotNull("The router should find a pt route and not return null, but did return null", legs); + Assert.assertTrue( legs.stream().filter(Leg.class::isInstance).anyMatch(planElement -> ((Leg) planElement).getMode().equals(TransportMode.pt))); + + legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac2, toFac2, 7*3600, f.dummyPerson)); + Assert.assertNotNull("The router should find a pt route and not return null, but did return null", legs); + Assert.assertFalse( legs.stream().filter(Leg.class::isInstance).anyMatch(planElement -> ((Leg) planElement).getMode().equals(TransportMode.pt))); + + //allow + data.config.setIntermodalLegOnlyHandling(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.allow); + legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac, toFac, 7*3600, f.dummyPerson)); + Assert.assertFalse( legs.stream().filter(Leg.class::isInstance).anyMatch(planElement -> ((Leg) planElement).getMode().equals(TransportMode.pt))); + Assert.assertNotNull("The router should find a pt route and not return null, but did return something else.", legs); + + legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac2, toFac2, 7*3600, f.dummyPerson)); + Assert.assertNotNull("The router should find a pt route and not return null, but did return null", legs); + Assert.assertFalse( legs.stream().filter(Leg.class::isInstance).anyMatch(planElement -> ((Leg) planElement).getMode().equals(TransportMode.pt))); + + } + + @Test public void testIntermodalTrip_competingAccess() { @@ -446,11 +499,11 @@ public void testIntermodalTrip_competingAccess() { // we need to set special values for walk and bike as the defaults are the same for walk, bike and waiting // which would result in all options having the same cost in the end. - f.config.planCalcScore().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(-8); + f.config.scoring().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(-8); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(-7); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); f.srrConfig.setUseIntermodalAccessEgress(true); IntermodalAccessEgressParameterSet walkAccess = new IntermodalAccessEgressParameterSet(); @@ -541,11 +594,11 @@ public void testIntermodalTrip_RandomAccessEgressModeRaptorStopFinder() { // we need to set special values for walk and bike as the defaults are the same for walk, bike and waiting // which would result in all options having the same cost in the end. - f.config.planCalcScore().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(-8); + f.config.scoring().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(-8); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(-7); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); f.srrConfig.setUseIntermodalAccessEgress(true); IntermodalAccessEgressParameterSet walkAccess = new IntermodalAccessEgressParameterSet(); @@ -623,7 +676,7 @@ else if ((((Leg)(legs.get(0))).getMode().equals(TransportMode.bike)) && (((Leg)l Assert.assertTrue(numWalkBike > 0); Assert.assertTrue(numBikeWalk > 0); Assert.assertTrue(numBikeBike > 0); - Assert.assertTrue(numOther == 0); + Assert.assertEquals(0, numOther); } } @@ -844,8 +897,8 @@ public void testIntermodalTrip_accessModeRouterReturnsNull() { Assert.assertEquals(TransportMode.walk, legAccess.getMode()); Assert.assertEquals("AA", legAccess.getRoute().getStartLinkId().toString()); Assert.assertEquals("to", legAccess.getRoute().getEndLinkId().toString()); - - + + // Part 2: Change bike router to return null. f.routingModules.remove(TransportMode.bike); f.routingModules.put(TransportMode.bike, @@ -855,7 +908,7 @@ public void testIntermodalTrip_accessModeRouterReturnsNull() { public List calcRoute(RoutingRequest request) { return null; } - + }); SwissRailRaptorData data2 = SwissRailRaptorData.create(f.scenario.getTransitSchedule(), null, RaptorUtils.createStaticConfig(f.config), f.scenario.getNetwork(), null); @@ -863,25 +916,25 @@ public List calcRoute(RoutingRequest request) { SwissRailRaptor raptor2 = new SwissRailRaptor.Builder(data2, f.scenario.getConfig()).with(stopFinder2).build(); List legs2 = raptor2.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac, toFac, 8 * 3600 - 900, f.dummyPerson)); - - Assert.assertNull("The router should not find a route and return null, but did return something else.", legs2); + + Assert.assertNull("The router should not find a route and return null, but did return something else.", legs2); } /** - * + * * The agent has a super-fast bike. So in theory it is faster to travel * from stop_3 to the destination. However, with the introduced trip share * constraint it will still take the closest stop accessible by the bike. - * If this constraint is not used the agent will take pt_3 stop as an + * If this constraint is not used the agent will take pt_3 stop as an * access stop to his final destination. - * + * */ @Test public void testIntermodalTrip_tripLengthShare() { IntermodalFixture f = new IntermodalFixture(); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); Map routingModules = new HashMap<>(); routingModules.put(TransportMode.walk, @@ -941,7 +994,7 @@ public void testIntermodalTrip_tripLengthShare() { Assert.assertEquals(Id.create("bike_5", Link.class), leg.getRoute().getStartLinkId()); Assert.assertEquals(Id.create("to", Link.class), leg.getRoute().getEndLinkId()); } - + @Test public void testIntermodalTrip_activityInteraction() { double bikeInteractionDuration = 1.0; @@ -949,38 +1002,38 @@ public void testIntermodalTrip_activityInteraction() { IntermodalFixture f = new IntermodalFixture(); final Scenario scenario = ScenarioUtils.createScenario( ConfigUtils.createConfig() ); PopulationFactory populationFactory = scenario.getPopulation().getFactory(); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); Map routingModules = new HashMap<>(); routingModules.put(TransportMode.walk, new TeleportationRoutingModule(TransportMode.walk, f.scenario, walkSpeed, 1.3)); - - + + routingModules.put(TransportMode.bike, new RoutingModule() { - + @Override public List calcRoute(RoutingRequest request) { final Facility fromFacility = request.getFromFacility(); final Facility toFacility = request.getToFacility(); final double departureTime = request.getDepartureTime(); - + Coord bikeCoord = CoordUtils.createCoord(9500, 10000); - + List allElements = new LinkedList<>(); // Create walk-out-of-building stage - + Leg leg = populationFactory.createLeg("walk"); leg.setDepartureTime(departureTime); double walkDistance = CoordUtils.calcEuclideanDistance(fromFacility.getCoord(), bikeCoord); - + leg.setTravelTime(walkDistance/walkSpeed); - + leg.setRoute(new GenericRouteImpl(fromFacility.getLinkId(), Id.createLinkId("pt_1"))); allElements.add(leg); - + // Create activity where the bike is pickedup Activity activity = populationFactory.createActivityFromLinkId("bike interaction", Id.createLinkId("pt_1")); activity.setStartTime(departureTime + walkDistance/walkSpeed); @@ -989,7 +1042,7 @@ public List calcRoute(RoutingRequest request) { // Route bike stage double distance = CoordUtils.calcEuclideanDistance(bikeCoord, toFacility.getCoord()); - + Leg bikeLeg = populationFactory.createLeg("bike"); bikeLeg.setDepartureTime(departureTime + bikeInteractionDuration + walkDistance/walkSpeed); bikeLeg.setTravelTime(distance/60.0); @@ -998,7 +1051,7 @@ public List calcRoute(RoutingRequest request) { return allElements; } }); - + f.srrConfig.setUseIntermodalAccessEgress(true); IntermodalAccessEgressParameterSet walkAccess = new IntermodalAccessEgressParameterSet(); @@ -1056,13 +1109,13 @@ public List calcRoute(RoutingRequest request) { Assert.assertEquals(Id.create("pt_5", Link.class), leg.getRoute().getStartLinkId()); Assert.assertEquals(Id.create("to", Link.class), leg.getRoute().getEndLinkId()); } - + /** - * + * * This test tests the intermodal router when access modes - * have interaction activities and it tests the inclusion of the + * have interaction activities and it tests the inclusion of the * pt interaction activities by the SwissRailRaptorRoutingModule - */ + */ @Test public void testIntermodalTrip_activityInteractionAdd() { double bikeInteractionDuration = 1.0; @@ -1070,38 +1123,38 @@ public void testIntermodalTrip_activityInteractionAdd() { IntermodalFixture f = new IntermodalFixture(); final Scenario scenario = ScenarioUtils.createScenario( ConfigUtils.createConfig() ); PopulationFactory populationFactory = scenario.getPopulation().getFactory(); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); Map routingModules = new HashMap<>(); routingModules.put(TransportMode.walk, new TeleportationRoutingModule(TransportMode.walk, f.scenario, walkSpeed, 1.3)); - - + + routingModules.put(TransportMode.bike, new RoutingModule() { - + @Override public List calcRoute(RoutingRequest request) { final Facility fromFacility = request.getFromFacility(); final Facility toFacility = request.getToFacility(); final double departureTime = request.getDepartureTime(); - + Coord bikeCoord = CoordUtils.createCoord(9500, 10000); - + List allElements = new LinkedList<>(); // Create walk-out-of-building stage - + Leg leg = populationFactory.createLeg("walk"); leg.setDepartureTime(departureTime); double walkDistance = CoordUtils.calcEuclideanDistance(fromFacility.getCoord(), bikeCoord); - + leg.setTravelTime(walkDistance/walkSpeed); - + leg.setRoute(new GenericRouteImpl(fromFacility.getLinkId(), Id.createLinkId("pt_1"))); allElements.add(leg); - + // Create activity where the bike is pickedup Activity activity = populationFactory.createActivityFromLinkId("bike interaction", Id.createLinkId("pt_1")); activity.setStartTime(departureTime + walkDistance/walkSpeed); @@ -1110,7 +1163,7 @@ public List calcRoute(RoutingRequest request) { // Route bike stage double distance = CoordUtils.calcEuclideanDistance(bikeCoord, toFacility.getCoord()); - + Leg bikeLeg = populationFactory.createLeg("bike"); bikeLeg.setDepartureTime(departureTime + bikeInteractionDuration + walkDistance/walkSpeed); bikeLeg.setTravelTime(distance/60.0); @@ -1119,7 +1172,7 @@ public List calcRoute(RoutingRequest request) { return allElements; } }); - + f.srrConfig.setUseIntermodalAccessEgress(true); IntermodalAccessEgressParameterSet walkAccess = new IntermodalAccessEgressParameterSet(); @@ -1183,8 +1236,71 @@ public List calcRoute(RoutingRequest request) { Assert.assertEquals(Id.create("pt_5", Link.class), leg.getRoute().getStartLinkId()); Assert.assertEquals(Id.create("to", Link.class), leg.getRoute().getEndLinkId()); } - - + + @Test + public void testIntermodalTripWithAccessAndEgressTimesAtStops() { + IntermodalFixture f = new IntermodalFixture(); + f.scenario.getTransitSchedule().getFacilities().values() + .forEach(stopFacility -> TransitScheduleUtils.setSymmetricStopAccessEgressTime(stopFacility,120.0)); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); + walk.setMarginalUtilityOfTraveling(0.0); + f.config.scoring().addModeParams(walk); + + Map routingModules = new HashMap<>(); + routingModules.put(TransportMode.walk, + new TeleportationRoutingModule(TransportMode.walk, f.scenario, 1.1, 1.3)); + routingModules.put(TransportMode.bike, + new TeleportationRoutingModule(TransportMode.bike, f.scenario, 3, 1.4)); + + f.srrConfig.setUseIntermodalAccessEgress(true); + IntermodalAccessEgressParameterSet walkAccess = new IntermodalAccessEgressParameterSet(); + walkAccess.setMode(TransportMode.walk); + walkAccess.setMaxRadius(1000); + walkAccess.setInitialSearchRadius(1000); + f.srrConfig.addIntermodalAccessEgress(walkAccess); + IntermodalAccessEgressParameterSet bikeAccess = new IntermodalAccessEgressParameterSet(); + bikeAccess.setMode(TransportMode.bike); + bikeAccess.setMaxRadius(1500); + bikeAccess.setInitialSearchRadius(1500); + bikeAccess.setStopFilterAttribute("bikeAccessible"); + bikeAccess.setLinkIdAttribute("accessLinkId_bike"); + bikeAccess.setStopFilterValue("true"); + f.srrConfig.addIntermodalAccessEgress(bikeAccess); + + SwissRailRaptorData data = SwissRailRaptorData.create(f.scenario.getTransitSchedule(), null, RaptorUtils.createStaticConfig(f.config), f.scenario.getNetwork(), null); + DefaultRaptorStopFinder stopFinder = new DefaultRaptorStopFinder(new DefaultRaptorIntermodalAccessEgress(), routingModules); + SwissRailRaptor raptor = new SwissRailRaptor.Builder(data, f.scenario.getConfig()).with(stopFinder).build(); + + Facility fromFac = new FakeFacility(new Coord(10000, 10500), Id.create("from", Link.class)); + Facility toFac = new FakeFacility(new Coord(50000, 10500), Id.create("to", Link.class)); + + List legs = raptor.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFac, toFac, 7*3600, f.dummyPerson)); + for (PlanElement leg : legs) { + System.out.println(leg); + } + + Assert.assertEquals("wrong number of legs.", 5, legs.size()); + Leg leg = (Leg) legs.get(1); + Assert.assertEquals(TransportMode.walk, leg.getMode()); + Assert.assertEquals(Id.create("pt_2", Link.class), leg.getRoute().getStartLinkId()); + Assert.assertEquals(Id.create("pt_2", Link.class), leg.getRoute().getEndLinkId()); + Assert.assertEquals(120.0,leg.getTravelTime().seconds(), MatsimTestUtils.EPSILON); + leg = (Leg) legs.get(2); + Assert.assertEquals(TransportMode.pt, leg.getMode()); + Assert.assertEquals(Id.create("pt_2", Link.class), leg.getRoute().getStartLinkId()); + Assert.assertEquals(Id.create("pt_5", Link.class), leg.getRoute().getEndLinkId()); + leg = (Leg) legs.get(3); + Assert.assertEquals(TransportMode.walk, leg.getMode()); + Assert.assertEquals(Id.create("pt_5", Link.class), leg.getRoute().getStartLinkId()); + Assert.assertEquals(Id.create("bike_5", Link.class), leg.getRoute().getEndLinkId()); + Assert.assertEquals(120.0,leg.getTravelTime().seconds(), MatsimTestUtils.EPSILON); + leg = (Leg) legs.get(4); + Assert.assertEquals(TransportMode.bike, leg.getMode()); + Assert.assertEquals(Id.create("bike_5", Link.class), leg.getRoute().getStartLinkId()); + Assert.assertEquals(Id.create("to", Link.class), leg.getRoute().getEndLinkId()); + } + + /* for test of intermodal routing requiring transfers at the beginning or end of the pt trip, * the normal IntermodalFixture does not work, so create a special mini scenario here. @@ -1368,15 +1484,15 @@ public IntermodalTransferFixture() { // we need to set special values for walk and bike as the defaults are the same for walk, bike and waiting // which would result in all options having the same cost in the end. - this.config.planCalcScore().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(-8); + this.config.scoring().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(-8); this.config.transitRouter().setMaxBeelineWalkConnectionDistance(150); - + /* * Prior to non_network_walk the utilities of access_walk and egress_walk were set to 0 here. * non_network_walk replaced access_walk and egress_walk, so one might assume that now egress_walk should * have marginalUtilityOfTraveling = 0. - * + * * However, non_network_walk also replaces walk, so the alternative access leg by *_walk without any bike * leg is calculated based on marginalUtilityOfTraveling of non_network_walk. Setting * marginalUtilityOfTraveling = 0 obviously makes that alternative more attractive than any option with bike @@ -1385,13 +1501,13 @@ public IntermodalTransferFixture() { * bike (and access / egress transfer) are rather short and thereby have little influence on the total cost. * Furthermore, this is additional cost for the path including bike, so we are on the safe side with that * change. - gleich aug'19 - * - * Instead of TransportMode.non_network_walk we are now (after the introduction of routing mode) using + * + * Instead of TransportMode.non_network_walk we are now (after the introduction of routing mode) using * TransportMode.walk for access and egress to pt. */ - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(-7); - this.config.planCalcScore().addModeParams(walk); + this.config.scoring().addModeParams(walk); this.srrConfig.setUseIntermodalAccessEgress(true); IntermodalAccessEgressParameterSet walkAccess = new IntermodalAccessEgressParameterSet(); diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorModuleTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorModuleTest.java index c2a85b66d35..a5fc49cfefe 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorModuleTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorModuleTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import java.util.ArrayList; @@ -26,8 +41,8 @@ import org.matsim.api.core.v01.population.PopulationFactory; 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.StrategySettings; +import org.matsim.core.config.groups.ScoringConfigGroup; +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; @@ -78,10 +93,10 @@ public void setUp() { @Test public void testInitialization() { Config config = ConfigUtils.createConfig(); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); config.transit().setUseTransit(true); Scenario scenario = ScenarioUtils.createScenario(config); Controler controler = new Controler(scenario); @@ -141,23 +156,23 @@ public void testIntermodalIntegration() { // prepare scoring Config config = f.config; - PlanCalcScoreConfigGroup.ActivityParams homeScoring = new PlanCalcScoreConfigGroup.ActivityParams("home"); + ScoringConfigGroup.ActivityParams homeScoring = new ScoringConfigGroup.ActivityParams("home"); homeScoring.setTypicalDuration(16*3600); - f.config.planCalcScore().addActivityParams(homeScoring); - PlanCalcScoreConfigGroup.ActivityParams workScoring = new PlanCalcScoreConfigGroup.ActivityParams("work"); + f.config.scoring().addActivityParams(homeScoring); + ScoringConfigGroup.ActivityParams workScoring = new ScoringConfigGroup.ActivityParams("work"); workScoring.setTypicalDuration(8*3600); - f.config.planCalcScore().addActivityParams(workScoring); + f.config.scoring().addActivityParams(workScoring); - PlanCalcScoreConfigGroup.ModeParams walk = new PlanCalcScoreConfigGroup.ModeParams(TransportMode.walk); + ScoringConfigGroup.ModeParams walk = new ScoringConfigGroup.ModeParams(TransportMode.walk); walk.setMarginalUtilityOfTraveling(0.0); - f.config.planCalcScore().addModeParams(walk); + f.config.scoring().addModeParams(walk); // prepare rest of config - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); config.qsim().setEndTime(10*3600); config.transit().setUseTransit(true); Controler controler = new Controler(f.scenario); @@ -231,7 +246,7 @@ public void install() { // :-( :-( kai, mar'20) } - + /** * Test update of SwissRailRaptorData after TransitScheduleChangedEvent */ @@ -252,29 +267,29 @@ public void testTransitScheduleUpdate() { plan.addActivity(homeAct); plan.addLeg(pf.createLeg(TransportMode.pt)); plan.addActivity(pf.createActivityFromCoord("work", new Coord(24010, 10000))); - + // prepare scoring Config config = f.config; - PlanCalcScoreConfigGroup.ActivityParams homeScoring = new PlanCalcScoreConfigGroup.ActivityParams("home"); + ScoringConfigGroup.ActivityParams homeScoring = new ScoringConfigGroup.ActivityParams("home"); homeScoring.setTypicalDuration(16*3600); - f.config.planCalcScore().addActivityParams(homeScoring); - PlanCalcScoreConfigGroup.ActivityParams workScoring = new PlanCalcScoreConfigGroup.ActivityParams("work"); + f.config.scoring().addActivityParams(homeScoring); + ScoringConfigGroup.ActivityParams workScoring = new ScoringConfigGroup.ActivityParams("work"); workScoring.setTypicalDuration(8*3600); - f.config.planCalcScore().addActivityParams(workScoring); + f.config.scoring().addActivityParams(workScoring); - f.config.planCalcScore().getOrCreateModeParams(TransportMode.walk).setMarginalUtilityOfTraveling(0.0); + f.config.scoring().getOrCreateModeParams(TransportMode.walk).setMarginalUtilityOfTraveling(0.0); StrategySettings reRoute = new StrategySettings(); reRoute.setStrategyName("ReRoute"); reRoute.setWeight(1.0); - config.strategy().addStrategySettings(reRoute); - config.strategy().setMaxAgentPlanMemorySize(1); + config.replanning().addStrategySettings(reRoute); + config.replanning().setMaxAgentPlanMemorySize(1); // prepare rest of config - config.controler().setLastIteration(1); - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); + config.controller().setLastIteration(1); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); config.qsim().setEndTime(10*3600); config.transit().setUseTransit(true); Controler controler = new Controler(f.scenario); @@ -288,12 +303,12 @@ public void install() { }); controler.run(); - + // test that swiss rail raptor was used TripRouter tripRouter = controler.getInjector().getInstance(TripRouter.class); RoutingModule module = tripRouter.getRoutingModule(TransportMode.pt); Assert.assertTrue(module instanceof SwissRailRaptorRoutingModule); - + // Check routed plan List planElements = p1.getSelectedPlan().getPlanElements(); for (PlanElement pe : planElements) { @@ -317,13 +332,13 @@ public void install() { Assert.assertEquals(TransportMode.walk, ((Leg) planElements.get(1)).getMode()); Assert.assertEquals(TransportMode.pt, ((Leg) planElements.get(3)).getMode()); Assert.assertEquals(TransportMode.walk, ((Leg) planElements.get(5)).getMode()); - + // Check route: should return one of the added lines although the removed green line would be faster Leg ptLeg = (Leg) planElements.get(3); TransitPassengerRoute ptRoute = (TransitPassengerRoute) ptLeg.getRoute(); - Assert.assertEquals(Id.create("AddedLine" + 1, TransitLine.class), ptRoute.getLineId()); + Assert.assertEquals(Id.create("AddedLine" + 1, TransitLine.class), ptRoute.getLineId()); } - + /** * Test individual scoring parameters for agents */ @@ -333,21 +348,21 @@ public void testRaptorParametersForPerson() { srrConfig.setScoringParameters(ch.sbb.matsim.config.SwissRailRaptorConfigGroup.ScoringParameters.Individual); Config config = ConfigUtils.createConfig(srrConfig); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); config.transit().setUseTransit(true); - config.planCalcScore().getOrCreateScoringParameters("default").setPerforming_utils_hr(3600.0 * 50.0); - config.planCalcScore().getOrCreateScoringParameters("sub").setPerforming_utils_hr(3600.0 * 50.0); + config.scoring().getOrCreateScoringParameters("default").setPerforming_utils_hr(3600.0 * 50.0); + config.scoring().getOrCreateScoringParameters("sub").setPerforming_utils_hr(3600.0 * 50.0); for (String mode : Arrays.asList("car", "walk", "pt")) { - config.planCalcScore().getOrCreateScoringParameters("default").getOrCreateModeParams(mode); - config.planCalcScore().getOrCreateScoringParameters("sub").getOrCreateModeParams(mode); + config.scoring().getOrCreateScoringParameters("default").getOrCreateModeParams(mode); + config.scoring().getOrCreateScoringParameters("sub").getOrCreateModeParams(mode); } - config.planCalcScore().getOrCreateScoringParameters("default").setMarginalUtlOfWaitingPt_utils_hr(-3600.0 * 30.0); - config.planCalcScore().getOrCreateScoringParameters("sub").setMarginalUtlOfWaitingPt_utils_hr(-3600.0 * 10.0); + config.scoring().getOrCreateScoringParameters("default").setMarginalUtlOfWaitingPt_utils_hr(-3600.0 * 30.0); + config.scoring().getOrCreateScoringParameters("sub").setMarginalUtlOfWaitingPt_utils_hr(-3600.0 * 10.0); Scenario scenario = ScenarioUtils.createScenario(config); @@ -431,5 +446,5 @@ private void removeGreenLineAndStop(ControlerEvent event) { } } - + } diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTest.java index 08b16d83972..e24bf036cc6 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; @@ -21,8 +36,8 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.router.DefaultRoutingModules; @@ -37,6 +52,7 @@ import org.matsim.facilities.ActivityFacility; import org.matsim.pt.router.TransitRouter; import org.matsim.pt.routes.TransitPassengerRoute; +import org.matsim.pt.transitSchedule.TransitScheduleUtils; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; @@ -153,6 +169,28 @@ public void testWalkDurations() { assertEquals(Math.ceil(expectedEgressWalkTime), ((Leg)legs.get(2)).getTravelTime().seconds(), MatsimTestUtils.EPSILON); } + + @Test + public void testStationAccessEgressTimes() { + Fixture f = new Fixture(); + f.init(); + RaptorParameters raptorParams = RaptorUtils.createParameters(f.config); + f.schedule.getFacilities().values().forEach(facility-> TransitScheduleUtils.setSymmetricStopAccessEgressTime(facility,120.0)); + TransitRouter router = createTransitRouter(f.schedule, f.config, f.network); + Coord fromCoord = new Coord(3800, 5100); + Coord toCoord = new Coord(16100, 5050); + List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 5.0*3600, null)); + assertEquals(3, legs.size()); + assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); + assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); + assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); + + double expectedAccessWalkTime = 120.0 + CoordUtils.calcEuclideanDistance(f.schedule.getFacilities().get(Id.create("0", TransitStopFacility.class)).getCoord(), fromCoord) / raptorParams.getBeelineWalkSpeed(); + assertEquals(Math.ceil(expectedAccessWalkTime), ((Leg)legs.get(0)).getTravelTime().seconds(), MatsimTestUtils.EPSILON); + double expectedEgressWalkTime = 120.0 + CoordUtils.calcEuclideanDistance(f.schedule.getFacilities().get(Id.create("6", TransitStopFacility.class)).getCoord(), toCoord) / raptorParams.getBeelineWalkSpeed(); + assertEquals(Math.ceil(expectedEgressWalkTime), ((Leg)legs.get(2)).getTravelTime().seconds(), MatsimTestUtils.EPSILON); + } + @Test public void testWalkDurations_range() { Fixture f = new Fixture(); @@ -202,7 +240,10 @@ public void testFromToSameStop() { public void testDirectWalkCheaper() { Fixture f = new Fixture(); f.init(); + SwissRailRaptorConfigGroup srrConfig = ConfigUtils.addOrGetModule(f.config,SwissRailRaptorConfigGroup.class); + srrConfig.setIntermodalLegOnlyHandling(SwissRailRaptorConfigGroup.IntermodalLegOnlyHandling.avoid); RaptorParameters raptorParams = RaptorUtils.createParameters(f.config); + TransitRouter router = createTransitRouter(f.schedule, f.config, f.network); Coord fromCoord = new Coord(4000, 3000); Coord toCoord = new Coord(8000, 3000); @@ -357,7 +398,7 @@ public void testTransferWeights() { */ Fixture f = new Fixture(); f.init(); - f.config.planCalcScore().setUtilityOfLineSwitch(0); + f.config.scoring().setUtilityOfLineSwitch(0); RaptorParameters raptorParams = RaptorUtils.createParameters(f.config); TransitRouter router = createTransitRouter(f.schedule, f.config, f.network); List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord(11900, 5100)), new FakeFacility(new Coord(24100, 4950)), 6.0*3600 - 5.0*60, null)); @@ -372,7 +413,7 @@ public void testTransferWeights() { Config config = ConfigUtils.createConfig(); double transferUtility = 300.0 * raptorParams.getMarginalUtilityOfTravelTime_utl_s(TransportMode.pt); // corresponds to 5 minutes transit travel time - config.planCalcScore().setUtilityOfLineSwitch(transferUtility); + config.scoring().setUtilityOfLineSwitch(transferUtility); raptorParams = RaptorUtils.createParameters(config); Assert.assertEquals(-transferUtility, raptorParams.getTransferPenaltyFixCostPerTransfer(), 0.0); router = createTransitRouter(f.schedule, config, f.network); @@ -396,7 +437,7 @@ public void testTransferTime() { */ Fixture f = new Fixture(); f.init(); - f.config.planCalcScore().setUtilityOfLineSwitch(0); + f.config.scoring().setUtilityOfLineSwitch(0); f.config.transitRouter().setAdditionalTransferTime(0); TransitRouter router = createTransitRouter(f.schedule, f.config, f.network); List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord(11900, 5100)), new FakeFacility(new Coord(24100, 4950)), 6.0*3600 - 5.0*60, null)); @@ -511,7 +552,7 @@ public void testLongTransferTime_withTransitRouterWrapper() { Assert.assertEquals(1895.0, legDuration, 0.0); RoutingModule walkRoutingModule = DefaultRoutingModules.createTeleportationRouter(TransportMode.transit_walk, f.scenario, - f.config.plansCalcRoute().getModeRoutingParams().get(TransportMode.walk)); + f.config.routing().getModeRoutingParams().get(TransportMode.walk)); TransitRouterWrapper wrapper = new TransitRouterWrapper( router, @@ -549,7 +590,7 @@ public void testLongTransferTime_withTransitRouterWrapper() { Assert.assertEquals(5500.0, legDuration, 0.0); RoutingModule walkRoutingModule = DefaultRoutingModules.createTeleportationRouter(TransportMode.transit_walk, f.scenario, - f.config.plansCalcRoute().getModeRoutingParams().get(TransportMode.walk)); + f.config.routing().getModeRoutingParams().get(TransportMode.walk)); TransitRouterWrapper wrapper = new TransitRouterWrapper( router, @@ -578,7 +619,7 @@ public void testLongTransferTime_withTransitRouterWrapper() { Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); RoutingModule walkRoutingModule = DefaultRoutingModules.createTeleportationRouter(TransportMode.transit_walk, f.scenario, - f.config.plansCalcRoute().getModeRoutingParams().get(TransportMode.walk)); + f.config.routing().getModeRoutingParams().get(TransportMode.walk)); TransitRouterWrapper routingModule = new TransitRouterWrapper( router, @@ -595,15 +636,13 @@ public void testLongTransferTime_withTransitRouterWrapper() { private static double calcTripDuration(List planElements) { double duration = 0.0; for (PlanElement pe : planElements) { - if (pe instanceof Activity) { - Activity act = (Activity)pe; + if (pe instanceof Activity act) { if (act.getStartTime().isDefined() && act.getEndTime().isDefined()) { double startTime = act.getStartTime().seconds(); double endTime = act.getEndTime().seconds(); duration += (endTime - startTime); } - } else if (pe instanceof Leg) { - Leg leg = (Leg) pe; + } else if (pe instanceof Leg leg) { duration += leg.getTravelTime().seconds(); } } @@ -861,12 +900,12 @@ private Config prepareConfig(double transferFixedCost, double transferRelativeCo Config config = ConfigUtils.createConfig(srrConfig); config.transitRouter().setDirectWalkFactor(1.0); - double beelineDistanceFactor = config.plansCalcRoute().getModeRoutingParams().get( TransportMode.walk ).getBeelineDistanceFactor(); - PlansCalcRouteConfigGroup.TeleportedModeParams walkParameters = new PlansCalcRouteConfigGroup.TeleportedModeParams(TransportMode.walk); + double beelineDistanceFactor = config.routing().getModeRoutingParams().get( TransportMode.walk ).getBeelineDistanceFactor(); + RoutingConfigGroup.TeleportedModeParams walkParameters = new RoutingConfigGroup.TeleportedModeParams(TransportMode.walk); walkParameters.setTeleportedModeSpeed(beelineDistanceFactor); // set it such that the beelineWalkSpeed is exactly 1 - config.plansCalcRoute().addParameterSet(walkParameters); + config.routing().addParameterSet(walkParameters); - config.planCalcScore().setUtilityOfLineSwitch(-transferFixedCost); + config.scoring().setUtilityOfLineSwitch(-transferFixedCost); srrConfig.setTransferPenaltyBaseCost(transferFixedCost); srrConfig.setTransferPenaltyCostPerTravelTimeHour(transferRelativeCostFactor); @@ -895,11 +934,11 @@ public void testModeMapping() { ModeParams railParams = new ModeParams("rail"); railParams.setMarginalUtilityOfTraveling(-6.0); - f.config.planCalcScore().addModeParams(railParams); + f.config.scoring().addModeParams(railParams); ModeParams roadParams = new ModeParams("road"); roadParams.setMarginalUtilityOfTraveling(-6.0); - f.config.planCalcScore().addModeParams(roadParams); + f.config.scoring().addModeParams(roadParams); TransitRouter router = createTransitRouter(f.schedule, f.config, f.network); Coord toCoord = new Coord(16100, 10050); @@ -957,11 +996,11 @@ public void testModeMappingCosts() { ModeParams railParams = new ModeParams("rail"); railParams.setMarginalUtilityOfTraveling(-6.0); - config.planCalcScore().addModeParams(railParams); + config.scoring().addModeParams(railParams); ModeParams roadParams = new ModeParams("road"); roadParams.setMarginalUtilityOfTraveling(-6.0); - config.planCalcScore().addModeParams(roadParams); + config.scoring().addModeParams(roadParams); } { // test with similar costs, the red line should still be cheaper @@ -989,7 +1028,7 @@ public void testModeMappingCosts() { // (the access/egress legs to red are each 2 meters shorter than to green line, which adds a little additional penalty for the green line, about 0.02) ModeParams roadParams = new ModeParams("road"); roadParams.setMarginalUtilityOfTraveling(2.83); - config.planCalcScore().addModeParams(roadParams); + config.scoring().addModeParams(roadParams); TransitRouter router = createTransitRouter(f.schedule, config, f.network); List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 6.0 * 3600 - 5 * 60, null)); @@ -1224,10 +1263,10 @@ private static class TransferFixture { this.config.transitRouter().setSearchRadius(500.0); this.config.transitRouter().setMaxBeelineWalkConnectionDistance(100.0); - double beelineDistanceFactor = this.config.plansCalcRoute().getModeRoutingParams().get( TransportMode.walk ).getBeelineDistanceFactor(); - PlansCalcRouteConfigGroup.TeleportedModeParams walkParameters = new PlansCalcRouteConfigGroup.TeleportedModeParams(TransportMode.walk); + double beelineDistanceFactor = this.config.routing().getModeRoutingParams().get( TransportMode.walk ).getBeelineDistanceFactor(); + RoutingConfigGroup.TeleportedModeParams walkParameters = new RoutingConfigGroup.TeleportedModeParams(TransportMode.walk); walkParameters.setTeleportedModeSpeed(beelineDistanceFactor); // set it such that the beelineWalkSpeed is exactly 1 - this.config.plansCalcRoute().addParameterSet(walkParameters); + this.config.routing().addParameterSet(walkParameters); // network Network network = this.scenario.getNetwork(); diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTreeTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTreeTest.java index f1932f29f52..05ad518af21 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTreeTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTreeTest.java @@ -1,7 +1,22 @@ -/* - * Copyright (C) Schweizerische Bundesbahnen SBB, 2018. - */ - +/* *********************************************************************** * + * project: org.matsim.* * + * + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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 ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorCore.TravelInfo; diff --git a/matsim/src/test/java/org/matsim/analysis/IterationTravelStatsControlerListenerTest.java b/matsim/src/test/java/org/matsim/analysis/IterationTravelStatsControlerListenerTest.java index f36eb79f670..d665683747a 100644 --- a/matsim/src/test/java/org/matsim/analysis/IterationTravelStatsControlerListenerTest.java +++ b/matsim/src/test/java/org/matsim/analysis/IterationTravelStatsControlerListenerTest.java @@ -1,5 +1,5 @@ /** - * + * */ package org.matsim.analysis; @@ -43,19 +43,19 @@ public class IterationTravelStatsControlerListenerTest { final IdMap map = new IdMap<>(Person.class); Config config = ConfigUtils.createConfig(); - + private int person; private int executed_score; private int first_act_x; private int first_act_y; private int first_act_type; - + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - + @Test public void testIterationTravelStatsControlerListener() { - + Plans plans = new Plans(); /**************************** @@ -78,9 +78,9 @@ public void testIterationTravelStatsControlerListener() { * Plan 4-----creating plan 4 **************************************/ Plan plan4 = plans.createPlanFour(); - + Scenario scenario = ScenarioUtils.createScenario(config); - + Person person1 = PopulationUtils.getFactory().createPerson(Id.create("1", Person.class));; person1.addPlan(plan1); Person person2 = PopulationUtils.getFactory().createPerson(Id.create("2", Person.class));; @@ -89,18 +89,18 @@ public void testIterationTravelStatsControlerListener() { person3.addPlan(plan3); Person person4 = PopulationUtils.getFactory().createPerson(Id.create("4", Person.class));; person4.addPlan(plan4); - + scenario.getPopulation().addPerson(person1); scenario.getPopulation().addPerson(person2); scenario.getPopulation().addPerson(person3); scenario.getPopulation().addPerson(person4); - + performTest(scenario, utils.getOutputDirectory() + "/IterationTravelStatsControlerListener"); } - + private void performTest(Scenario scenario, String outputDirectory) { - - config.controler().setOutputDirectory(utils.getOutputDirectory()); + + config.controller().setOutputDirectory(utils.getOutputDirectory()); ShutdownEvent shutdownEvent = new ShutdownEvent(null, false, 0); com.google.inject.Injector injector = Injector.createInjector(config, new AbstractModule() { @Override @@ -121,11 +121,11 @@ public void install() { ltcl.notifyShutdown(shutdownEvent); readAndValidateValues(scenario); } - + private Activity identifyFirstActivity(Person person) { return (Activity) person.getSelectedPlan().getPlanElements().get(0); } - + private void readAndValidateValues(Scenario scenario) { String file = utils.getOutputDirectory() + "/output_persons.csv.gz"; @@ -163,9 +163,9 @@ private void readAndValidateValues(Scenario scenario) { e.printStackTrace(); } - + } - + private void decideColumns(String[] columnNames) { Integer i = 0; @@ -184,7 +184,7 @@ private void decideColumns(String[] columnNames) { case "first_act_x": first_act_x = i; break; - + case "first_act_y": first_act_y = i; break; diff --git a/matsim/src/test/java/org/matsim/analysis/LinkStatsControlerListenerTest.java b/matsim/src/test/java/org/matsim/analysis/LinkStatsControlerListenerTest.java index 2518d3f0635..e72013364c3 100644 --- a/matsim/src/test/java/org/matsim/analysis/LinkStatsControlerListenerTest.java +++ b/matsim/src/test/java/org/matsim/analysis/LinkStatsControlerListenerTest.java @@ -65,8 +65,8 @@ public void testlinksOutputCSV() throws IOException { String outputDirectory = util.getOutputDirectory(); Config config = this.util.loadConfig("test/scenarios/equil/config_plans1.xml"); - config.controler().setLastIteration(10); - config.controler().setOutputDirectory(outputDirectory); + config.controller().setLastIteration(10); + config.controller().setOutputDirectory(outputDirectory); Controler c = new Controler(config); c.run(); @@ -84,7 +84,7 @@ public void testlinksOutputCSV() throws IOException { @Test public void testUseVolumesOfIteration() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(util.getOutputDirectory()); + config.controller().setOutputDirectory(util.getOutputDirectory()); final Scenario scenario = ScenarioUtils.createScenario(config); com.google.inject.Injector injector = Injector.createInjector(config, new AbstractModule() { @Override @@ -320,38 +320,38 @@ public void test_writeLinkStatsInterval() { controler.addOverridingModule(new AbstractModule() { @Override public void install() { - if (getConfig().controler().getMobsim().equals("dummy")) { + if (getConfig().controller().getMobsim().equals("dummy")) { bind(Mobsim.class).toProvider(DummyMobsimFactory.class); } } }); - config.controler().setMobsim("dummy"); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(7); - - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); + config.controller().setMobsim("dummy"); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(7); + + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); controler.run(); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.0/0.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.1/1.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.2/2.linkstats.txt.gz").exists()); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.3/3.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.4/4.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.5/5.linkstats.txt.gz").exists()); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.6/6.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.7/7.linkstats.txt.gz").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.0/0.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.1/1.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.2/2.linkstats.txt.gz").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.3/3.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.4/4.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.5/5.linkstats.txt.gz").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.6/6.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.7/7.linkstats.txt.gz").exists()); } @Test public void testReset_CorrectlyExecuted() throws IOException { Config config = this.util.loadConfig((String) null); - config.controler().setMobsim("dummy"); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(7); - config.controler().setWritePlansInterval(0); + config.controller().setMobsim("dummy"); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(7); + config.controller().setWritePlansInterval(0); LinkStatsConfigGroup lsConfig = config.linkStats(); lsConfig.setWriteLinkStatsInterval(3); @@ -367,31 +367,31 @@ public void testReset_CorrectlyExecuted() throws IOException { controler.addOverridingModule(new AbstractModule() { @Override public void install() { - if (getConfig().controler().getMobsim().equals("dummy")) { + if (getConfig().controller().getMobsim().equals("dummy")) { bind(Mobsim.class).toProvider(DummyMobsimFactory.class); } } }); - 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(); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.0/0.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.1/1.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.2/2.linkstats.txt.gz").exists()); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.3/3.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.4/4.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.5/5.linkstats.txt.gz").exists()); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.6/6.linkstats.txt.gz").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.7/7.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.0/0.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.1/1.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.2/2.linkstats.txt.gz").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.3/3.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.4/4.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.5/5.linkstats.txt.gz").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.6/6.linkstats.txt.gz").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.7/7.linkstats.txt.gz").exists()); - double[] volumes = getVolumes(config.controler().getOutputDirectory() + "ITERS/it.3/3.linkstats.txt"); + double[] volumes = getVolumes(config.controller().getOutputDirectory() + "ITERS/it.3/3.linkstats.txt"); Assert.assertEquals(3, volumes[0], 1e-8); Assert.assertEquals(3.5, volumes[1], 1e-8); Assert.assertEquals(4, volumes[2], 1e-8); - volumes = getVolumes(config.controler().getOutputDirectory() + "ITERS/it.6/6.linkstats.txt"); + volumes = getVolumes(config.controller().getOutputDirectory() + "ITERS/it.6/6.linkstats.txt"); Assert.assertEquals(6, volumes[0], 1e-8); Assert.assertEquals(6.5, volumes[1], 1e-8); Assert.assertEquals(7, volumes[2], 1e-8); diff --git a/matsim/src/test/java/org/matsim/analysis/ModeChoiceCoverageControlerListenerTest.java b/matsim/src/test/java/org/matsim/analysis/ModeChoiceCoverageControlerListenerTest.java index 093aae7460d..051f1485cf6 100644 --- a/matsim/src/test/java/org/matsim/analysis/ModeChoiceCoverageControlerListenerTest.java +++ b/matsim/src/test/java/org/matsim/analysis/ModeChoiceCoverageControlerListenerTest.java @@ -8,9 +8,9 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.*; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.ControlerConfigGroup.CompressionType; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.controler.events.IterationEndsEvent; @@ -38,17 +38,17 @@ public class ModeChoiceCoverageControlerListenerTest { public void testChangePlanModes() { Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig()); - PlanCalcScoreConfigGroup scoreConfig = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup scoreConfig = new ScoringConfigGroup(); TransportPlanningMainModeIdentifier transportId = new TransportPlanningMainModeIdentifier(); - ControlerConfigGroup controlerConfigGroup = new ControlerConfigGroup(); + ControllerConfigGroup controllerConfigGroup = new ControllerConfigGroup(); OutputDirectoryHierarchy controlerIO = new OutputDirectoryHierarchy(utils.getOutputDirectory() + "/ModeChoiceCoverageControlerListener", OverwriteFileSetting.overwriteExistingFiles, CompressionType.gzip); Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); population.addPerson(person); - ModeChoiceCoverageControlerListener modeCC = new ModeChoiceCoverageControlerListener(controlerConfigGroup, population, controlerIO, scoreConfig, transportId); + ModeChoiceCoverageControlerListener modeCC = new ModeChoiceCoverageControlerListener(controllerConfigGroup, population, controlerIO, scoreConfig, transportId); modeCC.notifyStartup(new StartupEvent(null)); // Iteration 0: walk - walk @@ -95,10 +95,10 @@ public void testChangePlanModes() { @Test public void testTwoAgents() { Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig()); - PlanCalcScoreConfigGroup scoreConfig = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup scoreConfig = new ScoringConfigGroup(); TransportPlanningMainModeIdentifier transportId = new TransportPlanningMainModeIdentifier(); - ControlerConfigGroup controlerConfigGroup = new ControlerConfigGroup(); + ControllerConfigGroup controllerConfigGroup = new ControllerConfigGroup(); OutputDirectoryHierarchy controlerIO = new OutputDirectoryHierarchy(utils.getOutputDirectory() + "/ModeChoiceCoverageControlerListener", OverwriteFileSetting.overwriteExistingFiles, CompressionType.gzip); @@ -108,7 +108,7 @@ public void testTwoAgents() { population.addPerson(person2); - ModeChoiceCoverageControlerListener modeCC = new ModeChoiceCoverageControlerListener(controlerConfigGroup, population, controlerIO, scoreConfig, transportId); + ModeChoiceCoverageControlerListener modeCC = new ModeChoiceCoverageControlerListener(controllerConfigGroup, population, controlerIO, scoreConfig, transportId); modeCC.notifyStartup(new StartupEvent(null)); // Iteration 0: walk - walk @@ -166,17 +166,17 @@ public void testTwoAgents() { public void testDifferentLevels() { Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig()); - PlanCalcScoreConfigGroup scoreConfig = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup scoreConfig = new ScoringConfigGroup(); TransportPlanningMainModeIdentifier transportId = new TransportPlanningMainModeIdentifier(); - ControlerConfigGroup controlerConfigGroup = new ControlerConfigGroup(); + ControllerConfigGroup controllerConfigGroup = new ControllerConfigGroup(); OutputDirectoryHierarchy controlerIO = new OutputDirectoryHierarchy(utils.getOutputDirectory() + "/ModeChoiceCoverageControlerListener", OverwriteFileSetting.overwriteExistingFiles, CompressionType.gzip); Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); population.addPerson(person); - ModeChoiceCoverageControlerListener modeCC = new ModeChoiceCoverageControlerListener(controlerConfigGroup, population, controlerIO, scoreConfig, transportId); + ModeChoiceCoverageControlerListener modeCC = new ModeChoiceCoverageControlerListener(controllerConfigGroup, population, controlerIO, scoreConfig, transportId); modeCC.notifyStartup(new StartupEvent(null)); // After 1 iteration @@ -243,4 +243,4 @@ private Plan makePlan( Person person, String modeLeg1, String modeLeg2) { plan.addActivity(act3); return plan; } -} \ No newline at end of file +} diff --git a/matsim/src/test/java/org/matsim/analysis/ModeStatsControlerListenerTest.java b/matsim/src/test/java/org/matsim/analysis/ModeStatsControlerListenerTest.java index ec04b4c6874..daf5a8cd90d 100644 --- a/matsim/src/test/java/org/matsim/analysis/ModeStatsControlerListenerTest.java +++ b/matsim/src/test/java/org/matsim/analysis/ModeStatsControlerListenerTest.java @@ -1,5 +1,5 @@ /** - * + * */ package org.matsim.analysis; @@ -23,14 +23,14 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.api.core.v01.population.Population; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.ControlerConfigGroup.CompressionType; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; +import org.matsim.core.config.groups.GlobalConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.controler.events.IterationEndsEvent; -import org.matsim.core.controler.events.ShutdownEvent; import org.matsim.core.controler.events.StartupEvent; import org.matsim.core.population.PopulationUtils; import org.matsim.testcases.MatsimTestUtils; @@ -48,9 +48,9 @@ public class ModeStatsControlerListenerTest { int non_network_walk; int ride; int walk; - HashMap person3modes = new HashMap(); - HashMap person1modes = new HashMap(); - HashMap person2modes = new HashMap(); + HashMap person3modes = new HashMap<>(); + HashMap person1modes = new HashMap<>(); + HashMap person2modes = new HashMap<>(); @Rule public MatsimTestUtils utils = new MatsimTestUtils(); @@ -60,7 +60,7 @@ public void testModeStatsControlerListener() { Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig()); final List planElem = new ArrayList(); - PlanCalcScoreConfigGroup scoreConfig = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup scoreConfig = new ScoringConfigGroup(); TransportPlanningMainModeIdentifier transportId = new TransportPlanningMainModeIdentifier(); ModeParams modeParam1 = new ModeParams(TransportMode.walk); ModeParams modeParam2 = new ModeParams(TransportMode.car); @@ -344,25 +344,24 @@ public void testModeStatsControlerListener() { person3.addPlan(plan3); population.addPerson(person3); - performTest(population, transportId, scoreConfig, utils.getOutputDirectory() + "/ModeStatsControlerListener", - planElem); + performTest(population, transportId, utils.getOutputDirectory() + "/ModeStatsControlerListener"); } private void performTest(Population population, TransportPlanningMainModeIdentifier transportId, - PlanCalcScoreConfigGroup scoreConfig, String outputDirectory, List planElem) { + String outputDirectory) { - ControlerConfigGroup controlerConfigGroup = new ControlerConfigGroup(); + ControllerConfigGroup controllerConfigGroup = new ControllerConfigGroup(); OutputDirectoryHierarchy controlerIO = new OutputDirectoryHierarchy(outputDirectory, OverwriteFileSetting.overwriteExistingFiles, CompressionType.gzip); - controlerConfigGroup.setCreateGraphs(true); - controlerConfigGroup.setFirstIteration(0); - ModeStatsControlerListener modStatListner = new ModeStatsControlerListener(controlerConfigGroup, population, - controlerIO, scoreConfig, transportId); + controllerConfigGroup.setCreateGraphs(true); + controllerConfigGroup.setFirstIteration(0); + ModeStatsControlerListener modStatListner = new ModeStatsControlerListener(controllerConfigGroup, population, + controlerIO, new GlobalConfigGroup(), transportId); StartupEvent eventStart = new StartupEvent(null); modStatListner.notifyStartup(eventStart); - HashMap modesIter0 = new HashMap(); + HashMap modesIter0 = new HashMap<>(); IterationEndsEvent event0 = new IterationEndsEvent(null, 0, false); modStatListner.notifyIterationEnds(event0); @@ -373,7 +372,7 @@ private void performTest(Population population, TransportPlanningMainModeIdentif person3modes.forEach((k, v) -> modesIter0.merge(k, v, Integer::sum)); readAndcompareValues(modesIter0, 0); - + //Remove one person population.getPersons().remove(Id.create("2", Person.class)); @@ -412,7 +411,7 @@ private void performTest(Population population, TransportPlanningMainModeIdentif //sum of the scores of each mode should add up to 1 private void readAndcompareValues(HashMap modes, int itr) { - String file = utils.getOutputDirectory() + "/ModeStatsControlerListener" + "/modestats.txt"; + String file = utils.getOutputDirectory() + "/ModeStatsControlerListener" + "/modestats.csv"; BufferedReader br; String line; int totalTrips = modes.get(TransportMode.car) + modes.get(TransportMode.bike) + modes.get(TransportMode.pt) @@ -421,21 +420,22 @@ private void readAndcompareValues(HashMap modes, int itr) { try { br = new BufferedReader(new FileReader(file)); String firstRow = br.readLine(); - String[] columnNames = firstRow.split(" "); + String delimiter = new GlobalConfigGroup().getDefaultDelimiter(); + String[] columnNames = firstRow.split(delimiter); decideColumns(columnNames); int iteration = 0; while ((line = br.readLine()) != null) { if (iteration == itr) { - String[] column = line.split(" "); + String[] column = line.split(delimiter); // checking if column number in greater than 0, because 0th column is always 'Iteration' and we don't need that --> see decideColumns() method - Double carvalue = (car > 0) ? Double.valueOf(column[car]) : 0; - Double walkvalue = (walk > 0) ? Double.valueOf(column[walk]) : 0; - Double ptvalue = (pt > 0) ? Double.valueOf(column[pt]) : 0; - Double bikevalue = (bike > 0) ? Double.valueOf(column[bike]) : 0; - Double non_network_walkvalue = (non_network_walk > 0) ? Double.valueOf(column[non_network_walk]) + double carvalue = (car > 0) ? Double.parseDouble(column[car]) : 0; + double walkvalue = (walk > 0) ? Double.parseDouble(column[walk]) : 0; + double ptvalue = (pt > 0) ? Double.parseDouble(column[pt]) : 0; + double bikevalue = (bike > 0) ? Double.parseDouble(column[bike]) : 0; + double non_network_walkvalue = (non_network_walk > 0) ? Double.valueOf(column[non_network_walk]) : 0; - Double othervalue = (other > 0) ? Double.valueOf(column[other]) : 0; - Double ridevalue = (ride > 0) ? Double.valueOf(column[ride]) : 0; + double othervalue = (other > 0) ? Double.parseDouble(column[other]) : 0; + double ridevalue = (ride > 0) ? Double.parseDouble(column[ride]) : 0; Assert.assertEquals("car mode has an unexpected score", (modes.get(TransportMode.car).doubleValue() / totalTrips), carvalue, 0); Assert.assertEquals("walk mode has an unexpected score", @@ -461,7 +461,6 @@ private void readAndcompareValues(HashMap modes, int itr) { iteration++; } } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } diff --git a/matsim/src/test/java/org/matsim/analysis/OutputTravelStatsTest.java b/matsim/src/test/java/org/matsim/analysis/OutputTravelStatsTest.java index a0b143b7642..2ed4392921c 100644 --- a/matsim/src/test/java/org/matsim/analysis/OutputTravelStatsTest.java +++ b/matsim/src/test/java/org/matsim/analysis/OutputTravelStatsTest.java @@ -44,9 +44,9 @@ public void testActivitiesOutputCSV() throws IOException { String outputDirectory = util.getOutputDirectory(); Config config = this.util.loadConfig("test/scenarios/equil/config_plans1.xml"); - config.controler().setLastIteration(10); - config.controler().setWriteTripsInterval(1); - config.controler().setOutputDirectory(outputDirectory); + config.controller().setLastIteration(10); + config.controller().setWriteTripsInterval(1); + config.controller().setOutputDirectory(outputDirectory); Controler c = new Controler(config); c.run(); diff --git a/matsim/src/test/java/org/matsim/analysis/PHbyModeCalculatorTest.java b/matsim/src/test/java/org/matsim/analysis/PHbyModeCalculatorTest.java index ff7ee2442c6..e123bfceea9 100644 --- a/matsim/src/test/java/org/matsim/analysis/PHbyModeCalculatorTest.java +++ b/matsim/src/test/java/org/matsim/analysis/PHbyModeCalculatorTest.java @@ -1,5 +1,5 @@ /** - * + * */ package org.matsim.analysis; @@ -19,8 +19,9 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.ControlerConfigGroup.CompressionType; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; +import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.router.StageActivityTypeIdentifier; @@ -38,7 +39,7 @@ public class PHbyModeCalculatorTest { private int walk_travel; private int pt_wait; private int stageActivity_wait; - + Id person1 = Id.create("person1", Person.class); Id person2 = Id.create("person2", Person.class); @@ -86,18 +87,18 @@ public void testPKMbyModeCalculator() { private void performTest(IdMap map, String outputDirectory) { - ControlerConfigGroup controlerConfigGroup = new ControlerConfigGroup(); + ControllerConfigGroup controllerConfigGroup = new ControllerConfigGroup(); OutputDirectoryHierarchy controlerIO = new OutputDirectoryHierarchy(outputDirectory, OverwriteFileSetting.overwriteExistingFiles, CompressionType.gzip); - controlerConfigGroup.setCreateGraphs(true); - controlerConfigGroup.setFirstIteration(0); - controlerConfigGroup.setLastIteration(10); - PHbyModeCalculator phbyModeCalculator = new PHbyModeCalculator(controlerConfigGroup, controlerIO); + controllerConfigGroup.setCreateGraphs(true); + controllerConfigGroup.setFirstIteration(0); + controllerConfigGroup.setLastIteration(10); + PHbyModeCalculator phbyModeCalculator = new PHbyModeCalculator(controllerConfigGroup, controlerIO, new GlobalConfigGroup()); phbyModeCalculator.addIteration(1, map); phbyModeCalculator.writeOutput(); readAndValidateValues(1, map); - + // removing person 2 map.remove(person2); phbyModeCalculator.addIteration(2, map); @@ -145,7 +146,7 @@ private void readAndValidateValues(int itr, IdMap map) { .getAttribute(EventsToLegs.ENTER_VEHICLE_TIME_ATTRIBUTE_NAME) - ((Leg) elem).getDepartureTime().seconds(); modeValues.put("pt_wait", wait_value); } - + }else if(elem instanceof Activity) { Activity act = (Activity) elem; if (StageActivityTypeIdentifier.isStageActivity(act.getType())) { @@ -157,25 +158,26 @@ private void readAndValidateValues(int itr, IdMap map) { } } - String file = utils.getOutputDirectory() + "/PHbyModeCalculator" + "/ph_modestats.txt"; + String file = utils.getOutputDirectory() + "/PHbyModeCalculator" + "/ph_modestats.csv"; BufferedReader br; String line; try { br = new BufferedReader(new FileReader(file)); String firstRow = br.readLine(); - String[] columnNames = firstRow.split(" "); + String delimiter = new GlobalConfigGroup().getDefaultDelimiter(); + String[] columnNames = firstRow.split(delimiter); decideColumns(columnNames); int iteration = 1; while ((line = br.readLine()) != null) { if (iteration == itr) { - String[] column = line.split(" "); + String[] column = line.split(delimiter); // checking if column number in greater than 0, because 0th column is always // 'Iteration' and we don't need that --> see decideColumns() method - Double car_travel_value = Double.valueOf(column[car_travel]); - Double pt_travel_value = Double.valueOf(column[pt_travel]); - Double walk_travel_value = Double.valueOf(column[walk_travel]); - Double pt_wait_value = Double.valueOf(column[pt_wait]); - Double stageActivity_wait_value = Double.valueOf(column[stageActivity_wait]); + double car_travel_value = Double.parseDouble(column[car_travel]); + double pt_travel_value = Double.parseDouble(column[pt_travel]); + double walk_travel_value = Double.parseDouble(column[walk_travel]); + double pt_wait_value = Double.parseDouble(column[pt_wait]); + double stageActivity_wait_value = Double.parseDouble(column[stageActivity_wait]); Assert.assertEquals("car_travel hour does not match", Math.round(modeValues.get("car") / 3600.0), car_travel_value, 0); @@ -218,11 +220,11 @@ private void decideColumns(String[] columnNames) { case "walk_travel": walk_travel = i; break; - + case "pt_wait": pt_wait = i; break; - + case "stageActivity_wait": stageActivity_wait = i; break; diff --git a/matsim/src/test/java/org/matsim/analysis/PKMbyModeCalculatorTest.java b/matsim/src/test/java/org/matsim/analysis/PKMbyModeCalculatorTest.java index 648fda65cd8..ba62f04f994 100644 --- a/matsim/src/test/java/org/matsim/analysis/PKMbyModeCalculatorTest.java +++ b/matsim/src/test/java/org/matsim/analysis/PKMbyModeCalculatorTest.java @@ -1,5 +1,5 @@ /** - * + * */ package org.matsim.analysis; @@ -17,8 +17,9 @@ import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.ControlerConfigGroup.CompressionType; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; +import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.population.PopulationUtils; @@ -51,7 +52,7 @@ public void testPKMbyModeCalculator() { /**************************** * Person - creating person 1 ************************************/ - + Plan plan = plans.createPlanOne(); // counting the total distance traveled in each mode @@ -153,13 +154,13 @@ public void testPKMbyModeCalculator() { private void performTest(IdMap map, HashMap modeCalcDist, String outputDirectory) { - ControlerConfigGroup controlerConfigGroup = new ControlerConfigGroup(); + ControllerConfigGroup controllerConfigGroup = new ControllerConfigGroup(); OutputDirectoryHierarchy controlerIO = new OutputDirectoryHierarchy(outputDirectory, OverwriteFileSetting.overwriteExistingFiles, CompressionType.gzip); - controlerConfigGroup.setCreateGraphs(true); - controlerConfigGroup.setFirstIteration(0); - controlerConfigGroup.setLastIteration(10); - PKMbyModeCalculator pkmbyModeCalculator = new PKMbyModeCalculator(controlerConfigGroup, controlerIO); + controllerConfigGroup.setCreateGraphs(true); + controllerConfigGroup.setFirstIteration(0); + controllerConfigGroup.setLastIteration(10); + PKMbyModeCalculator pkmbyModeCalculator = new PKMbyModeCalculator(controllerConfigGroup, controlerIO, new GlobalConfigGroup()); // iteration 0 pkmbyModeCalculator.addIteration(0, map); pkmbyModeCalculator.writeOutput(); @@ -198,23 +199,23 @@ private void performTest(IdMap map, HashMap modeCa /************ Reading and validating the output ************/ private void readAndValidateValues(int itr, Double totalCar, Double totalPt, Double totalWalk) { - String file = utils.getOutputDirectory() + "/PKMbyModeCalculator" + "/pkm_modestats.txt"; + String file = utils.getOutputDirectory() + "/PKMbyModeCalculator" + "/pkm_modestats.csv"; BufferedReader br; String line; try { br = new BufferedReader(new FileReader(file)); String firstRow = br.readLine(); - String[] columnNames = firstRow.split(" "); + String[] columnNames = firstRow.split(new GlobalConfigGroup().getDefaultDelimiter()); decideColumns(columnNames); int iteration = 0; while ((line = br.readLine()) != null) { if (iteration == itr) { - String[] column = line.split(" "); + String[] column = line.split(new GlobalConfigGroup().getDefaultDelimiter()); // checking if column number in greater than 0, because 0th column is always // 'Iteration' and we don't need that --> see decideColumns() method - Double carStat = (car > 0) ? Double.valueOf(column[car]) : 0; - Double ptStat = (pt > 0) ? Double.valueOf(column[pt]) : 0; - Double walkStat = (walk > 0) ? Double.valueOf(column[walk]) : 0; + double carStat = (car > 0) ? Double.parseDouble(column[car]) : 0; + double ptStat = (pt > 0) ? Double.parseDouble(column[pt]) : 0; + double walkStat = (walk > 0) ? Double.parseDouble(column[walk]) : 0; Assert.assertEquals("Car stats score does not match", Math.round((totalCar / 1000)), carStat, 0); Assert.assertEquals("PT stats score does not match", Math.round((totalPt / 1000)), ptStat, 0); diff --git a/matsim/src/test/java/org/matsim/analysis/ScoreStatsControlerListenerTest.java b/matsim/src/test/java/org/matsim/analysis/ScoreStatsControlerListenerTest.java index 6d944d4de95..33345fdfb2b 100644 --- a/matsim/src/test/java/org/matsim/analysis/ScoreStatsControlerListenerTest.java +++ b/matsim/src/test/java/org/matsim/analysis/ScoreStatsControlerListenerTest.java @@ -19,9 +19,11 @@ import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.Route; +import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.ControlerConfigGroup.CompressionType; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; +import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.controler.events.IterationEndsEvent; @@ -474,13 +476,13 @@ public void testScoreStatsControlerListner() throws IOException { private void performTest(String outputDirectory, Population population) throws IOException { - ControlerConfigGroup controlerConfigGroup = new ControlerConfigGroup(); + ControllerConfigGroup controllerConfigGroup = new ControllerConfigGroup(); OutputDirectoryHierarchy controlerIO = new OutputDirectoryHierarchy(outputDirectory, OverwriteFileSetting.overwriteExistingFiles, CompressionType.gzip); - controlerConfigGroup.setCreateGraphs(true); - controlerConfigGroup.setFirstIteration(0); - controlerConfigGroup.setLastIteration(10); - ScoreStatsControlerListener scoreStatsControlerListener = new ScoreStatsControlerListener(controlerConfigGroup, population, controlerIO, null, null); + controllerConfigGroup.setCreateGraphs(true); + controllerConfigGroup.setFirstIteration(0); + controllerConfigGroup.setLastIteration(10); + ScoreStatsControlerListener scoreStatsControlerListener = new ScoreStatsControlerListener(controllerConfigGroup, population, controlerIO, new GlobalConfigGroup()); String outDir = utils.getOutputDirectory() + "/ScoreStatsControlerListener"; @@ -520,25 +522,26 @@ private void performTest(String outputDirectory, Population population) throws I private void readAndValidateValues(String outDir, int itr, Population population) throws IOException { - String file = outDir + "/scorestats.txt"; + String file = outDir + "/scorestats.csv"; BufferedReader br; String line; br = new BufferedReader(new FileReader(file)); String firstRow = br.readLine(); - String[] columnNames = firstRow.split(" "); + String delimiter = new GlobalConfigGroup().getDefaultDelimiter(); + String[] columnNames = firstRow.split(delimiter); decideColumns(columnNames); int iteration = 0; while ((line = br.readLine()) != null) { if (iteration == itr) { - String[] column = line.split(" "); + String[] column = line.split(delimiter); // checking if column number in greater than 0, because 0th column is always // 'Iteration' and we don't need that --> see decideColumns() method - Double avgExecuted = (avgexecuted > 0) ? Double.valueOf(column[avgexecuted]) : 0; - Double avgWorst = (avgworst > 0) ? Double.valueOf(column[avgworst]) : 0; - Double avgBest = (avgbest > 0) ? Double.valueOf(column[avgbest]) : 0; - Double avgAverage = (avgaverage > 0) ? Double.valueOf(column[avgaverage]) : 0; + double avgExecuted = (avgexecuted > 0) ? Double.parseDouble(column[avgexecuted]) : 0; + double avgWorst = (avgworst > 0) ? Double.parseDouble(column[avgworst]) : 0; + double avgBest = (avgbest > 0) ? Double.parseDouble(column[avgbest]) : 0; + double avgAverage = (avgaverage > 0) ? Double.parseDouble(column[avgaverage]) : 0; Assert.assertEquals("avg. executed score does not match", (getScore(population, "avgexecuted")/(4-itr)), avgExecuted, 0); @@ -552,10 +555,10 @@ private void readAndValidateValues(String outDir, int itr, Population populatio iteration++; } - Assertions.assertThat(new File(outDir, "scorestats_group1.txt")) + Assertions.assertThat(new File(outDir, "scorestats_group1.csv")) .isFile(); - Assertions.assertThat(new File(outDir, "scorestats_group2.txt")) + Assertions.assertThat(new File(outDir, "scorestats_group2.csv")) .isFile(); } @@ -603,19 +606,19 @@ private void decideColumns(String[] columnNames) { String name = columnNames[i]; switch (name) { - case "avg. EXECUTED": + case "avg_executed": avgexecuted = i; break; - case "avg. WORST": + case "avg_worst": avgworst = i; break; - case "avg. AVG": + case "avg_average": avgaverage = i; break; - case "avg. BEST": + case "avg_best": avgbest = i; break; diff --git a/matsim/src/test/java/org/matsim/analysis/TravelDistanceStatsTest.java b/matsim/src/test/java/org/matsim/analysis/TravelDistanceStatsTest.java index 1c1897c8bac..e1e0a8fb0d2 100644 --- a/matsim/src/test/java/org/matsim/analysis/TravelDistanceStatsTest.java +++ b/matsim/src/test/java/org/matsim/analysis/TravelDistanceStatsTest.java @@ -1,5 +1,5 @@ /** - * + * */ package org.matsim.analysis; @@ -21,8 +21,9 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Route; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.ControlerConfigGroup.CompressionType; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; +import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.population.PopulationUtils; @@ -35,9 +36,9 @@ */ public class TravelDistanceStatsTest { - HashMap person3modes = new HashMap(); - HashMap person1modes = new HashMap(); - HashMap person2modes = new HashMap(); + HashMap person3modes = new HashMap<>(); + HashMap person1modes = new HashMap<>(); + HashMap person2modes = new HashMap<>(); private int avglegdis; private int avgtripdis; private Double person1legsum; @@ -336,13 +337,13 @@ public void testTravelDistanceStats() { private void performTest(IdMap map, String outputDirectory) { - ControlerConfigGroup controlerConfigGroup = new ControlerConfigGroup(); + ControllerConfigGroup controllerConfigGroup = new ControllerConfigGroup(); OutputDirectoryHierarchy controlerIO = new OutputDirectoryHierarchy(outputDirectory, OverwriteFileSetting.overwriteExistingFiles, CompressionType.gzip); - controlerConfigGroup.setCreateGraphs(true); - controlerConfigGroup.setFirstIteration(0); - controlerConfigGroup.setLastIteration(10); - TravelDistanceStats travelDistanceStats = new TravelDistanceStats(controlerConfigGroup, controlerIO); + controllerConfigGroup.setCreateGraphs(true); + controllerConfigGroup.setFirstIteration(0); + controllerConfigGroup.setLastIteration(10); + TravelDistanceStats travelDistanceStats = new TravelDistanceStats(controllerConfigGroup, controlerIO, new GlobalConfigGroup()); travelDistanceStats.addIteration(0, map); readAndValidateValues(0, person1legsum + person2legsum + person3legsum, 12, person1TotalNumberOfLegs + person2TotalNumberOfLegs + person3TotalNumberOfLegs); @@ -357,22 +358,23 @@ private void performTest(IdMap map, String outputDirectory) { private void readAndValidateValues(int itr, Double legSum, int totalTrip, long totalLeg) { - String file = utils.getOutputDirectory() + "/TravelDistanceStat" + "/traveldistancestats.txt"; + String file = utils.getOutputDirectory() + "/TravelDistanceStat" + "/traveldistancestats.csv"; BufferedReader br; String line; try { br = new BufferedReader(new FileReader(file)); String firstRow = br.readLine(); - String[] columnNames = firstRow.split(" "); + String delimiter = new GlobalConfigGroup().getDefaultDelimiter(); + String[] columnNames = firstRow.split(delimiter); decideColumns(columnNames); int iteration = 0; while ((line = br.readLine()) != null) { if (iteration == itr) { - String[] column = line.split(" "); + String[] column = line.split(delimiter); // checking if column number in greater than 0, because 0th column is always // 'Iteration' and we don't need that --> see decideColumns() method - Double avgLegvalue = (avglegdis > 0) ? Double.valueOf(column[avglegdis]) : 0; - Double avgTripvalue = (avgtripdis > 0) ? Double.valueOf(column[avgtripdis]) : 0; + double avgLegvalue = (avglegdis > 0) ? Double.parseDouble(column[avglegdis]) : 0; + double avgTripvalue = (avgtripdis > 0) ? Double.parseDouble(column[avgtripdis]) : 0; Assert.assertEquals("avg. Average Trip distance does not match", (legSum / totalTrip), avgTripvalue, 0); @@ -384,7 +386,6 @@ private void readAndValidateValues(int itr, Double legSum, int totalTrip, long t iteration++; } } catch (IOException e) { - // TODO Auto-generated catch block e.printStackTrace(); } diff --git a/matsim/src/test/java/org/matsim/analysis/TripsAnalysisIT.java b/matsim/src/test/java/org/matsim/analysis/TripsAnalysisIT.java new file mode 100644 index 00000000000..7abdeff8aea --- /dev/null +++ b/matsim/src/test/java/org/matsim/analysis/TripsAnalysisIT.java @@ -0,0 +1,80 @@ +/* *********************************************************************** * + * project: org.matsim.* + * * + * *********************************************************************** * + * * + * copyright : (C) 2023 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.analysis; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; +import org.assertj.core.api.Assertions; +import org.junit.Rule; +import org.junit.Test; +import org.matsim.api.core.v01.Scenario; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.controler.Controler; +import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.core.utils.io.IOUtils; +import org.matsim.examples.ExamplesUtils; +import org.matsim.testcases.MatsimTestUtils; + +import java.io.IOException; +import java.io.Reader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TripsAnalysisIT { + + @Rule + public MatsimTestUtils testUtils = new MatsimTestUtils(); + + @Test + public void testMainMode() { + final Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); + Scenario scenario = ScenarioUtils.loadScenario(config); + + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); + + Controler controller = new Controler(scenario); + controller.run(); + + String tripsCsvFilename = controller.getControlerIO().getOutputFilename(Controler.DefaultFiles.tripscsv); + try (Reader reader = IOUtils.getBufferedReader(tripsCsvFilename)) { + CSVParser parser = new CSVParser(reader, CSVFormat.newFormat(config.global().getDefaultDelimiter().charAt(0))); + List records = parser.getRecords(); + CSVRecord header = records.get(0); + Map headerMap = new HashMap<>(); + for (int i = 0; i < header.size(); i++) { + headerMap.put(header.get(i), i); + } + int mainModeIndex = headerMap.get("main_mode"); + for (int row = 1, n = Math.min(30, records.size()); row < n; row++) { + CSVRecord record = records.get(row); + String mainMode = record.get(mainModeIndex); + if (mainMode == null || mainMode.isBlank()) { + Assertions.fail("Row " + row + " has no main_mode set.\nheader = " + header + "\nrow = " + row); + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/matsim/src/test/java/org/matsim/api/core/v01/IdAnnotationsTest.java b/matsim/src/test/java/org/matsim/api/core/v01/IdAnnotationsTest.java index f99a2a6d700..dcfa4db3a27 100644 --- a/matsim/src/test/java/org/matsim/api/core/v01/IdAnnotationsTest.java +++ b/matsim/src/test/java/org/matsim/api/core/v01/IdAnnotationsTest.java @@ -4,9 +4,7 @@ import org.junit.Assert; import org.junit.Test; -import org.matsim.api.core.v01.IdAnnotations.JsonLinkId; -import org.matsim.api.core.v01.IdAnnotations.JsonNodeId; -import org.matsim.api.core.v01.IdAnnotations.JsonPersonId; +import org.matsim.api.core.v01.IdAnnotations.JsonId; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Node; import org.matsim.api.core.v01.population.Person; @@ -22,8 +20,9 @@ public class IdAnnotationsTest { @Test public void testRecordJsonIds() throws JsonProcessingException { + Id personId = Id.createPersonId("person"); RecordWithIds recordWithIds1 = new RecordWithIds( - Id.createPersonId("person"), + personId, Id.createLinkId("link"), Id.createNodeId("node")); @@ -31,22 +30,28 @@ public void testRecordJsonIds() throws JsonProcessingException { RecordWithIds recordWithIds2 = objectMapper.readValue(s, RecordWithIds.class); Assert.assertEquals(recordWithIds1, recordWithIds2); + Assert.assertEquals(personId, recordWithIds2.personId); + Assert.assertSame(personId, recordWithIds2.personId); } @Test public void testRecordJsonIdsWithNull() throws JsonProcessingException { - RecordWithIds recordWithIds1 = new RecordWithIds(null, null, null); + Id personId = null; + RecordWithIds recordWithIds1 = new RecordWithIds(personId, null, null); String s = objectMapper.writeValueAsString(recordWithIds1); RecordWithIds recordWithIds2 = objectMapper.readValue(s, RecordWithIds.class); Assert.assertEquals(recordWithIds1, recordWithIds2); + Assert.assertEquals(personId, recordWithIds2.personId); + Assert.assertSame(personId, recordWithIds2.personId); } @Test public void testClassJsonIds() throws JsonProcessingException { + Id personId = Id.createPersonId("person"); ClassWithIds classWithIds1 = new ClassWithIds( - Id.createPersonId("person"), + personId, Id.createLinkId("link"), Id.createNodeId("node")); @@ -54,35 +59,40 @@ public void testClassJsonIds() throws JsonProcessingException { ClassWithIds classWithIds2 = objectMapper.readValue(s, ClassWithIds.class); Assert.assertEquals(classWithIds1, classWithIds2); + Assert.assertEquals(personId, classWithIds2.personId); + Assert.assertSame(personId, classWithIds2.personId); } @Test public void testClassJsonIdsWithNull() throws JsonProcessingException { - ClassWithIds classWithIds1 = new ClassWithIds(null, null, null); + Id personId = null; + ClassWithIds classWithIds1 = new ClassWithIds(personId, null, null); String s = objectMapper.writeValueAsString(classWithIds1); ClassWithIds classWithIds2 = objectMapper.readValue(s, ClassWithIds.class); Assert.assertEquals(classWithIds1, classWithIds2); + Assert.assertEquals(personId, classWithIds2.personId); + Assert.assertSame(personId, classWithIds2.personId); } @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) private static record RecordWithIds( - @JsonPersonId Id personId, - @JsonLinkId Id linkId, - @JsonNodeId Id nodeId) { + @JsonId Id personId, + @JsonId Id linkId, + @JsonId Id nodeId) { }; @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) private static class ClassWithIds { - @JsonPersonId + @JsonId Id personId; - @JsonLinkId + @JsonId Id linkId; - @JsonNodeId + @JsonId Id nodeId; ClassWithIds() { diff --git a/matsim/src/test/java/org/matsim/api/core/v01/IdDeSerializationModuleTest.java b/matsim/src/test/java/org/matsim/api/core/v01/IdDeSerializationModuleTest.java new file mode 100644 index 00000000000..6550f16c2d4 --- /dev/null +++ b/matsim/src/test/java/org/matsim/api/core/v01/IdDeSerializationModuleTest.java @@ -0,0 +1,103 @@ +package org.matsim.api.core.v01; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.matsim.api.core.v01.network.Link; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.type.MapType; +import com.fasterxml.jackson.databind.type.TypeFactory; + +public class IdDeSerializationModuleTest { + + private static final TypeFactory TYPE_FACTORY = TypeFactory.defaultInstance(); + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Before + public void init() { + this.objectMapper.registerModule(IdDeSerializationModule.getInstance()); + } + + @Test + public void testMapKey() { + + // create map with Id as keys + Map, String> map0 = new LinkedHashMap<>(); + Id linkId0 = Id.createLinkId("0"); + Id linkId1 = Id.createLinkId("1"); + map0.put(linkId0, "a"); + map0.put(linkId1, "b"); + + // build writer + JavaType linkIdType = TYPE_FACTORY.constructParametricType(Id.class, Link.class); + MapType mapType = TYPE_FACTORY.constructMapType(Map.class, linkIdType, TYPE_FACTORY.constructType(String.class)); + ObjectWriter objectWriter = objectMapper.writerFor(mapType); + + // serialize + String s; + try { + s = objectWriter.writeValueAsString(map0); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + System.out.println(s); + Assert.assertEquals("{\"0\":\"a\",\"1\":\"b\"}", s); + + // deserialize + Map, String> map1; + try { + map1 = objectMapper.readValue(s, mapType); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + Assert.assertEquals(map0, map1); + Assert.assertEquals(linkId0, + map1.keySet().stream().filter(lId -> lId.equals(linkId0)).findFirst().orElseThrow()); + Assert.assertSame(linkId0, + map1.keySet().stream().filter(lId -> lId.equals(linkId0)).findFirst().orElseThrow()); + } + + @Test + public void testMapValue() { + + // create map with Id as values + Map> map0 = new LinkedHashMap<>(); + Id linkId0 = Id.createLinkId("0"); + map0.put("a", linkId0); + map0.put("b", Id.createLinkId("1")); + + // build writer + JavaType linkIdType = TYPE_FACTORY.constructParametricType(Id.class, Link.class); + MapType mapType = TypeFactory.defaultInstance().constructMapType(Map.class, TYPE_FACTORY.constructType(String.class), linkIdType); + ObjectWriter objectWriter = objectMapper.writerFor(mapType); + + // serialize + String s; + try { + s = objectWriter.writeValueAsString(map0); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + System.out.println(s); + Assert.assertEquals("{\"a\":\"0\",\"b\":\"1\"}", s); + + // deserialize + Map> map1; + try { + map1 = objectMapper.readValue(s, mapType); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + Assert.assertEquals(map0, map1); + Assert.assertEquals(linkId0, map1.get("a")); + Assert.assertSame(linkId0, map1.get("a")); + } + +} diff --git a/matsim/src/test/java/org/matsim/core/config/ConfigReaderMatsimV2Test.java b/matsim/src/test/java/org/matsim/core/config/ConfigReaderMatsimV2Test.java index 1e157d3bc05..af1a7d1a58b 100644 --- a/matsim/src/test/java/org/matsim/core/config/ConfigReaderMatsimV2Test.java +++ b/matsim/src/test/java/org/matsim/core/config/ConfigReaderMatsimV2Test.java @@ -2,7 +2,7 @@ import org.junit.Assert; import org.junit.Test; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; @@ -30,10 +30,32 @@ public void testModuleNameAlias() { """; ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - r2.addAlias("theController", ControlerConfigGroup.GROUP_NAME); + r2.getConfigAliases().addAlias("theController", ControllerConfigGroup.GROUP_NAME); r2.readStream(bais); - Assert.assertEquals(27, config.controler().getLastIteration()); + Assert.assertEquals(27, config.controller().getLastIteration()); + } + + @Test + public void testModuleNameAlias_noOldModules() { + Config config = ConfigUtils.createConfig(); + ConfigReaderMatsimV2 r2 = new ConfigReaderMatsimV2(config); + + String xml = """ + + + + + + + + """; + ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); + + r2.readStream(bais); + + Assert.assertEquals(27, config.controller().getLastIteration()); + Assert.assertNull(config.getModules().get("controler")); } @Test @@ -52,10 +74,10 @@ public void testParamNameAlias() { """; ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - r2.addAlias("theLastIteration", "lastIteration"); + r2.getConfigAliases().addAlias("theLastIteration", "lastIteration"); r2.readStream(bais); - Assert.assertEquals(23, config.controler().getLastIteration()); + Assert.assertEquals(23, config.controller().getLastIteration()); } @Test @@ -74,11 +96,44 @@ public void testModuleAndParamNameAlias() { """; ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - r2.addAlias("theController", ControlerConfigGroup.GROUP_NAME); - r2.addAlias("theLastIteration", "lastIteration"); + r2.getConfigAliases().addAlias("theController", ControllerConfigGroup.GROUP_NAME); + r2.getConfigAliases().addAlias("theLastIteration", "lastIteration"); r2.readStream(bais); - Assert.assertEquals(23, config.controler().getLastIteration()); + Assert.assertEquals(23, config.controller().getLastIteration()); + } + + /** + * Test that a parameter can be renamed inside a renamed module. + */ + @Test + public void testConditionalParamNameAliasWithModuleRenaming() { + Config config = ConfigUtils.createConfig(); + ConfigReaderMatsimV2 r2 = new ConfigReaderMatsimV2(config); + + String xml = """ + + + + + + + + + + + """; + ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); + + r2.getConfigAliases().addAlias("the_network", "network"); + r2.getConfigAliases().addAlias("the_plans", "plans"); + // for the path, the new name needs to be used: + r2.getConfigAliases().addAlias("input", "inputNetworkFile", "network"); + r2.getConfigAliases().addAlias("input", "inputPlansFile", "plans"); + r2.readStream(bais); + + Assert.assertEquals("my_network.xml.gz", config.network().getInputFile()); + Assert.assertEquals("my_plans.xml.gz", config.plans().getInputFile()); } /** @@ -104,8 +159,8 @@ public void testConditionalParamNameAlias() { """; ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - r2.addAlias("input", "inputNetworkFile", "network"); - r2.addAlias("input", "inputPlansFile", "plans"); + r2.getConfigAliases().addAlias("input", "inputNetworkFile", "network"); + r2.getConfigAliases().addAlias("input", "inputPlansFile", "plans"); r2.readStream(bais); Assert.assertEquals("my_network.xml.gz", config.network().getInputFile()); @@ -134,7 +189,7 @@ public void testConditionalParamNameAlias2() { """; ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - r2.addAlias("inputNetworkFile", "inputPlansFile", "plans"); + r2.getConfigAliases().addAlias("inputNetworkFile", "inputPlansFile", "plans"); r2.readStream(bais); Assert.assertEquals("my_network.xml.gz", config.network().getInputFile()); @@ -160,7 +215,7 @@ public void testConditionalParamNameAlias3() { """; ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - r2.addAlias("inputPlansFile", "input", "inexistant"); + r2.getConfigAliases().addAlias("inputPlansFile", "input", "inexistant"); r2.readStream(bais); // if the alias were matched, it should produce an exception, as "input" is not known Assert.assertEquals("my_plans.xml.gz", config.plans().getInputFile()); @@ -185,7 +240,7 @@ public void testConditionalParamNameAlias4() { """; ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - r2.addAlias("inputPlansFile", "input", "plans", "inexistant"); + r2.getConfigAliases().addAlias("inputPlansFile", "input", "plans", "inexistant"); r2.readStream(bais); // if the alias were matched, it should produce an exception, as "input" is not known Assert.assertEquals("my_plans.xml.gz", config.plans().getInputFile()); @@ -204,9 +259,9 @@ public void testAliasWithParamSets() { - + - + @@ -228,12 +283,13 @@ public void testAliasWithParamSets() { """; ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); - r2.addAlias("scoring", "planCalcScore"); - r2.addAlias("theLateArrival", "lateArrival", "planCalcScore", "scoringParameters"); - r2.addAlias("theMode", "mode", "planCalcScore", "scoringParameters", "modeParams"); + r2.getConfigAliases().clearAliases(); + r2.getConfigAliases().addAlias("planCalcScore", "scoring"); + r2.getConfigAliases().addAlias("theLateArrival", "lateArrival", "scoring", "scoringParameters"); + r2.getConfigAliases().addAlias("theMode", "mode", "scoring", "scoringParameters", "modeParams"); r2.readStream(bais); - Assert.assertEquals(-5.6, config.planCalcScore().getModes().get("car").getMarginalUtilityOfTraveling(), 1e-7); - Assert.assertEquals(-8.7, config.planCalcScore().getModes().get("unicycle").getMarginalUtilityOfTraveling(), 1e-7); + Assert.assertEquals(-5.6, config.scoring().getModes().get("car").getMarginalUtilityOfTraveling(), 1e-7); + Assert.assertEquals(-8.7, config.scoring().getModes().get("unicycle").getMarginalUtilityOfTraveling(), 1e-7); } } diff --git a/matsim/src/test/java/org/matsim/core/config/ReflectiveConfigGroupTest.java b/matsim/src/test/java/org/matsim/core/config/ReflectiveConfigGroupTest.java index fcc54693e19..a662f53d5ad 100644 --- a/matsim/src/test/java/org/matsim/core/config/ReflectiveConfigGroupTest.java +++ b/matsim/src/test/java/org/matsim/core/config/ReflectiveConfigGroupTest.java @@ -22,6 +22,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -61,6 +64,9 @@ public void testDumpAndRead() { dumpedModule.charField = 'z'; dumpedModule.byteField = 78; dumpedModule.booleanField = true; + dumpedModule.localTimeField = LocalTime.of(23, 59, 59); + dumpedModule.localDateField = LocalDate.of(2022, 12, 31); + dumpedModule.localDateTimeField = LocalDateTime.of(2022, 12, 31, 23, 59, 59); dumpedModule.enumListField = List.of(MyEnum.VALUE1, MyEnum.VALUE2); dumpedModule.enumSetField = Set.of(MyEnum.VALUE2); dumpedModule.setField = ImmutableSet.of("a", "b", "c"); @@ -154,6 +160,9 @@ public void testComments() { expectedComments.put("charField", "char"); expectedComments.put("byteField", "byte"); expectedComments.put("booleanField", "boolean"); + expectedComments.put("localTimeField", "local time"); + expectedComments.put("localDateField", "local date"); + expectedComments.put("localDateTimeField", "local datetime"); expectedComments.put("enumField", "Possible values: VALUE1,VALUE2"); expectedComments.put("enumListField", "list of enum"); expectedComments.put("enumSetField", "set of enum"); @@ -439,6 +448,18 @@ private static class MyModule extends ReflectiveConfigGroup { @Parameter private boolean booleanField; + @Comment("local time") + @Parameter + private LocalTime localTimeField; + + @Comment("local date") + @Parameter + private LocalDate localDateField; + + @Comment("local datetime") + @Parameter + private LocalDateTime localDateTimeField; + @Comment("set") @Parameter private Set setField; diff --git a/matsim/src/test/java/org/matsim/core/config/consistency/ConfigConsistencyCheckerImplTest.java b/matsim/src/test/java/org/matsim/core/config/consistency/ConfigConsistencyCheckerImplTest.java index 60ed86ec921..737607dae7d 100644 --- a/matsim/src/test/java/org/matsim/core/config/consistency/ConfigConsistencyCheckerImplTest.java +++ b/matsim/src/test/java/org/matsim/core/config/consistency/ConfigConsistencyCheckerImplTest.java @@ -25,7 +25,7 @@ import org.matsim.api.core.v01.TransportMode; 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.ScoringConfigGroup.ActivityParams; import org.matsim.pt.PtConstants; import org.matsim.testcases.utils.LogCounter; @@ -58,7 +58,7 @@ public void testCheckPlanCalcScore_Traveling() { Config config = new Config(); config.addCoreModules(); - config.planCalcScore().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(3.0); + config.scoring().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(3.0); LogCounter logger = new LogCounter(Level.WARN); try { @@ -76,7 +76,7 @@ public void testCheckPlanCalcScore_TravelingPt() { Config config = new Config(); config.addCoreModules(); - config.planCalcScore().getModes().get(TransportMode.pt).setMarginalUtilityOfTraveling(3.0); + config.scoring().getModes().get(TransportMode.pt).setMarginalUtilityOfTraveling(3.0); LogCounter logger = new LogCounter(Level.WARN); try { @@ -94,7 +94,7 @@ public void testCheckPlanCalcScore_TravelingBike() { Config config = new Config(); config.addCoreModules(); - config.planCalcScore().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(3.0); + config.scoring().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(3.0); LogCounter logger = new LogCounter(Level.WARN); try { @@ -112,7 +112,7 @@ public void testCheckPlanCalcScore_TravelingWalk() { Config config = new Config(); config.addCoreModules(); - config.planCalcScore().getModes().get(TransportMode.walk).setMarginalUtilityOfTraveling(3.0); + config.scoring().getModes().get(TransportMode.walk).setMarginalUtilityOfTraveling(3.0); LogCounter logger = new LogCounter(Level.WARN); try { @@ -124,7 +124,7 @@ public void testCheckPlanCalcScore_TravelingWalk() { logger.deactivate(); } } - + @Test public void testCheckPlanCalcScore_PtInteractionActivity() { Config config = new Config(); @@ -132,24 +132,24 @@ public void testCheckPlanCalcScore_PtInteractionActivity() { ActivityParams transitActivityParams = new ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); transitActivityParams.setClosingTime(1.) ; - config.planCalcScore().addActivityParams(transitActivityParams); + config.scoring().addActivityParams(transitActivityParams); try { ConfigConsistencyCheckerImpl.checkPlanCalcScore(config); Assert.assertEquals(0,1) ; // should never get here } catch ( Exception ee ){ - + System.out.println("expected exception") ; } - + config.vspExperimental().setAbleToOverwritePtInteractionParams(true) ; - + try { ConfigConsistencyCheckerImpl.checkPlanCalcScore(config ); } catch ( Exception ee ){ Assert.assertEquals(0,1) ; // should never get here } - + } @@ -165,9 +165,9 @@ public void checkConsistencyBetweenRouterAndTravelTimeCalculatorTest(){ Assert.assertFalse( problem ); } { - Set modes = new LinkedHashSet<>( config.plansCalcRoute().getNetworkModes() ); + Set modes = new LinkedHashSet<>( config.routing().getNetworkModes() ); modes.add( TransportMode.bike ); - config.plansCalcRoute().setNetworkModes( modes ); + config.routing().setNetworkModes( modes ); boolean problem = ConfigConsistencyCheckerImpl.checkConsistencyBetweenRouterAndTravelTimeCalculator( config ); Assert.assertFalse( problem ); @@ -199,9 +199,9 @@ public void checkConsistencyBetweenRouterAndTravelTimeCalculatorTest(){ ConfigConsistencyCheckerImpl.checkConsistencyBetweenRouterAndTravelTimeCalculator( config ); { - Set modes = new LinkedHashSet<>( config.plansCalcRoute().getNetworkModes() ); + Set modes = new LinkedHashSet<>( config.routing().getNetworkModes() ); modes.add( TransportMode.bike ); - config.plansCalcRoute().setNetworkModes( modes ); + config.routing().setNetworkModes( modes ); boolean problem = ConfigConsistencyCheckerImpl.checkConsistencyBetweenRouterAndTravelTimeCalculator( config ); // see comments inside that static function. kai, jul'19 diff --git a/matsim/src/test/java/org/matsim/core/config/groups/ControlerConfigGroupTest.java b/matsim/src/test/java/org/matsim/core/config/groups/ControllerConfigGroupTest.java similarity index 77% rename from matsim/src/test/java/org/matsim/core/config/groups/ControlerConfigGroupTest.java rename to matsim/src/test/java/org/matsim/core/config/groups/ControllerConfigGroupTest.java index 4b479ad330c..a1c50b1d46f 100644 --- a/matsim/src/test/java/org/matsim/core/config/groups/ControlerConfigGroupTest.java +++ b/matsim/src/test/java/org/matsim/core/config/groups/ControllerConfigGroupTest.java @@ -25,9 +25,9 @@ import org.junit.Assert; import org.junit.Test; -import org.matsim.core.config.groups.ControlerConfigGroup.EventsFileFormat; +import org.matsim.core.config.groups.ControllerConfigGroup.EventsFileFormat; -public class ControlerConfigGroupTest { +public class ControllerConfigGroupTest { /** * Ensure that the events-file-format is correctly stored @@ -37,46 +37,46 @@ public class ControlerConfigGroupTest { */ @Test public void testEventsFileFormat() { - ControlerConfigGroup cg = new ControlerConfigGroup(); + ControllerConfigGroup cg = new ControllerConfigGroup(); Set formats; // test initial value formats = cg.getEventsFileFormats(); Assert.assertEquals(1, formats.size()); Assert.assertTrue(formats.contains(EventsFileFormat.xml)); - Assert.assertEquals("xml", cg.getValue(ControlerConfigGroup.EVENTS_FILE_FORMAT)); + Assert.assertEquals("xml", cg.getValue(ControllerConfigGroup.EVENTS_FILE_FORMAT)); // test setting with setEventsFileFormat cg.setEventsFileFormats(EnumSet.of(EventsFileFormat.xml)); formats = cg.getEventsFileFormats(); Assert.assertEquals(1, formats.size()); Assert.assertTrue(formats.contains(EventsFileFormat.xml)); - Assert.assertEquals("xml", cg.getValue(ControlerConfigGroup.EVENTS_FILE_FORMAT)); + Assert.assertEquals("xml", cg.getValue(ControllerConfigGroup.EVENTS_FILE_FORMAT)); // test setting to none cg.setEventsFileFormats(EnumSet.noneOf(EventsFileFormat.class)); formats = cg.getEventsFileFormats(); Assert.assertEquals(0, formats.size()); - Assert.assertEquals("", cg.getValue(ControlerConfigGroup.EVENTS_FILE_FORMAT)); + Assert.assertEquals("", cg.getValue(ControllerConfigGroup.EVENTS_FILE_FORMAT)); // test setting with addParam - cg.addParam(ControlerConfigGroup.EVENTS_FILE_FORMAT, "xml"); + cg.addParam(ControllerConfigGroup.EVENTS_FILE_FORMAT, "xml"); formats = cg.getEventsFileFormats(); Assert.assertEquals(1, formats.size()); Assert.assertTrue(formats.contains(EventsFileFormat.xml)); - Assert.assertEquals("xml", cg.getValue(ControlerConfigGroup.EVENTS_FILE_FORMAT)); + Assert.assertEquals("xml", cg.getValue(ControllerConfigGroup.EVENTS_FILE_FORMAT)); // test setting to none - cg.addParam(ControlerConfigGroup.EVENTS_FILE_FORMAT, ""); + cg.addParam(ControllerConfigGroup.EVENTS_FILE_FORMAT, ""); formats = cg.getEventsFileFormats(); Assert.assertEquals(0, formats.size()); - Assert.assertEquals("", cg.getValue(ControlerConfigGroup.EVENTS_FILE_FORMAT)); + Assert.assertEquals("", cg.getValue(ControllerConfigGroup.EVENTS_FILE_FORMAT)); // test setting with non-conform formatting - cg.addParam(ControlerConfigGroup.EVENTS_FILE_FORMAT, " xml\t\t "); + cg.addParam(ControllerConfigGroup.EVENTS_FILE_FORMAT, " xml\t\t "); formats = cg.getEventsFileFormats(); Assert.assertEquals(1, formats.size()); Assert.assertTrue(formats.contains(EventsFileFormat.xml)); - Assert.assertEquals("xml", cg.getValue(ControlerConfigGroup.EVENTS_FILE_FORMAT)); + Assert.assertEquals("xml", cg.getValue(ControllerConfigGroup.EVENTS_FILE_FORMAT)); // test setting to non-conform none - cg.addParam(ControlerConfigGroup.EVENTS_FILE_FORMAT, " \t "); + cg.addParam(ControllerConfigGroup.EVENTS_FILE_FORMAT, " \t "); formats = cg.getEventsFileFormats(); Assert.assertEquals(0, formats.size()); - Assert.assertEquals("", cg.getValue(ControlerConfigGroup.EVENTS_FILE_FORMAT)); + Assert.assertEquals("", cg.getValue(ControllerConfigGroup.EVENTS_FILE_FORMAT)); } /** @@ -87,18 +87,18 @@ public void testEventsFileFormat() { */ @Test public void testMobsim() { - ControlerConfigGroup cg = new ControlerConfigGroup(); + ControllerConfigGroup cg = new ControllerConfigGroup(); // test initial value Assert.assertEquals("qsim", cg.getMobsim()); - Assert.assertEquals("qsim", cg.getValue(ControlerConfigGroup.MOBSIM)); + Assert.assertEquals("qsim", cg.getValue(ControllerConfigGroup.MOBSIM)); // test setting to null cg.setMobsim(null); Assert.assertNull(cg.getMobsim()); - Assert.assertNull(cg.getValue(ControlerConfigGroup.MOBSIM)); + Assert.assertNull(cg.getValue(ControllerConfigGroup.MOBSIM)); // test setting with addParam - cg.addParam(ControlerConfigGroup.MOBSIM, "queueSimulation"); + cg.addParam(ControllerConfigGroup.MOBSIM, "queueSimulation"); Assert.assertEquals("queueSimulation", cg.getMobsim()); - Assert.assertEquals("queueSimulation", cg.getValue(ControlerConfigGroup.MOBSIM)); + Assert.assertEquals("queueSimulation", cg.getValue(ControllerConfigGroup.MOBSIM)); } /** @@ -109,7 +109,7 @@ public void testMobsim() { */ @Test public void testWritePlansInterval() { - ControlerConfigGroup cg = new ControlerConfigGroup(); + ControllerConfigGroup cg = new ControllerConfigGroup(); // test initial value Assert.assertEquals(50, cg.getWritePlansInterval()); // test setting with setMobsim @@ -121,12 +121,12 @@ public void testWritePlansInterval() { } /** - * Ensure that the enableLinkToLinkRouting value is correctly stored and + * Ensure that the enableLinkToLinkRouting value is correctly stored and * returned with the getters and setters. */ @Test public void testLink2LinkRouting(){ - ControlerConfigGroup cg = new ControlerConfigGroup(); + ControllerConfigGroup cg = new ControllerConfigGroup(); //initial value Assert.assertFalse(cg.isLinkToLinkRoutingEnabled()); //modify by string @@ -144,12 +144,12 @@ public void testLink2LinkRouting(){ } /** - * Ensure that the writeSnapshotsInterval value is correctly stored and + * Ensure that the writeSnapshotsInterval value is correctly stored and * returned with the getters and setters. */ @Test public void testWriteSnapshotInterval(){ - ControlerConfigGroup cg = new ControlerConfigGroup(); + ControllerConfigGroup cg = new ControllerConfigGroup(); //initial value Assert.assertEquals(1, cg.getWriteSnapshotsInterval()); //modify by string @@ -161,5 +161,5 @@ public void testWriteSnapshotInterval(){ Assert.assertEquals(42, cg.getWriteSnapshotsInterval()); } - + } diff --git a/matsim/src/test/java/org/matsim/core/config/groups/StrategyConfigGroupTest.java b/matsim/src/test/java/org/matsim/core/config/groups/ReplanningConfigGroupTest.java similarity index 91% rename from matsim/src/test/java/org/matsim/core/config/groups/StrategyConfigGroupTest.java rename to matsim/src/test/java/org/matsim/core/config/groups/ReplanningConfigGroupTest.java index 42d60cd29ed..17409e3ec33 100644 --- a/matsim/src/test/java/org/matsim/core/config/groups/StrategyConfigGroupTest.java +++ b/matsim/src/test/java/org/matsim/core/config/groups/ReplanningConfigGroupTest.java @@ -35,17 +35,17 @@ import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.ConfigWriter; import org.matsim.core.config.ConfigReader; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.testcases.MatsimTestUtils; /** - * Test for {@link StrategyConfigGroup}. + * Test for {@link ReplanningConfigGroup}. * * @author mrieser */ -public class StrategyConfigGroupTest { +public class ReplanningConfigGroupTest { - private static final Logger log = LogManager.getLogger(StrategyConfigGroupTest.class); + private static final Logger log = LogManager.getLogger(ReplanningConfigGroupTest.class); @Rule public final MatsimTestUtils utils = new MatsimTestUtils(); @@ -56,7 +56,7 @@ public class StrategyConfigGroupTest { */ @Test public void testParamNames() { - StrategyConfigGroup configGroup = new StrategyConfigGroup(); + ReplanningConfigGroup configGroup = new ReplanningConfigGroup(); configGroup.addParam("maxAgentPlanMemorySize", "3"); configGroup.addParam("Module_1", "ReRoute"); configGroup.addParam("ModuleProbability_1", "0.5"); @@ -81,7 +81,7 @@ public void testParamNames() { @Test public void testCheckConsistency() { // start with a simple configuration with exactly one module defined - StrategyConfigGroup configGroup = new StrategyConfigGroup(); + ReplanningConfigGroup configGroup = new ReplanningConfigGroup(); configGroup.addParam("maxAgentPlanMemorySize", "3"); configGroup.addParam("Module_1", "ReRoute"); configGroup.addParam("ModuleProbability_1", "0.5"); @@ -149,7 +149,7 @@ public void testCheckConsistency() { @Test public void testIOWithFormatChange() { - final StrategyConfigGroup initialGroup = createTestConfigGroup(); + final ReplanningConfigGroup initialGroup = createTestConfigGroup(); final String v1path = utils.getOutputDirectory() + "/configv1_out.xml"; final Config configV1 = new Config(); @@ -160,7 +160,7 @@ public void testIOWithFormatChange() { final Config configV1In = ConfigUtils.createConfig(); new ConfigReader( configV1In ).readFile( v1path ); - assertIdentical("re-read v1", initialGroup, configV1In.strategy()); + assertIdentical("re-read v1", initialGroup, configV1In.replanning()); final String v2path = utils.getOutputDirectory() + "/configv2_out.xml"; @@ -169,13 +169,13 @@ public void testIOWithFormatChange() { final Config configV2 = ConfigUtils.createConfig(); new ConfigReader( configV2 ).readFile( v2path ); - assertIdentical("re-read v2", initialGroup, configV2.strategy()); + assertIdentical("re-read v2", initialGroup, configV2.replanning()); } private void assertIdentical( final String msg, - final StrategyConfigGroup initialGroup, - final StrategyConfigGroup inputConfigGroup) { + final ReplanningConfigGroup initialGroup, + final ReplanningConfigGroup inputConfigGroup) { assertEquals( "wrong config template for "+msg, initialGroup.getExternalExeConfigTemplate(), @@ -213,10 +213,10 @@ private void assertIdentical( inputConfigGroup.getStrategySettings().size() ); } - private ConfigGroup toUnderscoredModule(final StrategyConfigGroup initialGroup) { + private ConfigGroup toUnderscoredModule(final ReplanningConfigGroup initialGroup) { // yyyy is this method/this execution path still necessary? Maybe we need to be able to read config v1, but certainly // we don't need to WRITE it, do we? kai/mz, nov'15 - + final ConfigGroup module = new ConfigGroup( initialGroup.getName() ); for ( Map.Entry e : initialGroup.getParams().entrySet() ) { @@ -236,8 +236,8 @@ private ConfigGroup toUnderscoredModule(final StrategyConfigGroup initialGroup) return module; } - private StrategyConfigGroup createTestConfigGroup() { - final StrategyConfigGroup group = new StrategyConfigGroup(); + private ReplanningConfigGroup createTestConfigGroup() { + final ReplanningConfigGroup group = new ReplanningConfigGroup(); group.setExternalExeConfigTemplate( "bwark" ); group.setExternalExeTimeOut( 999 ); group.setExternalExeTmpFileRootDir( "some/random/location" ); diff --git a/matsim/src/test/java/org/matsim/core/config/groups/PlansCalcRouteConfigGroupTest.java b/matsim/src/test/java/org/matsim/core/config/groups/RoutingConfigGroupTest.java similarity index 86% rename from matsim/src/test/java/org/matsim/core/config/groups/PlansCalcRouteConfigGroupTest.java rename to matsim/src/test/java/org/matsim/core/config/groups/RoutingConfigGroupTest.java index 86847b25448..7b765cd84bb 100644 --- a/matsim/src/test/java/org/matsim/core/config/groups/PlansCalcRouteConfigGroupTest.java +++ b/matsim/src/test/java/org/matsim/core/config/groups/RoutingConfigGroupTest.java @@ -33,11 +33,11 @@ import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.ConfigWriter; import org.matsim.core.config.ConfigReader; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.TeleportedModeParams; +import org.matsim.core.config.groups.RoutingConfigGroup.TeleportedModeParams; import org.matsim.testcases.MatsimTestUtils; -public class PlansCalcRouteConfigGroupTest { - private final static Logger log = LogManager.getLogger(PlansCalcRouteConfigGroupTest.class); +public class RoutingConfigGroupTest { + private final static Logger log = LogManager.getLogger(RoutingConfigGroupTest.class); private final static int N_MODE_ROUTING_PARAMS_DEFAULT = 5 ; @Rule @@ -49,7 +49,7 @@ public void testAddModeParamsTwice() { final String filename = outdir + "config.xml"; { Config config = ConfigUtils.createConfig(); - PlansCalcRouteConfigGroup group = config.plansCalcRoute(); + RoutingConfigGroup group = config.routing(); Assert.assertEquals( N_MODE_ROUTING_PARAMS_DEFAULT, group.getModeRoutingParams().size() ); group.clearModeRoutingParams(); // group.setTeleportedModeSpeed( TransportMode.bike, 1. ); @@ -63,7 +63,7 @@ public void testAddModeParamsTwice() { } { Config config = ConfigUtils.loadConfig( filename ) ; - PlansCalcRouteConfigGroup group = config.plansCalcRoute(); + RoutingConfigGroup group = config.routing(); Assert.assertEquals( 0, group.getModeRoutingParams().size() ); } } @@ -73,7 +73,7 @@ public void testClearParamsWriteRead() { final String filename = outdir + "config.xml"; { Config config = ConfigUtils.createConfig(); - PlansCalcRouteConfigGroup group = config.plansCalcRoute(); + RoutingConfigGroup group = config.routing(); Assert.assertEquals( N_MODE_ROUTING_PARAMS_DEFAULT, group.getModeRoutingParams().size() ); group.clearModeRoutingParams(); group.setTeleportedModeSpeed( TransportMode.bike, 1. ); @@ -87,7 +87,7 @@ public void testClearParamsWriteRead() { } { Config config = ConfigUtils.loadConfig( filename ) ; - PlansCalcRouteConfigGroup group = config.plansCalcRoute(); + RoutingConfigGroup group = config.routing(); Assert.assertEquals( 0, group.getModeRoutingParams().size() ); } } @@ -97,7 +97,7 @@ public void testRemoveParamsWriteRead() { final String filename = outdir + "config.xml"; { Config config = ConfigUtils.createConfig(); - PlansCalcRouteConfigGroup group = config.plansCalcRoute(); + RoutingConfigGroup group = config.routing(); Assert.assertEquals( N_MODE_ROUTING_PARAMS_DEFAULT, group.getModeRoutingParams().size() ); group.setTeleportedModeSpeed( TransportMode.bike, 1. ); Assert.assertEquals( 1, group.getModeRoutingParams().size() ); @@ -112,14 +112,14 @@ public void testRemoveParamsWriteRead() { } { Config config = ConfigUtils.loadConfig( filename ) ; - PlansCalcRouteConfigGroup group = config.plansCalcRoute(); + RoutingConfigGroup group = config.routing(); Assert.assertEquals( 0, group.getModeRoutingParams().size() ); } } @Test public void testClearDefaults() { Config config = ConfigUtils.createConfig( ) ; - PlansCalcRouteConfigGroup group = config.plansCalcRoute() ; + RoutingConfigGroup group = config.routing() ; Assert.assertEquals( N_MODE_ROUTING_PARAMS_DEFAULT, group.getModeRoutingParams().size() ); group.setTeleportedModeSpeed( "def", 1. ); Assert.assertEquals( 1, group.getModeRoutingParams().size() ); @@ -131,20 +131,20 @@ public void testClearDefaults() { @Test public void test3() { Config config = ConfigUtils.createConfig( ) ; - PlansCalcRouteConfigGroup group = config.plansCalcRoute() ; + RoutingConfigGroup group = config.routing() ; group.clearModeRoutingParams(); group.setClearingDefaultModeRoutingParams( true ); // should be ok } @Test( expected = RuntimeException.class ) public void testInconsistencyBetweenActionAndState() { - PlansCalcRouteConfigGroup group = new PlansCalcRouteConfigGroup() ; + RoutingConfigGroup group = new RoutingConfigGroup() ; group.clearModeRoutingParams(); group.setClearingDefaultModeRoutingParams( false ); // should fail } @Test public void testBackwardsCompatibility() { - PlansCalcRouteConfigGroup group = new PlansCalcRouteConfigGroup(); + RoutingConfigGroup group = new RoutingConfigGroup(); // test default Assert.assertEquals("different default than expected.", 3.0 / 3.6, group.getTeleportedModeSpeeds().get(TransportMode.walk), MatsimTestUtils.EPSILON); @@ -162,7 +162,7 @@ public void testBackwardsCompatibility() { @Test public void testDefaultsAreCleared() { - PlansCalcRouteConfigGroup group = new PlansCalcRouteConfigGroup(); + RoutingConfigGroup group = new RoutingConfigGroup(); // group.clearModeRoutingParams(); group.setTeleportedModeSpeed( "skateboard" , 20 / 3.6 ); group.setTeleportedModeSpeed( "longboard" , 20 / 3.6 ); @@ -173,9 +173,9 @@ public void testDefaultsAreCleared() { } @Test - public void testIODifferentVersions() + public void testIODifferentVersions() { - final PlansCalcRouteConfigGroup initialGroup = createTestConfigGroup(); + final RoutingConfigGroup initialGroup = createTestConfigGroup(); log.info( "constructing new config ..."); final Config configV1 = new Config(); @@ -197,7 +197,7 @@ public void testIODifferentVersions() log.info("... done reading file into new config.") ; log.info( "asserting ..."); - assertIdentical("re-read v1", initialGroup, configV1In.plansCalcRoute()); + assertIdentical("re-read v1", initialGroup, configV1In.routing()); log.info( "... done asserting.") ; final String v2path = utils.getOutputDirectory() + "/configv2_out.xml"; @@ -207,15 +207,15 @@ public void testIODifferentVersions() final Config configV2 = ConfigUtils.createConfig(); new ConfigReader( configV2 ).readFile( v2path ); - assertIdentical("re-read v2", initialGroup, configV2.plansCalcRoute()); + assertIdentical("re-read v2", initialGroup, configV2.routing()); } - + @Test( expected=RuntimeException.class ) public void testConsistencyCheckIfNoTeleportedSpeed() { final Config config = ConfigUtils.createConfig(); final TeleportedModeParams params = new TeleportedModeParams( "skateboard" ); - config.plansCalcRoute().addModeRoutingParams( params ); + config.routing().addModeRoutingParams( params ); // (one needs to set one of the teleported speed settings) config.checkConsistency(); @@ -237,8 +237,8 @@ public void testCannotAddFactorAfterSpeed() { private static void assertIdentical( final String msg, - final PlansCalcRouteConfigGroup initialGroup, - final PlansCalcRouteConfigGroup inputConfigGroup) { + final RoutingConfigGroup initialGroup, + final RoutingConfigGroup inputConfigGroup) { Assert.assertEquals( "unexpected beelineDistanceFactor", // initialGroup.getBeelineDistanceFactor(), @@ -260,14 +260,14 @@ private static void assertIdentical( inputConfigGroup.getTeleportedModeSpeeds() ); } - private static ConfigGroup toUnderscoredModule(final PlansCalcRouteConfigGroup initialGroup) { + private static ConfigGroup toUnderscoredModule(final RoutingConfigGroup initialGroup) { final ConfigGroup module = new ConfigGroup( initialGroup.getName() ); for ( Map.Entry e : initialGroup.getParams().entrySet() ) { log.info( "add param="+e.getKey() + " with value=" + e.getValue() ); module.addParam( e.getKey() , e.getValue() ); } - + for ( TeleportedModeParams settings : initialGroup.getModeRoutingParams().values() ) { final String mode = settings.getMode(); module.addParam( "teleportedModeSpeed_"+mode , ""+settings.getTeleportedModeSpeed() ); @@ -283,23 +283,23 @@ private static ConfigGroup toUnderscoredModule(final PlansCalcRouteConfigGroup i } else if ( !settings.getBeelineDistanceFactor().equals( val ) ) { throw new RuntimeException( "beeline distance factor varies by mode; this cannot be covered by this test" ) ; } - } + } module.addParam( "beelineDistanceFactor", ""+val ); - + return module; } - private static PlansCalcRouteConfigGroup createTestConfigGroup() { - log.info( "creating test config group ... "); - - final PlansCalcRouteConfigGroup group = new PlansCalcRouteConfigGroup(); + private static RoutingConfigGroup createTestConfigGroup() { + log.info( "creating test config group ... "); + + final RoutingConfigGroup group = new RoutingConfigGroup(); group.setNetworkModes( Arrays.asList( "electricity" , "water_supply" ) ); // two modes with only one speed group.setTeleportedModeFreespeedFactor( "inline skate" , 0.1 ); // group.getModeRoutingParams().get("inline skate").setBeelineDistanceFactor( 10000000. ); - + group.setTeleportedModeSpeed( "ice skates" , 10 ); // group.getModeRoutingParams().get("ice skates").setBeelineDistanceFactor( 10000000. ); @@ -310,7 +310,7 @@ private static PlansCalcRouteConfigGroup createTestConfigGroup() { //group.setTeleportedModeFreespeedFactor( "overboard" , 100 ); //group.setTeleportedModeSpeed( "overboard" , 999 ); - log.info( "... done creating test config group."); + log.info( "... done creating test config group."); return group; } } diff --git a/matsim/src/test/java/org/matsim/core/config/groups/PlanCalcScoreConfigGroupTest.java b/matsim/src/test/java/org/matsim/core/config/groups/ScoringConfigGroupTest.java similarity index 92% rename from matsim/src/test/java/org/matsim/core/config/groups/PlanCalcScoreConfigGroupTest.java rename to matsim/src/test/java/org/matsim/core/config/groups/ScoringConfigGroupTest.java index 95dfb44e7cf..16e7f336a44 100644 --- a/matsim/src/test/java/org/matsim/core/config/groups/PlanCalcScoreConfigGroupTest.java +++ b/matsim/src/test/java/org/matsim/core/config/groups/ScoringConfigGroupTest.java @@ -21,7 +21,7 @@ package org.matsim.core.config.groups; -import static org.matsim.core.config.groups.PlanCalcScoreConfigGroup.createStageActivityType; +import static org.matsim.core.config.groups.ScoringConfigGroup.createStageActivityType; import java.util.Map; import java.util.Random; @@ -37,19 +37,19 @@ import org.matsim.core.config.ConfigReader; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.ConfigWriter; -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.testcases.MatsimTestUtils; -public class PlanCalcScoreConfigGroupTest { +public class ScoringConfigGroupTest { private static final Logger log = - LogManager.getLogger(PlanCalcScoreConfigGroupTest.class); + LogManager.getLogger(ScoringConfigGroupTest.class); @Rule public final MatsimTestUtils utils = new MatsimTestUtils(); private void testResultsBeforeCheckConsistency( Config config, boolean fullyHierarchical ) { - PlanCalcScoreConfigGroup scoringConfig = config.planCalcScore() ; + ScoringConfigGroup scoringConfig = config.scoring() ; if ( ! fullyHierarchical ){ // mode params are there for default modes: @@ -70,10 +70,10 @@ private void testResultsBeforeCheckConsistency( Config config, boolean fullyHier // } } private void testResultsAfterCheckConsistency( Config config ) { - PlanCalcScoreConfigGroup scoringConfig = config.planCalcScore() ; + ScoringConfigGroup scoringConfig = config.scoring() ; // default stage/interaction params for modes routed on the network are now there: - for( String networkMode : config.plansCalcRoute().getNetworkModes() ){ + for( String networkMode : config.routing().getNetworkModes() ){ Assert.assertNotNull( scoringConfig.getActivityParams( createStageActivityType( networkMode ) ) ); } } @@ -81,7 +81,7 @@ private void testResultsAfterCheckConsistency( Config config ) { @Test public void testFullyHierarchicalVersion() { Config config = ConfigUtils.loadConfig( utils.getClassInputDirectory() + "config_v2_w_scoringparams.xml" ) ; - PlanCalcScoreConfigGroup scoringConfig = config.planCalcScore() ; + ScoringConfigGroup scoringConfig = config.scoring() ; testResultsBeforeCheckConsistency( config, true ) ; log.warn( "" ); for( ModeParams modeParams : scoringConfig.getModes().values() ){ @@ -93,7 +93,7 @@ public void testFullyHierarchicalVersion() { } log.warn( "" ); log.warn( "checking consistency ..." ); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); scoringConfig.checkConsistency( config ); testResultsAfterCheckConsistency( config ); log.warn( "" ); @@ -109,7 +109,7 @@ public void testFullyHierarchicalVersion() { @Test public void testVersionWoScoringparams() { Config config = ConfigUtils.loadConfig( utils.getClassInputDirectory() + "config_v2_wo_scoringparams.xml" ) ; - PlanCalcScoreConfigGroup scoringConfig = config.planCalcScore() ; + ScoringConfigGroup scoringConfig = config.scoring() ; testResultsBeforeCheckConsistency( config, false ) ; log.warn( "" ); for( ModeParams modeParams : scoringConfig.getModes().values() ){ @@ -121,7 +121,7 @@ public void testVersionWoScoringparams() { } log.warn( "" ); log.warn( "checking consistency ..." ); - config.plansCalcRoute().setAccessEgressType( PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.routing().setAccessEgressType( RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); scoringConfig.checkConsistency( config ); testResultsAfterCheckConsistency( config ); log.warn( "" ); @@ -137,7 +137,7 @@ public void testVersionWoScoringparams() { @Test public void testAddActivityParams() { - PlanCalcScoreConfigGroup c = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup c = new ScoringConfigGroup(); int originalSize = c.getActivityParams().size(); Assert.assertNull(c.getActivityParams("type1")); Assert.assertEquals(originalSize, c.getActivityParams().size()); @@ -150,7 +150,7 @@ public void testAddActivityParams() { @Test public void testIODifferentVersions() { - final PlanCalcScoreConfigGroup initialGroup = createTestConfigGroup(); + final ScoringConfigGroup initialGroup = createTestConfigGroup(); final String v1path = utils.getOutputDirectory() + "/configv1_out.xml"; final Config configV1 = new Config(); @@ -161,7 +161,7 @@ public void testIODifferentVersions() { final Config configV1In = ConfigUtils.createConfig(); new ConfigReader( configV1In ).readFile( v1path ); - assertIdentical("re-read v1", initialGroup, configV1In.planCalcScore()); + assertIdentical("re-read v1", initialGroup, configV1In.scoring()); final String v2path = utils.getOutputDirectory() + "/configv2_out.xml"; @@ -170,13 +170,13 @@ public void testIODifferentVersions() { final Config configV2 = ConfigUtils.createConfig(); new ConfigReader( configV2 ).readFile( v2path ); - assertIdentical("re-read v2", initialGroup, configV2.planCalcScore()); + assertIdentical("re-read v2", initialGroup, configV2.scoring()); } private void assertIdentical( final String msg, - final PlanCalcScoreConfigGroup initialGroup, - final PlanCalcScoreConfigGroup inputConfigGroup) { + final ScoringConfigGroup initialGroup, + final ScoringConfigGroup inputConfigGroup) { Assert.assertEquals( "wrong brainExpBeta "+msg, initialGroup.getBrainExpBeta(), @@ -359,7 +359,7 @@ private void assertIdentical( } - private static ConfigGroup toUnderscoredModule(final PlanCalcScoreConfigGroup initialGroup) { + private static ConfigGroup toUnderscoredModule(final ScoringConfigGroup initialGroup) { final ConfigGroup module = new ConfigGroup( initialGroup.getName() ); for ( Map.Entry e : initialGroup.getParams().entrySet() ) { @@ -401,8 +401,8 @@ private static ConfigGroup toUnderscoredModule(final PlanCalcScoreConfigGroup in return module; } - private PlanCalcScoreConfigGroup createTestConfigGroup() { - final PlanCalcScoreConfigGroup group = new PlanCalcScoreConfigGroup(); + private ScoringConfigGroup createTestConfigGroup() { + final ScoringConfigGroup group = new ScoringConfigGroup(); group.setBrainExpBeta( 124); group.getModes().get(TransportMode.bike).setConstant((double) 98); diff --git a/matsim/src/test/java/org/matsim/core/controler/AbstractModuleTest.java b/matsim/src/test/java/org/matsim/core/controler/AbstractModuleTest.java index 98f682623db..ae3c97c0a8e 100644 --- a/matsim/src/test/java/org/matsim/core/controler/AbstractModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/AbstractModuleTest.java @@ -28,7 +28,7 @@ public class AbstractModuleTest{ public void test1() { Config config = ConfigUtils.createConfig() ; - config.controler().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); Scenario scenario = ScenarioUtils.loadScenario( config ) ; diff --git a/matsim/src/test/java/org/matsim/core/controler/ControlerEventsTest.java b/matsim/src/test/java/org/matsim/core/controler/ControlerEventsTest.java index 4dae7008bee..4a696e4e606 100644 --- a/matsim/src/test/java/org/matsim/core/controler/ControlerEventsTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/ControlerEventsTest.java @@ -107,7 +107,7 @@ private static class TestController extends AbstractController { public TestController(Config config) { this.config = config; - super.setupOutputDirectory(new OutputDirectoryHierarchy(config.controler())); + super.setupOutputDirectory(new OutputDirectoryHierarchy(config.controller())); } @Override @@ -131,12 +131,12 @@ protected void prepareForMobsim() { @Override protected boolean mayTerminateAfterIteration(int iteration) { - return iteration >= config.controler().getLastIteration(); + return iteration >= config.controller().getLastIteration(); } @Override protected boolean shouldTerminate(int iteration) { - return iteration >= config.controler().getLastIteration(); + return iteration >= config.controller().getLastIteration(); } } diff --git a/matsim/src/test/java/org/matsim/core/controler/ControlerIT.java b/matsim/src/test/java/org/matsim/core/controler/ControlerIT.java index 41a7370e3f9..a0c6bc24154 100644 --- a/matsim/src/test/java/org/matsim/core/controler/ControlerIT.java +++ b/matsim/src/test/java/org/matsim/core/controler/ControlerIT.java @@ -21,8 +21,8 @@ package org.matsim.core.controler; import static org.junit.Assert.*; -import static org.matsim.core.config.groups.ControlerConfigGroup.CompressionType; -import static org.matsim.core.config.groups.ControlerConfigGroup.SnapshotFormat; +import static org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; +import static org.matsim.core.config.groups.ControllerConfigGroup.SnapshotFormat; import java.io.File; import java.util.ArrayList; @@ -54,12 +54,12 @@ import org.matsim.api.core.v01.population.PopulationFactory; 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.ControlerConfigGroup.EventsFileFormat; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup.EventsFileFormat; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup.SnapshotStyle; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.mobsim.framework.Mobsim; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.routes.NetworkRoute; @@ -82,26 +82,26 @@ public class ControlerIT { @Rule public MatsimTestUtils utils = new MatsimTestUtils(); private final boolean isUsingFastCapacityUpdate; - + public ControlerIT(boolean isUsingFastCapacityUpdate) { this.isUsingFastCapacityUpdate = isUsingFastCapacityUpdate; } - + @Parameters(name = "{index}: isUsingfastCapacityUpdate == {0}") public static Collection parameterObjects () { Object [] capacityUpdates = new Object [] { false, true }; return Arrays.asList(capacityUpdates); // yyyy I am not sure why it is doing this ... it is necessary to do this around the qsim, but why here? kai, aug'16 } - + @Test public void testScenarioLoading() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); Controler controler = new Controler( config ); // need to run the controler to get Scenario initilized - controler.getConfig().controler().setLastIteration( 0 ); - controler.getConfig().controler().setCleanItersAtEnd(ControlerConfigGroup.CleanIterations.keep); + controler.getConfig().controller().setLastIteration( 0 ); + controler.getConfig().controller().setCleanItersAtEnd(ControllerConfigGroup.CleanIterations.keep); controler.run(); assertNotNull(controler.getScenario().getNetwork()); // is required, e.g. for changing the factories @@ -115,7 +115,7 @@ public void testScenarioLoading() { @Test public void testTerminationCriterion() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Controler controler = new Controler(config); controler.setTerminationCriterion(new TerminationCriterion() { @Override @@ -136,13 +136,13 @@ public void testConstructor_EventsManagerTypeImmutable() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); MatsimServices controler = new Controler(config); try { - controler.getConfig().setParam("parallelEventHandling", "numberOfThreads", "2"); + controler.getConfig().setParam("eventsManager", "numberOfThreads", "2"); Assert.fail("Expected exception"); } catch (Exception e) { log.info("catched expected exception", e); } try { - controler.getConfig().setParam("parallelEventHandling", "estimatedNumberOfEvents", "200000"); + controler.getConfig().setParam("eventsManager", "estimatedNumberOfEvents", "200000"); Assert.fail("Expected exception"); } catch (Exception e) { log.info("catched expected exception", e); @@ -159,11 +159,11 @@ public void testConstructor_EventsManagerTypeImmutable() { public void testTravelTimeCalculation() { Fixture f = new Fixture(ConfigUtils.createConfig()); Config config = f.scenario.getConfig(); - + /* Create 2 persons driving from link 1 to link 3, both starting at the same time at 7am. */ Population population = f.scenario.getPopulation(); PopulationFactory factory = population.getFactory(); - + Person person1 = factory.createPerson(Id.create("1", Person.class)); Plan plan1 = factory.createPlan(); person1.addPlan(plan1); @@ -193,28 +193,28 @@ public void testTravelTimeCalculation() { route2.setLinkIds(f.link1.getId(), linkIds, f.link3.getId()); plan2.addActivity(factory.createActivityFromLinkId("h", f.link3.getId())); population.addPerson(person2); - - /* the first agent needs 101 seconds (100 seconds free speed + 1s buffer) for link2; + + /* the first agent needs 101 seconds (100 seconds free speed + 1s buffer) for link2; * the second agent needs 200 seconds (has to wait for 100 seconds because of flow capacity) */ double avgTravelTimeLink2 = 150.5; // Complete the configuration for our test case - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - config.controler().setCreateGraphs(false); - config.controler().setWriteEventsInterval(0); - config.controler().setDumpDataAtEnd(false); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setCreateGraphs(false); + config.controller().setWriteEventsInterval(0); + config.controller().setDumpDataAtEnd(false); // - set scoring parameters ActivityParams actParams = new ActivityParams("h"); actParams.setTypicalDuration(8*3600); actParams.setPriority(1.0); - config.planCalcScore().addActivityParams(actParams); + config.scoring().addActivityParams(actParams); // - define iterations - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); // - make sure we don't use threads, as they are not deterministic config.global().setNumberOfThreads(0); config.qsim().setUsingFastCapacityUpdate(this.isUsingFastCapacityUpdate); - + // Now run the simulation Controler controler = new Controler(f.scenario); controler.run(); @@ -225,18 +225,18 @@ public void testTravelTimeCalculation() { controler.getLinkTravelTimes().getLinkTravelTime(f.link2, 7 * 3600, null, null), MatsimTestUtils.EPSILON); // now test that the ReRoute-Strategy also knows about these travel times... - config.controler().setLastIteration(1); - config.strategy().setMaxAgentPlanMemorySize(4); + config.controller().setLastIteration(1); + config.replanning().setMaxAgentPlanMemorySize(4); // add ReRoute strategy StrategySettings strat = new StrategySettings(); strat.setStrategyName(DefaultStrategy.ReRoute.toString()); strat.setWeight(1.); - config.strategy().addStrategySettings(strat); + config.replanning().addStrategySettings(strat); // Run the simulation again controler = new Controler(f.scenario); controler.run(); - // test that the plans have the correct travel times + // test that the plans have the correct travel times // (travel time of the plan does not contain first and last link) assertEquals("ReRoute seems to have wrong travel times.", avgTravelTimeLink2, ((Leg)(person1.getPlans().get(1).getPlanElements().get(1))).getTravelTime().seconds(), MatsimTestUtils.EPSILON); @@ -251,10 +251,10 @@ public void testTravelTimeCalculation() { @Test public void testSetScoringFunctionFactory() { final Config config = this.utils.loadConfig((String) null); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); config.qsim().setUsingFastCapacityUpdate( this.isUsingFastCapacityUpdate ); - + MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config); // create a very simple network with one link only and an empty population Network network = scenario.getNetwork(); @@ -269,8 +269,8 @@ public void testSetScoringFunctionFactory() { link.setNumberOfLanes(1); final Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setWriteEventsInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(0); controler.setScoringFunctionFactory(new DummyScoringFunctionFactory()); controler.addOverridingModule(new AbstractModule() { @@ -284,7 +284,7 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); assertTrue("Custom ScoringFunctionFactory was not set.", @@ -337,18 +337,18 @@ public void testCalcMissingRoutes() { ActivityParams actParams = new ActivityParams("h"); actParams.setTypicalDuration(8*3600); actParams.setPriority(1.0); - config.planCalcScore().addActivityParams(actParams); + config.scoring().addActivityParams(actParams); // - define iterations - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); // - make sure we don't use threads, as they are not deterministic config.global().setNumberOfThreads(1); config.qsim().setUsingFastCapacityUpdate( this.isUsingFastCapacityUpdate ); - + // Now run the simulation Controler controler = new Controler(f.scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setWriteEventsInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(0); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -360,7 +360,7 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); /* if something goes wrong, there will be an exception we don't catch and the test fails, * otherwise, everything is fine. */ @@ -435,18 +435,18 @@ public void testCalcMissingActLinks() { ActivityParams actParams = new ActivityParams("h"); actParams.setTypicalDuration(8*3600); actParams.setPriority(1.0); - config.planCalcScore().addActivityParams(actParams); + config.scoring().addActivityParams(actParams); // - define iterations - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); // - make sure we don't use threads, as they are not deterministic config.global().setNumberOfThreads(1); config.qsim().setUsingFastCapacityUpdate( this.isUsingFastCapacityUpdate ); - + // Now run the simulation Controler controler = new Controler(f.scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setWriteEventsInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(0); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -458,7 +458,7 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); /* if something goes wrong, there will be an exception we don't catch and the test fails, * otherwise, everything is fine. */ @@ -468,9 +468,9 @@ public Mobsim get() { assertEquals(f.link3.getId(), act1b.getLinkId()); assertEquals(f.link1.getId(), act2a.getLinkId()); assertEquals(f.link3.getId(), act2b.getLinkId()); - + int expectedPlanLength = 3 ; - if ( !f.scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !f.scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { // now 7 instead of earlier 3: h-wlk-iact-car-iact-walk-h expectedPlanLength = 7 ; } @@ -487,7 +487,7 @@ public Mobsim get() { assertNotNull( "null route in plan "+plan.getPlanElements(), ((Leg) plan.getPlanElements().get( 1 )).getRoute()); - if ( !f.scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !f.scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { assertNotNull( "null route in plan "+plan.getPlanElements(), ((Leg) plan.getPlanElements().get( 3 )).getRoute()); @@ -501,13 +501,13 @@ public Mobsim get() { @Test public void testCompressionType() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(0); - config.controler().setCompressionType( CompressionType.zst ); - config.controler().setCleanItersAtEnd(ControlerConfigGroup.CleanIterations.keep); + config.controller().setLastIteration(0); + config.controller().setCompressionType( CompressionType.zst ); + config.controller().setCleanItersAtEnd(ControllerConfigGroup.CleanIterations.keep); final Controler controler = new Controler(config); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setCreateGraphs(false); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -540,17 +540,17 @@ public Mobsim get() { @Test public void testSetWriteEventsInterval() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(10); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(10); + config.controller().setWritePlansInterval(0); final Controler controler = new Controler(config); assertFalse("Default for Controler.writeEventsInterval should be different from the interval we plan to use, otherwise it's hard to decide if it works correctly.", - 3 == controler.getConfig().controler().getWriteEventsInterval()); + 3 == controler.getConfig().controller().getWriteEventsInterval()); - controler.getConfig().controler().setWriteEventsInterval(3); - assertEquals(3, controler.getConfig().controler().getWriteEventsInterval()); + controler.getConfig().controller().setWriteEventsInterval(3); + assertEquals(3, controler.getConfig().controller().getWriteEventsInterval()); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setCreateGraphs(false); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -562,7 +562,7 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); assertTrue(new File(controler.getControlerIO().getIterationFilename(0, Controler.DefaultFiles.events)).exists()); @@ -575,7 +575,7 @@ public Mobsim get() { assertFalse(new File(controler.getControlerIO().getIterationFilename(7, Controler.DefaultFiles.events)).exists()); assertFalse(new File(controler.getControlerIO().getIterationFilename(8, Controler.DefaultFiles.events)).exists()); assertTrue(new File(controler.getControlerIO().getIterationFilename(9, Controler.DefaultFiles.events)).exists()); - assertTrue(new File(controler.getControlerIO().getIterationFilename(controler.getConfig().controler().getLastIteration(), Controler.DefaultFiles.events)).exists()); + assertTrue(new File(controler.getControlerIO().getIterationFilename(controler.getConfig().controller().getLastIteration(), Controler.DefaultFiles.events)).exists()); } /** @@ -584,13 +584,13 @@ public Mobsim get() { @Test public void testSetWriteEventsIntervalConfig() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(10); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(10); + config.controller().setWritePlansInterval(0); final Controler controler = new Controler(config); assertFalse("Default for Controler.writeEventsInterval should be different from the interval we plan to use, otherwise it's hard to decide if it works correctly.", - 3 == controler.getConfig().controler().getWriteEventsInterval()); - controler.getConfig().controler().setCreateGraphs(false); + 3 == controler.getConfig().controller().getWriteEventsInterval()); + controler.getConfig().controller().setCreateGraphs(false); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -602,9 +602,9 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); - assertEquals(4, controler.getConfig().controler().getWriteEventsInterval()); + assertEquals(4, controler.getConfig().controller().getWriteEventsInterval()); assertTrue(new File(controler.getControlerIO().getIterationFilename(0, Controler.DefaultFiles.events)).exists()); assertFalse(new File(controler.getControlerIO().getIterationFilename(1, Controler.DefaultFiles.events)).exists()); @@ -616,7 +616,7 @@ public Mobsim get() { assertFalse(new File(controler.getControlerIO().getIterationFilename(7, Controler.DefaultFiles.events)).exists()); assertTrue(new File(controler.getControlerIO().getIterationFilename(8, Controler.DefaultFiles.events)).exists()); assertFalse(new File(controler.getControlerIO().getIterationFilename(9, Controler.DefaultFiles.events)).exists()); - assertTrue(new File(controler.getControlerIO().getIterationFilename(controler.getConfig().controler().getLastIteration(), Controler.DefaultFiles.events)).exists()); + assertTrue(new File(controler.getControlerIO().getIterationFilename(controler.getConfig().controller().getLastIteration(), Controler.DefaultFiles.events)).exists()); } /** @@ -625,15 +625,15 @@ public Mobsim get() { @Test public void testSetWriteEventsNever() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(1); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(1); + config.controller().setWritePlansInterval(0); final Controler controler = new Controler(config); assertFalse("Default for Controler.writeEventsInterval should be different from the interval we plan to use, otherwise it's hard to decide if it works correctly.", - 0 == controler.getConfig().controler().getWriteEventsInterval()); - controler.getConfig().controler().setWriteEventsInterval(0); - assertEquals(0, controler.getConfig().controler().getWriteEventsInterval()); - controler.getConfig().controler().setCreateGraphs(false); + 0 == controler.getConfig().controller().getWriteEventsInterval()); + controler.getConfig().controller().setWriteEventsInterval(0); + assertEquals(0, controler.getConfig().controller().getWriteEventsInterval()); + controler.getConfig().controller().setCreateGraphs(false); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -645,7 +645,7 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); assertFalse(new File(controler.getControlerIO().getIterationFilename(0, Controler.DefaultFiles.events)).exists()); @@ -658,13 +658,13 @@ public Mobsim get() { @Test public void testSetWriteEventsAlways() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(1); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(1); + config.controller().setWritePlansInterval(0); final Controler controler = new Controler(config); - controler.getConfig().controler().setWriteEventsInterval(1); - assertEquals(1, controler.getConfig().controler().getWriteEventsInterval()); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(1); + assertEquals(1, controler.getConfig().controller().getWriteEventsInterval()); + controler.getConfig().controller().setCreateGraphs(false); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -676,7 +676,7 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); assertTrue(new File(controler.getControlerIO().getIterationFilename(0, Controler.DefaultFiles.events)).exists()); @@ -689,14 +689,14 @@ public Mobsim get() { @Test public void testSetWriteEventsXml() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(0); - config.controler().setWritePlansInterval(0); - config.controler().setEventsFileFormats(EnumSet.of(EventsFileFormat.xml)); + config.controller().setLastIteration(0); + config.controller().setWritePlansInterval(0); + config.controller().setEventsFileFormats(EnumSet.of(EventsFileFormat.xml)); final Controler controler = new Controler(config); - controler.getConfig().controler().setWriteEventsInterval(1); - assertEquals(1, controler.getConfig().controler().getWriteEventsInterval()); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(1); + assertEquals(1, controler.getConfig().controller().getWriteEventsInterval()); + controler.getConfig().controller().setCreateGraphs(false); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -708,7 +708,7 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); assertTrue(new File(controler.getControlerIO().getIterationFilename(0, Controler.DefaultFiles.events)).exists()); @@ -720,12 +720,12 @@ public Mobsim get() { @Test public void testSetDumpDataAtEnd_true() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(0); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(0); + config.controller().setWritePlansInterval(0); final Controler controler = new Controler(config); - controler.getConfig().controler().setWriteEventsInterval(0); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(0); + controler.getConfig().controller().setCreateGraphs(false); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -738,7 +738,7 @@ public Mobsim get() { } }); - controler.getConfig().controler().setDumpDataAtEnd(true); + controler.getConfig().controller().setDumpDataAtEnd(true); controler.run(); assertTrue(new File(controler.getControlerIO().getOutputFilename(Controler.DefaultFiles.population)).exists()); @@ -750,12 +750,12 @@ public Mobsim get() { @Test public void testSetDumpDataAtEnd_false() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(0); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(0); + config.controller().setWritePlansInterval(0); final Controler controler = new Controler(config); - controler.getConfig().controler().setWriteEventsInterval(0); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(0); + controler.getConfig().controller().setCreateGraphs(false); controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -768,7 +768,7 @@ public Mobsim get() { } }); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); @@ -778,7 +778,7 @@ public Mobsim get() { @Test(expected = RuntimeException.class) public void testShutdown_UncaughtException() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(1); + config.controller().setLastIteration(1); Controler controler = new Controler(config); controler.addOverridingModule(new AbstractModule() { @@ -787,17 +787,17 @@ public void install() { bindMobsim().to(CrashingMobsim.class); } }); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); } @Test public void test_ExceptionOnMissingPopulationFile() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(0); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(0); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); config.plans().setInputFile("dummy/non-existing/population.xml"); try { @@ -813,15 +813,15 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); Assert.fail("expected exception, got none."); - + // note: I moved loadScenario in the controler from run() into the constructor to mirror the loading sequence one has - // when calling new Controler(scenario). In consequence, it fails already in the constructor; one could stop after that. + // when calling new Controler(scenario). In consequence, it fails already in the constructor; one could stop after that. // kai, apr'15 - + } catch (RuntimeException e) { log.info("catched expected exception.", e); } @@ -831,9 +831,9 @@ public Mobsim get() { public void test_ExceptionOnMissingNetworkFile() { try { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(0); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(0); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); config.network().setInputFile("dummy/non-existing/network.xml"); final Controler controler = new Controler(config); @@ -848,15 +848,15 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); Assert.fail("expected exception, got none."); - + // note: I moved loadScenario in the controler from run() into the constructor to mirror the loading sequence one has - // when calling new Controler(scenario). In consequence, it fails already in the constructor; one could stop after that. + // when calling new Controler(scenario). In consequence, it fails already in the constructor; one could stop after that. // kai, apr'15 - + } catch (RuntimeException e) { log.info("catched expected exception.", e); } @@ -866,9 +866,9 @@ public Mobsim get() { public void test_ExceptionOnMissingFacilitiesFile() { try { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(0); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(0); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); config.facilities().setInputFile("dummy/non-existing/network.xml"); final Controler controler = new Controler(config); @@ -883,15 +883,15 @@ public Mobsim get() { }); } }); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); Assert.fail("expected exception, got none."); - + // note: I moved loadScenario in the controler from run() into the constructor to mirror the loading sequence one has - // when calling new Controler(scenario). In consequence, it fails already in the constructor; one could stop after that. + // when calling new Controler(scenario). In consequence, it fails already in the constructor; one could stop after that. // kai, apr'15 - + } catch (RuntimeException e) { log.info("catched expected exception.", e); } @@ -900,15 +900,15 @@ public Mobsim get() { @Test public void testOneSnapshotWriterInConfig() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(0); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(0); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); config.qsim().setSnapshotPeriod(10); config.qsim().setSnapshotStyle(SnapshotStyle.equiDist) ;; final Controler controler = new Controler(config); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); assertTrue(new File(controler.getControlerIO().getIterationFilename(0, "T.veh.gz")).exists()); @@ -917,18 +917,18 @@ public void testOneSnapshotWriterInConfig() { @Test public void testTransimsSnapshotWriterOnQSim() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration(2); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); - config.controler().setMobsim("qsim"); - config.controler().setSnapshotFormat( Collections.singletonList( SnapshotFormat.transims ) ); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setLastIteration(2); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); + config.controller().setMobsim("qsim"); + config.controller().setSnapshotFormat( Collections.singletonList( SnapshotFormat.transims ) ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); config.qsim().setSnapshotPeriod(600); config.qsim().setSnapshotStyle( SnapshotStyle.equiDist ) ;; final Controler controler = new Controler(config); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); assertTrue(new File(controler.getControlerIO().getIterationFilename(0, "T.veh.gz")).exists()); @@ -942,12 +942,12 @@ public void testTransimsSnapshotWriterOnQSim() { * which itself adds a Guice module... but too late. * * @thibautd - * + * */ @Test( expected = RuntimeException.class ) public void testGuiceModulesCannotAddModules() { final Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - config.controler().setLastIteration( 0 ); + config.controller().setLastIteration( 0 ); final Controler controler = new Controler( config ); final Scenario replacementScenario = ScenarioUtils.createScenario( config ); diff --git a/matsim/src/test/java/org/matsim/core/controler/ControlerMobsimIntegrationTest.java b/matsim/src/test/java/org/matsim/core/controler/ControlerMobsimIntegrationTest.java index 56a843a749b..a66fc10c46c 100644 --- a/matsim/src/test/java/org/matsim/core/controler/ControlerMobsimIntegrationTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/ControlerMobsimIntegrationTest.java @@ -45,15 +45,15 @@ public class ControlerMobsimIntegrationTest { @Test public void testRunMobsim_customMobsim() { Config cfg = this.utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config_plans1.xml")); - cfg.controler().setLastIteration(0); - cfg.controler().setMobsim("counting"); - cfg.controler().setWritePlansInterval(0); + cfg.controller().setLastIteration(0); + cfg.controller().setMobsim("counting"); + cfg.controller().setWritePlansInterval(0); final Controler c = new Controler(cfg); final CountingMobsimFactory mf = new CountingMobsimFactory(); c.addOverridingModule(new AbstractModule() { @Override public void install() { - if (getConfig().controler().getMobsim().equals("counting")) { + if (getConfig().controller().getMobsim().equals("counting")) { bind(Mobsim.class).toProvider(new Provider() { @Override public Mobsim get() { @@ -63,9 +63,9 @@ public Mobsim get() { } } }); - c.getConfig().controler().setCreateGraphs(false); - c.getConfig().controler().setDumpDataAtEnd(false); - c.getConfig().controler().setWriteEventsInterval(0); + c.getConfig().controller().setCreateGraphs(false); + c.getConfig().controller().setDumpDataAtEnd(false); + c.getConfig().controller().setWriteEventsInterval(0); c.run(); Assert.assertEquals(1, mf.callCount); } @@ -73,13 +73,13 @@ public Mobsim get() { @Test(expected = RuntimeException.class) public void testRunMobsim_missingMobsimFactory() { Config cfg = this.utils.loadConfig("test/scenarios/equil/config_plans1.xml"); - cfg.controler().setLastIteration(0); - cfg.controler().setMobsim("counting"); - cfg.controler().setWritePlansInterval(0); + cfg.controller().setLastIteration(0); + cfg.controller().setMobsim("counting"); + cfg.controller().setWritePlansInterval(0); Controler c = new Controler(cfg); - c.getConfig().controler().setCreateGraphs(false); - c.getConfig().controler().setDumpDataAtEnd(false); - c.getConfig().controler().setWriteEventsInterval(0); + c.getConfig().controller().setCreateGraphs(false); + c.getConfig().controller().setDumpDataAtEnd(false); + c.getConfig().controller().setWriteEventsInterval(0); c.run(); } diff --git a/matsim/src/test/java/org/matsim/core/controler/MatsimServicesImplTest.java b/matsim/src/test/java/org/matsim/core/controler/MatsimServicesImplTest.java index 0712fa96c72..b4ad53a30d1 100644 --- a/matsim/src/test/java/org/matsim/core/controler/MatsimServicesImplTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/MatsimServicesImplTest.java @@ -32,20 +32,20 @@ import org.matsim.testcases.MatsimTestUtils; public class MatsimServicesImplTest { - + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - + @Ignore @Test public void testIterationInServicesEqualsIterationInEvent() { - + Config config = ConfigUtils.createConfig(); - config.controler().setLastIteration(1); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - + config.controller().setLastIteration(1); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + Controler controler = new Controler( config ); - + controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -54,15 +54,15 @@ public void install() { @Override public void notifyIterationStarts(IterationStartsEvent event) { Assert.assertSame(event.getIteration(), event.getServices().getIterationNumber()); - + } - + }); } }); - + controler.run(); - + } } diff --git a/matsim/src/test/java/org/matsim/core/controler/MobsimListenerTest.java b/matsim/src/test/java/org/matsim/core/controler/MobsimListenerTest.java index 29d47a29ff6..099e07ca091 100644 --- a/matsim/src/test/java/org/matsim/core/controler/MobsimListenerTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/MobsimListenerTest.java @@ -39,8 +39,8 @@ public class MobsimListenerTest { @Test public void testRunMobsim_listenerTransient() { Config cfg = this.utils.loadConfig("test/scenarios/equil/config_plans1.xml"); - cfg.controler().setLastIteration(1); - cfg.controler().setWritePlansInterval(0); + cfg.controller().setLastIteration(1); + cfg.controller().setWritePlansInterval(0); final Controler c = new Controler(cfg); c.addOverridingModule(new AbstractModule() { @Override @@ -48,17 +48,17 @@ public void install() { addMobsimListenerBinding().to(CountingMobsimListener.class); } }); - c.getConfig().controler().setCreateGraphs(false); - c.getConfig().controler().setDumpDataAtEnd(false); - c.getConfig().controler().setWriteEventsInterval(0); + c.getConfig().controller().setCreateGraphs(false); + c.getConfig().controller().setDumpDataAtEnd(false); + c.getConfig().controller().setWriteEventsInterval(0); c.run(); } @Test(expected = RuntimeException.class) public void testRunMobsim_listenerSingleton() { Config cfg = this.utils.loadConfig("test/scenarios/equil/config_plans1.xml"); - cfg.controler().setLastIteration(1); - cfg.controler().setWritePlansInterval(0); + cfg.controller().setLastIteration(1); + cfg.controller().setWritePlansInterval(0); final Controler c = new Controler(cfg); c.addOverridingModule(new AbstractModule() { @Override @@ -66,9 +66,9 @@ public void install() { addMobsimListenerBinding().to(SingletonCountingMobsimListener.class); } }); - c.getConfig().controler().setCreateGraphs(false); - c.getConfig().controler().setDumpDataAtEnd(false); - c.getConfig().controler().setWriteEventsInterval(0); + c.getConfig().controller().setCreateGraphs(false); + c.getConfig().controller().setDumpDataAtEnd(false); + c.getConfig().controller().setWriteEventsInterval(0); c.run(); } diff --git a/matsim/src/test/java/org/matsim/core/controler/NewControlerTest.java b/matsim/src/test/java/org/matsim/core/controler/NewControlerTest.java index e292987d787..cbb1eabbe43 100644 --- a/matsim/src/test/java/org/matsim/core/controler/NewControlerTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/NewControlerTest.java @@ -46,8 +46,8 @@ public void testInjectionBeforeControler() { // facility file is provided in config and facilitySource is 'fromFile', the facilitySource must be changed. Amit Jan'18 config.facilities().setFacilitiesSource(FacilitiesConfigGroup.FacilitiesSource.none); - config.controler().setLastIteration(1); - config.controler().setOutputDirectory(testUtils.getOutputDirectory()); + config.controller().setLastIteration(1); + config.controller().setOutputDirectory(testUtils.getOutputDirectory()); final Scenario scenario = ScenarioUtils.createScenario(config); com.google.inject.Injector injector = Injector.createInjector(config, new AbstractModule() { @Override diff --git a/matsim/src/test/java/org/matsim/core/controler/OutputDirectoryHierarchyTest.java b/matsim/src/test/java/org/matsim/core/controler/OutputDirectoryHierarchyTest.java index 7bf52f3abb7..0431939f972 100644 --- a/matsim/src/test/java/org/matsim/core/controler/OutputDirectoryHierarchyTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/OutputDirectoryHierarchyTest.java @@ -21,14 +21,14 @@ import org.junit.Assert; import org.junit.Rule; import org.junit.Test; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.testcases.MatsimTestUtils; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; +import java.io.UncheckedIOException; /** * @author thibautd @@ -46,7 +46,7 @@ public void testFailureIfDirectoryExists() { new OutputDirectoryHierarchy( outputDirectory, OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists, - ControlerConfigGroup.CompressionType.none); + ControllerConfigGroup.CompressionType.none); Assert.assertTrue( "Directory was not created", @@ -65,7 +65,7 @@ public void testFailureIfDirectoryExists() { new OutputDirectoryHierarchy( outputDirectory, OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists, - ControlerConfigGroup.CompressionType.none); + ControllerConfigGroup.CompressionType.none); } catch ( RuntimeException e ) { return; @@ -82,7 +82,7 @@ public void testOverrideIfDirectoryExists() { new OutputDirectoryHierarchy( outputDirectory, OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles, - ControlerConfigGroup.CompressionType.none); + ControllerConfigGroup.CompressionType.none); Assert.assertTrue( "Directory was not created", @@ -100,7 +100,7 @@ public void testOverrideIfDirectoryExists() { new OutputDirectoryHierarchy( outputDirectory, OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles, - ControlerConfigGroup.CompressionType.none); + ControllerConfigGroup.CompressionType.none); Assert.assertTrue( "Directory was cleared", @@ -117,7 +117,7 @@ public void testDeleteIfDirectoryExists() { new OutputDirectoryHierarchy( outputDirectory, OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists, - ControlerConfigGroup.CompressionType.none); + ControllerConfigGroup.CompressionType.none); Assert.assertTrue( "Directory was not created", @@ -135,7 +135,7 @@ public void testDeleteIfDirectoryExists() { new OutputDirectoryHierarchy( outputDirectory, OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists, - ControlerConfigGroup.CompressionType.none); + ControllerConfigGroup.CompressionType.none); Assert.assertTrue( "Directory was deleted but not re-created!", diff --git a/matsim/src/test/java/org/matsim/core/controler/OverrideCarTraveltimeTest.java b/matsim/src/test/java/org/matsim/core/controler/OverrideCarTraveltimeTest.java index fb2d4ec1475..ff00e8c4fac 100644 --- a/matsim/src/test/java/org/matsim/core/controler/OverrideCarTraveltimeTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/OverrideCarTraveltimeTest.java @@ -22,7 +22,6 @@ package org.matsim.core.controler; -import com.google.inject.Provider; import org.junit.Assert; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; @@ -31,7 +30,6 @@ import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.events.ReplanningEvent; import org.matsim.core.controler.listener.ReplanningListener; -import org.matsim.core.replanning.ReplanningContext; import org.matsim.core.router.costcalculators.TravelDisutilityFactory; import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; @@ -45,8 +43,8 @@ public class OverrideCarTraveltimeTest { public static void main(String[] args) { final Config config = ConfigUtils.createConfig(); - config.controler().setLastIteration(1); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.controller().setLastIteration(1); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); Controler controler = new Controler(ScenarioUtils.createScenario(config)); controler.addOverridingModule(new AbstractModule() { @Override diff --git a/matsim/src/test/java/org/matsim/core/controler/PrepareForSimImplTest.java b/matsim/src/test/java/org/matsim/core/controler/PrepareForSimImplTest.java index e841aac308e..d711ebceaaa 100644 --- a/matsim/src/test/java/org/matsim/core/controler/PrepareForSimImplTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/PrepareForSimImplTest.java @@ -19,10 +19,7 @@ package org.matsim.core.controler; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.junit.Assert; import org.junit.Test; @@ -53,19 +50,23 @@ import org.matsim.core.router.TripStructureUtils; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.timing.TimeInterpretation; -import org.matsim.facilities.Facility; import com.google.inject.Provider; +import org.matsim.vehicles.Vehicle; +import org.matsim.vehicles.VehicleType; +import org.matsim.vehicles.VehicleUtils; + +import static org.assertj.core.api.Assertions.assertThat; /** * Mostly tests adaptation of old plans to routing mode and the related replacement of helper modes for access and egress * to pt/drt and the related replacement of fallback modes for pt/drt (if no route could be found). - * + * * Does not test the combination of already a routing mode and outdated helper / fallback modes, because those never existed * in the code at the same time. - * + * * TODO: add tests for other methods of {@link PrepareForSimImpl}. - * + * * @author vsp-gleich */ public class PrepareForSimImplTest { @@ -73,7 +74,7 @@ public class PrepareForSimImplTest { @Test public void testSingleLegTripRoutingMode() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); Scenario scenario = ScenarioUtils.createScenario(config); createAndAddNetwork(scenario); Population pop = scenario.getPopulation(); @@ -95,16 +96,16 @@ public void testSingleLegTripRoutingMode() { person.addPlan(plan); pop.addPerson(person); - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.assertEquals("wrong routing mode!", TransportMode.pt, TripStructureUtils.getRoutingMode(leg)); } - + // test routing mode set, such as after TripsToLegsAlgorithm + replanning strategy { PopulationFactory pf = pop.getFactory(); @@ -122,21 +123,21 @@ public void testSingleLegTripRoutingMode() { person.addPlan(plan); pop.addPerson(person); - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.assertEquals("wrong routing mode!", TransportMode.pt, TripStructureUtils.getRoutingMode(leg)); } } - + @Test public void testSingleFallbackModeLegTrip() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); Scenario scenario = ScenarioUtils.createScenario(config); createAndAddNetwork(scenario); Population pop = scenario.getPopulation(); @@ -158,17 +159,17 @@ public void testSingleFallbackModeLegTrip() { person.addPlan(plan); pop.addPerson(person); - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg.getMode()); Assert.assertEquals("wrong routing mode!", TransportMode.pt, TripStructureUtils.getRoutingMode(leg)); } - + // test outdated fallback mode single leg trip (arbitrary drt mode) { PopulationFactory pf = pop.getFactory(); @@ -186,10 +187,10 @@ public void testSingleFallbackModeLegTrip() { person.addPlan(plan); pop.addPerson(person); - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.assertEquals("wrong leg mode replacement", TransportMode.walk, leg.getMode()); @@ -197,15 +198,15 @@ public void testSingleFallbackModeLegTrip() { TripStructureUtils.getRoutingMode(leg)); } } - + @Test public void testCorrectTripsRemainUnchanged() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); Scenario scenario = ScenarioUtils.createScenario(config); createAndAddNetwork(scenario); Population pop = scenario.getPopulation(); - + // test car trip with access/egress walk legs { PopulationFactory pf = pop.getFactory(); @@ -233,24 +234,24 @@ public void testCorrectTripsRemainUnchanged() { plan.addActivity(activity4); person.addPlan(plan); pop.addPerson(person); - - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); - + // Check leg modes remain unchanged Assert.assertEquals("wrong leg mode!", TransportMode.walk, leg1.getMode()); Assert.assertEquals("wrong routing mode!", TransportMode.car, leg2.getMode()); Assert.assertEquals("wrong leg mode!", TransportMode.walk, leg3.getMode()); - + // Check routing mode: Assert.assertEquals("wrong routing mode!", TransportMode.car, TripStructureUtils.getRoutingMode(leg1)); Assert.assertEquals("wrong routing mode!", TransportMode.car, TripStructureUtils.getRoutingMode(leg2)); Assert.assertEquals("wrong routing mode!", TransportMode.car, TripStructureUtils.getRoutingMode(leg3)); } - + // test complicated intermodal trip with consistent routing modes passes unchanged { PopulationFactory pf = pop.getFactory(); @@ -326,15 +327,15 @@ public void testCorrectTripsRemainUnchanged() { plan.addActivity(activity12); person.addPlan(plan); pop.addPerson(person); - - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); - + // Check leg modes remain unchanged - + // TODO: Currently all TransportMode.non_network_walk legs are replaced by TransportMode.walk, so we cannot check // the correct handling of them right now. // Assert.assertEquals("wrong routing mode!", TransportMode.non_network_walk, leg1.getMode()); @@ -348,7 +349,7 @@ public void testCorrectTripsRemainUnchanged() { // Assert.assertEquals("wrong routing mode!", TransportMode.non_network_walk, leg9.getMode()); Assert.assertEquals("wrong leg mode!", TransportMode.walk, leg10.getMode()); // Assert.assertEquals("wrong routing mode!", TransportMode.non_network_walk, leg11.getMode()); - + // Check routing mode remains unchanged Assert.assertEquals("wrong routing mode!", "intermodal pt", TripStructureUtils.getRoutingMode(leg1)); Assert.assertEquals("wrong routing mode!", "intermodal pt", TripStructureUtils.getRoutingMode(leg2)); @@ -363,15 +364,15 @@ public void testCorrectTripsRemainUnchanged() { Assert.assertEquals("wrong routing mode!", "intermodal pt", TripStructureUtils.getRoutingMode(leg11)); } } - + @Test public void testRoutingModeConsistency() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); Scenario scenario = ScenarioUtils.createScenario(config); createAndAddNetwork(scenario); Population pop = scenario.getPopulation(); - + // test trip with inconsistent routing modes causes exception { PopulationFactory pf = pop.getFactory(); @@ -398,17 +399,17 @@ public void testRoutingModeConsistency() { plan.addActivity(activity4); person.addPlan(plan); pop.addPerson(person); - + try { - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.fail("expected Exception, got none."); } catch (RuntimeException expected) {} } - + // test trip with legs with and others without routing modes causes exception { PopulationFactory pf = pop.getFactory(); @@ -435,27 +436,27 @@ public void testRoutingModeConsistency() { plan.addActivity(activity4); person.addPlan(plan); pop.addPerson(person); - + try { - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.fail("expected Exception, got none."); } catch (RuntimeException expected) {} } } - + @Test public void testOutdatedHelperModesReplacement() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.reject); Scenario scenario = ScenarioUtils.createScenario(config); createAndAddNetwork(scenario); Population pop = scenario.getPopulation(); - + // test car trip with outdated access/egress walk modes { PopulationFactory pf = pop.getFactory(); @@ -483,36 +484,36 @@ public void testOutdatedHelperModesReplacement() { plan.addActivity(activity4); person.addPlan(plan); pop.addPerson(person); - + // Should give an exception with default: config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.reject); try { - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.fail("expected Exception, got none."); } catch (RuntimeException expected) {} - + // Should work with config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); - + // Check replacement of outdated helper modes. Assert.assertEquals("wrong leg mode!", TransportMode.walk, leg1.getMode()); Assert.assertEquals("wrong leg mode!", TransportMode.car, leg2.getMode()); Assert.assertEquals("wrong leg mode!", TransportMode.walk, leg3.getMode()); - + // Check routing mode: Assert.assertEquals("wrong routing mode!", TransportMode.car, TripStructureUtils.getRoutingMode(leg1)); Assert.assertEquals("wrong routing mode!", TransportMode.car, TripStructureUtils.getRoutingMode(leg2)); Assert.assertEquals("wrong routing mode!", TransportMode.car, TripStructureUtils.getRoutingMode(leg3)); } - + // test car trip with outdated access/egress walk modes { PopulationFactory pf = pop.getFactory(); @@ -540,37 +541,37 @@ public void testOutdatedHelperModesReplacement() { plan.addActivity(activity4); person.addPlan(plan); pop.addPerson(person); - + config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.reject); // Should give an exception with default: config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.reject); try { - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.fail("expected Exception, got none."); } catch (RuntimeException expected) {} - + // Should work with config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); - + // Check replacement of outdated helper modes. Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg1.getMode()); Assert.assertEquals("wrong leg mode!", TransportMode.car, leg2.getMode()); Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg3.getMode()); - + // Check routing mode: Assert.assertEquals("wrong routing mode!", TransportMode.car, TripStructureUtils.getRoutingMode(leg1)); Assert.assertEquals("wrong routing mode!", TransportMode.car, TripStructureUtils.getRoutingMode(leg2)); Assert.assertEquals("wrong routing mode!", TransportMode.car, TripStructureUtils.getRoutingMode(leg3)); } - + // test complicated intermodal drt+pt trip with outdated access/egress walk modes { PopulationFactory pf = pop.getFactory(); @@ -622,26 +623,26 @@ public void testOutdatedHelperModesReplacement() { plan.addActivity(activity8); person.addPlan(plan); pop.addPerson(person); - + config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.reject); // Should give an exception with default: config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.reject); try { - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.fail("expected Exception, got none."); } catch (RuntimeException expected) {} - + // Should work with config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); - + // Check replacement of outdated helper modes. Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg1.getMode()); Assert.assertEquals("wrong leg mode!", TransportMode.drt, leg2.getMode()); @@ -650,15 +651,15 @@ public void testOutdatedHelperModesReplacement() { Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg5.getMode()); Assert.assertEquals("wrong leg mode!", TransportMode.pt, leg6.getMode()); Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg7.getMode()); - + /* * Check routing mode: * TransportMode.drt is what the default MainModeIdentifierImpl returns. To handle intermodal trips "right" * in the old setup, we would probably have to overwrite the MainModeIdentifier with a custom * MainModeIdentifier able to understand intermodal trips. - * + * * For the scope of this test it is sufficient, that the MainModeIdentifier is run, returns a main mode - * and that this main mode is assigned as routingMode to all legs. + * and that this main mode is assigned as routingMode to all legs. */ Assert.assertEquals("wrong routing mode!", TransportMode.drt, TripStructureUtils.getRoutingMode(leg1)); Assert.assertEquals("wrong routing mode!", TransportMode.drt, TripStructureUtils.getRoutingMode(leg2)); @@ -669,16 +670,16 @@ public void testOutdatedHelperModesReplacement() { Assert.assertEquals("wrong routing mode!", TransportMode.drt, TripStructureUtils.getRoutingMode(leg7)); } } - + @Test public void testOutdatedFallbackAndHelperModesReplacement() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.reject); Scenario scenario = ScenarioUtils.createScenario(config); createAndAddNetwork(scenario); Population pop = scenario.getPopulation(); - + // test complicated intermodal trip with consistent routing modes passes unchanged { PopulationFactory pf = pop.getFactory(); @@ -718,40 +719,40 @@ public void testOutdatedFallbackAndHelperModesReplacement() { plan.addActivity(activity6); person.addPlan(plan); pop.addPerson(person); - + // Should give an exception with default: config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.reject); try { - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); Assert.fail("expected Exception, got none."); } catch (RuntimeException expected) {} - + // Should work with config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); - final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), - pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); - + prepareForSimImpl.run(); - + // Check replacement of outdated helper modes. Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg1.getMode()); Assert.assertEquals("wrong leg mode!", TransportMode.drt, leg2.getMode()); Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg3.getMode()); Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg4.getMode()); Assert.assertEquals("wrong leg mode replacement!", TransportMode.walk, leg5.getMode()); - + /* * Check routing mode: * TransportMode.drt is what the default MainModeIdentifierImpl returns. To handle intermodal trips "right" * in the old setup, we would probably have to overwrite the MainModeIdentifier with a custom * MainModeIdentifier able to understand intermodal trips. - * + * * For the scope of thios test it is sufficient, that the MainModeIdentifier is run, returns a main mode - * and that this main mode is assigned as routingMode to all legs. + * and that this main mode is assigned as routingMode to all legs. */ Assert.assertEquals("wrong routing mode!", TransportMode.drt, TripStructureUtils.getRoutingMode(leg1)); Assert.assertEquals("wrong routing mode!", TransportMode.drt, TripStructureUtils.getRoutingMode(leg2)); @@ -760,7 +761,49 @@ public void testOutdatedFallbackAndHelperModesReplacement() { Assert.assertEquals("wrong routing mode!", TransportMode.drt, TripStructureUtils.getRoutingMode(leg5)); } } - + + @Test + public void vehicleTypes() { + + Config config = ConfigUtils.createConfig(); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + Scenario scenario = ScenarioUtils.createScenario(config); + createAndAddNetwork(scenario); + Population pop = scenario.getPopulation(); + PopulationFactory f = pop.getFactory(); + + // add truck type + VehicleType truckType = scenario.getVehicles().getFactory().createVehicleType(Id.create("truck", VehicleType.class)); + scenario.getVehicles().addVehicleType(truckType); + + // Create test person + Person p1 = f.createPerson(Id.createPersonId("1")); + { + VehicleUtils.insertVehicleTypesIntoAttributes(p1, Map.of(TransportMode.car, Id.create("truck", VehicleType.class))); + + Plan plan = f.createPlan(); + Activity act = f.createActivityFromCoord("home", new Coord(0, 0)); + act.setEndTime(3600); + plan.addActivity(act); + plan.addLeg(f.createLeg(TransportMode.car)); + plan.addActivity(f.createActivityFromCoord("work", new Coord(1000, 0))); + p1.addPlan(plan); + pop.addPerson(p1); + } + + // run prepare + final PrepareForSimImpl prepareForSimImpl = new PrepareForSimImpl(config.global(), scenario, scenario.getNetwork(), + pop, scenario.getActivityFacilities(), new DummyTripRouterProvider(), config.qsim(), config.facilities(), + config.plans(), new MainModeIdentifierImpl(), TimeInterpretation.create(config)); + + prepareForSimImpl.run(); + + Id id = VehicleUtils.getVehicleId(p1, TransportMode.car); + assertThat(scenario.getVehicles().getVehicles().get(id).getType()) + .isEqualTo(truckType); + + } + private class DummyTripRouterProvider implements Provider { @Override public TripRouter get() { @@ -774,7 +817,7 @@ public TripRouter get() { .build(); } } - + private class DummyRoutingModule implements RoutingModule { @Override public List calcRoute(RoutingRequest request) { diff --git a/matsim/src/test/java/org/matsim/core/controler/TerminationTest.java b/matsim/src/test/java/org/matsim/core/controler/TerminationTest.java index f486ee58278..65de1dea5b9 100644 --- a/matsim/src/test/java/org/matsim/core/controler/TerminationTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/TerminationTest.java @@ -11,8 +11,8 @@ import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup; -import org.matsim.core.config.groups.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.events.IterationStartsEvent; import org.matsim.core.controler.listener.IterationStartsListener; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule.DefaultStrategy; @@ -35,7 +35,7 @@ public class TerminationTest { @Test public void testSimulationEndsOnInterval() { - prepareExperiment(2, 4, ControlerConfigGroup.CleanIterations.keep).run(); + prepareExperiment(2, 4, ControllerConfigGroup.CleanIterations.keep).run(); Assert.assertTrue(new File(utils.getOutputDirectory(), "/ITERS/it.4/4.events.xml.gz").exists()); Assert.assertTrue(new File(utils.getOutputDirectory(), "/output_events.xml.gz").exists()); @@ -47,7 +47,7 @@ public void testSimulationEndsOnInterval() { @Test public void testOnlyRunIterationZero() { - prepareExperiment(2, 0, ControlerConfigGroup.CleanIterations.keep).run(); + prepareExperiment(2, 0, ControllerConfigGroup.CleanIterations.keep).run(); Assert.assertTrue(new File(utils.getOutputDirectory(), "/ITERS/it.0/0.events.xml.gz").exists()); Assert.assertTrue(new File(utils.getOutputDirectory(), "/output_events.xml.gz").exists()); @@ -62,7 +62,7 @@ public void testSimulationEndsOffInterval() { // This is the case when the TerminationCriterion decides that the simulation is // done, but it does not fall at the same time as the output interval. - prepareExperiment(2, 3, ControlerConfigGroup.CleanIterations.keep).run(); + prepareExperiment(2, 3, ControllerConfigGroup.CleanIterations.keep).run(); Assert.assertTrue(new File(utils.getOutputDirectory(), "/ITERS/it.2/2.events.xml.gz").exists()); Assert.assertTrue(new File(utils.getOutputDirectory(), "/ITERS/it.3/3.events.xml.gz").exists()); @@ -75,17 +75,17 @@ public void testSimulationEndsOffInterval() { @Test public void testSimulationEndDeleteIters() { - prepareExperiment(2, 3, ControlerConfigGroup.CleanIterations.delete).run(); + prepareExperiment(2, 3, ControllerConfigGroup.CleanIterations.delete).run(); Assert.assertFalse(new File(utils.getOutputDirectory(), "/ITERS").exists()); } - private Controler prepareExperiment(int interval, int criterion, ControlerConfigGroup.CleanIterations iters) { + private Controler prepareExperiment(int interval, int criterion, ControllerConfigGroup.CleanIterations iters) { Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setCleanItersAtEnd(iters); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setCleanItersAtEnd(iters); - config.controler().setWriteEventsInterval(interval); - config.controler().setLastIteration(criterion); + config.controller().setWriteEventsInterval(interval); + config.controller().setLastIteration(criterion); return new Controler(config); } @@ -98,7 +98,7 @@ public void testMultipleLastIterations() { * is written, decides that more iterations need to be run. */ - Controler controller = prepareExperiment(2, 1000, ControlerConfigGroup.CleanIterations.keep); + Controler controller = prepareExperiment(2, 1000, ControllerConfigGroup.CleanIterations.keep); controller.setTerminationCriterion(new TerminationCriterion() { @Override @@ -132,8 +132,8 @@ public void testCustomConverenceCriterion() { */ Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setCleanItersAtEnd(ControlerConfigGroup.CleanIterations.keep); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setCleanItersAtEnd(ControllerConfigGroup.CleanIterations.keep); { // Set up mode choice config.changeMode().setModes(new String[] { "car", "walk" }); @@ -141,7 +141,7 @@ public void testCustomConverenceCriterion() { StrategySettings modeStrategy = new StrategySettings(); modeStrategy.setStrategyName(DefaultStrategy.ChangeTripMode); modeStrategy.setWeight(0.1); - config.strategy().addStrategySettings(modeStrategy); + config.replanning().addStrategySettings(modeStrategy); } Scenario scenario = ScenarioUtils.loadScenario(config); diff --git a/matsim/src/test/java/org/matsim/core/controler/TransitControlerIntegrationTest.java b/matsim/src/test/java/org/matsim/core/controler/TransitControlerIntegrationTest.java index 49192781892..3d2999caa20 100644 --- a/matsim/src/test/java/org/matsim/core/controler/TransitControlerIntegrationTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/TransitControlerIntegrationTest.java @@ -41,8 +41,8 @@ import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.core.config.Config; -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.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.scenario.MutableScenario; @@ -137,25 +137,25 @@ public class TransitControlerIntegrationTest { population.addPerson(person1); // prepare config - config.controler().setFirstIteration(0); - config.controler().setLastIteration(1); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(1); ActivityParams params = new ActivityParams("h"); params.setTypicalDuration(16.0*3600); - config.planCalcScore().addActivityParams(params); + config.scoring().addActivityParams(params); params = new ActivityParams("w"); params.setTypicalDuration(8.0*3600); - config.planCalcScore().addActivityParams(params); + config.scoring().addActivityParams(params); StrategySettings tam = new StrategySettings(Id.create(1, StrategySettings.class)); tam.setStrategyName("TimeAllocationMutator"); tam.setWeight(1.0); - config.strategy().addStrategySettings(tam); + config.replanning().addStrategySettings(tam); // run Controler controler = new Controler(scenario); - controler.getConfig().controler().setWriteEventsInterval(0); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(0); + controler.getConfig().controller().setCreateGraphs(false); controler.run(); // checks diff --git a/matsim/src/test/java/org/matsim/core/controler/corelisteners/ListenersInjectionTest.java b/matsim/src/test/java/org/matsim/core/controler/corelisteners/ListenersInjectionTest.java index 29b92632a2b..ca53da64631 100644 --- a/matsim/src/test/java/org/matsim/core/controler/corelisteners/ListenersInjectionTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/corelisteners/ListenersInjectionTest.java @@ -73,7 +73,7 @@ public void testPlansScoringIsSingleton() { private void testIsSingleton( final Class klass ) { final Config config = ConfigUtils.createConfig(); final String outputDir = utils.getOutputDirectory(); - config.controler().setOutputDirectory( outputDir ); + config.controller().setOutputDirectory( outputDir ); final com.google.inject.Injector injector = Injector.createInjector( config, @@ -86,7 +86,7 @@ public void install() { bind(ControlerListenerManager.class).to(ControlerListenerManagerImpl.class); bind(OutputDirectoryHierarchy.class).toInstance(new OutputDirectoryHierarchy(outputDir, OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists, - config.controler().getCompressionType())); + config.controller().getCompressionType())); bind(IterationStopWatch.class).toInstance(new IterationStopWatch()); bind(IterationCounter.class).toInstance(() -> 0); install(new ScenarioByInstanceModule(ScenarioUtils.createScenario(config))); diff --git a/matsim/src/test/java/org/matsim/core/controler/corelisteners/PlansDumpingIT.java b/matsim/src/test/java/org/matsim/core/controler/corelisteners/PlansDumpingIT.java index 6bb6709fced..ee429308a3a 100644 --- a/matsim/src/test/java/org/matsim/core/controler/corelisteners/PlansDumpingIT.java +++ b/matsim/src/test/java/org/matsim/core/controler/corelisteners/PlansDumpingIT.java @@ -40,11 +40,11 @@ public class PlansDumpingIT { @Test public void testPlansDump_Interval() { Config config = this.util.loadConfig("test/scenarios/equil/config_plans1.xml"); - config.controler().setLastIteration(10); - config.controler().setWritePlansInterval(3); + config.controller().setLastIteration(10); + config.controller().setWritePlansInterval(3); Controler c = new Controler(config); - c.getConfig().controler().setWriteEventsInterval(0); - c.getConfig().controler().setCreateGraphs(false); + c.getConfig().controller().setWriteEventsInterval(0); + c.getConfig().controller().setCreateGraphs(false); c.run(); @@ -64,11 +64,11 @@ public void testPlansDump_Interval() { @Test public void testPlansDump_Never() { Config config = this.util.loadConfig("test/scenarios/equil/config_plans1.xml"); - config.controler().setLastIteration(10); - config.controler().setWritePlansInterval(0); + config.controller().setLastIteration(10); + config.controller().setWritePlansInterval(0); Controler c = new Controler(config); - c.getConfig().controler().setWriteEventsInterval(0); - c.getConfig().controler().setCreateGraphs(false); + c.getConfig().controller().setWriteEventsInterval(0); + c.getConfig().controller().setCreateGraphs(false); c.run(); @@ -88,11 +88,11 @@ public void testPlansDump_Never() { @Test public void testPlansDump_Always() { Config config = this.util.loadConfig("test/scenarios/equil/config_plans1.xml"); - config.controler().setLastIteration(10); - config.controler().setWritePlansInterval(1); + config.controller().setLastIteration(10); + config.controller().setWritePlansInterval(1); Controler c = new Controler(config); - c.getConfig().controler().setWriteEventsInterval(0); - c.getConfig().controler().setCreateGraphs(false); + c.getConfig().controller().setWriteEventsInterval(0); + c.getConfig().controller().setCreateGraphs(false); c.run(); diff --git a/matsim/src/test/java/org/matsim/core/events/algorithms/EventWriterJsonTest.java b/matsim/src/test/java/org/matsim/core/events/algorithms/EventWriterJsonTest.java index 09606e024e2..9756af4c134 100644 --- a/matsim/src/test/java/org/matsim/core/events/algorithms/EventWriterJsonTest.java +++ b/matsim/src/test/java/org/matsim/core/events/algorithms/EventWriterJsonTest.java @@ -7,7 +7,7 @@ import org.matsim.api.core.v01.events.LinkLeaveEvent; import org.matsim.api.core.v01.network.Link; 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.MatsimEventsReader; import org.matsim.testcases.utils.EventsCollector; @@ -40,7 +40,7 @@ public void testSpecialCharacters() { EventsCollector collector = new EventsCollector(); events.addHandler(collector); events.initProcessing(); - new MatsimEventsReader(events).readStream(bios, ControlerConfigGroup.EventsFileFormat.json); + new MatsimEventsReader(events).readStream(bios, ControllerConfigGroup.EventsFileFormat.json); events.finishProcessing(); Assert.assertEquals("there must be 2 events.", 2, collector.getEvents().size()); @@ -72,7 +72,7 @@ public void testNullAttribute() { EventsCollector collector = new EventsCollector(); events.addHandler(collector); events.initProcessing(); - new MatsimEventsReader(events).readStream(bios, ControlerConfigGroup.EventsFileFormat.json); + new MatsimEventsReader(events).readStream(bios, ControllerConfigGroup.EventsFileFormat.json); events.finishProcessing(); Assert.assertEquals("there must be 1 event.", 1, collector.getEvents().size()); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/hermes/HermesRoundaboutTest.java b/matsim/src/test/java/org/matsim/core/mobsim/hermes/HermesRoundaboutTest.java index b5ca0b9ea82..ff2e28c9e31 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/hermes/HermesRoundaboutTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/hermes/HermesRoundaboutTest.java @@ -39,9 +39,9 @@ import org.matsim.api.core.v01.population.PopulationFactory; 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.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; +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.network.NetworkUtils; @@ -68,8 +68,8 @@ public class HermesRoundaboutTest { public void testRoundaboutBehavior(){ ScenarioImporter.flush(); final Config config = createConfig(); - config.controler().setMobsim("hermes"); - config.parallelEventHandling().setOneThreadPerHandler(true); + config.controller().setMobsim("hermes"); + config.eventsManager().setOneThreadPerHandler(true); Scenario scenario = ScenarioUtils.createScenario(config); buildRoundaboutNetwork(scenario); buildPopulation(scenario); @@ -87,26 +87,26 @@ public void testRoundaboutBehavior(){ private Config createConfig() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); config.qsim().setUsePersonIdForMissingVehicleId(true); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(2); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); //standard accessEgressMode is walk + config.controller().setFirstIteration(0); + config.controller().setLastIteration(2); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); //standard accessEgressMode is walk - final PlanCalcScoreConfigGroup.ActivityParams homeParams = new PlanCalcScoreConfigGroup.ActivityParams("home"); + final ScoringConfigGroup.ActivityParams homeParams = new ScoringConfigGroup.ActivityParams("home"); homeParams.setTypicalDuration(1); - config.planCalcScore().addActivityParams(homeParams); + config.scoring().addActivityParams(homeParams); - final PlanCalcScoreConfigGroup.ActivityParams workParams = new PlanCalcScoreConfigGroup.ActivityParams("work"); + final ScoringConfigGroup.ActivityParams workParams = new ScoringConfigGroup.ActivityParams("work"); workParams.setTypicalDuration(1); - config.planCalcScore().addActivityParams(workParams); + config.scoring().addActivityParams(workParams); - StrategyConfigGroup.StrategySettings replanning = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings replanning = new ReplanningConfigGroup.StrategySettings(); replanning.setStrategyName("ReRoute"); replanning.setWeight(1.0); - config.strategy().addStrategySettings(replanning); + config.replanning().addStrategySettings(replanning); return config; } @@ -190,7 +190,7 @@ private void buildRoundaboutNetwork(Scenario scenario) { Link dd1 = NetworkUtils.createAndAddLink(network,Id.createLinkId("d_d1"),d,d1,20,8,1100,1); Link d1d2 = NetworkUtils.createAndAddLink(network,Id.createLinkId("d1_d2"),d1,d2,2000,8,720000,1); Link d2d1 = NetworkUtils.createAndAddLink(network,Id.createLinkId("d2_d1"),d2,d1,2000,8,720000,1); - + } diff --git a/matsim/src/test/java/org/matsim/core/mobsim/hermes/StorageCapacityTest.java b/matsim/src/test/java/org/matsim/core/mobsim/hermes/StorageCapacityTest.java index c0488b7d76a..bd3289bc276 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/hermes/StorageCapacityTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/hermes/StorageCapacityTest.java @@ -234,7 +234,7 @@ public void testStorageCapacityWithDifferentPCUs() { public void testStorageCapacityWithVaryingPCUs() { ScenarioImporter.flush(); Config config = ConfigUtils.createConfig(); - config.plansCalcRoute().setNetworkModes(Set.of(TransportMode.car, TransportMode.truck)); + config.routing().setNetworkModes(Set.of(TransportMode.car, TransportMode.truck)); config.hermes().setStuckTime(Integer.MAX_VALUE); config.hermes().setMainModes(Set.of(TransportMode.car, TransportMode.truck)); Scenario scenario = ScenarioUtils.createScenario(config); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/AbstractQSimModuleTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/AbstractQSimModuleTest.java index 9dfedb7daba..02166c720bb 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/AbstractQSimModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/AbstractQSimModuleTest.java @@ -47,7 +47,7 @@ import com.google.inject.Inject; import com.google.inject.Injector; -public class AbstractQSimModuleTest { +public class AbstractQSimModuleTest { @Test public void testOverrides() { AbstractQSimModule moduleA = new AbstractQSimModule() { @@ -83,8 +83,8 @@ protected void configureQSim() { @Test public void testOverrideAgentFactory() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -103,12 +103,12 @@ public void testOverrideAgentFactory() { Assert.assertTrue(value.get() > 0); } - + @Test public void testOverrideAgentFactoryTwice() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); Scenario scenario = ScenarioUtils.loadScenario(config); @@ -165,8 +165,8 @@ public MobsimAgent createMobsimAgentFromPerson(Person p) { @Test public void testAddEngine() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); Scenario scenario = ScenarioUtils.loadScenario(config); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/AgentNotificationTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/AgentNotificationTest.java index 908e80db324..55a02dfcfd6 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/AgentNotificationTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/AgentNotificationTest.java @@ -52,7 +52,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.events.EventsUtils; import org.matsim.core.mobsim.framework.MobsimAgent; import org.matsim.core.mobsim.framework.MobsimDriverAgent; @@ -306,10 +306,10 @@ protected Double featureValueOf(Event event) { private static Scenario createSimpleScenario() { final Config config = ConfigUtils.createConfig(); - PlansCalcRouteConfigGroup.TeleportedModeParams params = new PlansCalcRouteConfigGroup.TeleportedModeParams( TransportMode.walk ) ; + RoutingConfigGroup.TeleportedModeParams params = new RoutingConfigGroup.TeleportedModeParams( TransportMode.walk ) ; params.setBeelineDistanceFactor(1.3); params.setTeleportedModeSpeed(1.); - config.plansCalcRoute().addModeRoutingParams( params ); + config.routing().addModeRoutingParams( params ); Scenario scenario = ScenarioUtils.createScenario(config); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/NetsimRoutingConsistencyTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/NetsimRoutingConsistencyTest.java index 5e778cd0ebc..c93509f82c9 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/NetsimRoutingConsistencyTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/NetsimRoutingConsistencyTest.java @@ -46,7 +46,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -70,53 +70,53 @@ public class NetsimRoutingConsistencyTest { * This test shows that the travel time that is predicted with the * NetworkRoutingModule is NOT equivalent to the travel time that is produced by * the Netsim. - * + * * The scenario is as follows: - * - * N1 ----- N2 ----- N3 ----- N4 ----- N5 + * + * N1 ----- N2 ----- N3 ----- N4 ----- N5 * L12 L23 L34 L45 - * + * * There are nodes Ni and connecting links Lij. There is one agent P who wants * to depart at L12 and arrive at L45. He has a plan with an activity at L12 and * another one at L45 and a connecting leg by car. - * + * * This car leg is produced (as would be in the full stack simulation) using the * NetworkRoutingModule. For the disutility OnlyTimeDependentDisutility is used, * for the TravelTime, freespeed is used. The freespeed of all links is 10, * while the length is 1000, hence the traversal time for each link is 100. - * + * * Accordingly, the NetworkRoutingModule produces a Leg for the agent with a * travel time of - * + * * routingTravelTime = 200.0 - * + * * because link L23 and L45 are taken into account. As expected the routing goes * from the end node of the departure link to the start node of the arrival * link. We already know that this will not be the true Netsim simulated time, * because traversal times are rounded up. So we would expect a - * + * * adjustedRoutingTravelTime = 202.0 - * + * * because we need to add 1s per traversed link. - * + * * Now, the scenario is simulated using the QSim/Netsim. An event handler is set * up that captures the only "departure" event and the only "arrival" event in * the simulation (which is produced by the leg of the agent). The travel time * can be computed an we get: - * + * * netsimTravelTime = 303.0 - * + * * Apparently, looking at QueueWithBuffer::moveQueueToBuffer , the agent needs * to traverse the arrival link before he can arrive there. This leads to a * travel time that is higher than expected by the router and so predictions * done by the NetworkRoutingModule are inconsistent. - * - * Not sure, what to do about that. Possible options: - * - Adjust Netsim such that agents arrive before they traverse the arrival link - * - Adjust the car routing such that the travel time of the final link is added - * - Adjust the car routing such that the routing goes to the end node of the arrival link + * + * Not sure, what to do about that. Possible options: + * - Adjust Netsim such that agents arrive before they traverse the arrival link + * - Adjust the car routing such that the travel time of the final link is added + * - Adjust the car routing such that the routing goes to the end node of the arrival link * - Explicitly document this behaviour somewhere - * + * * I guess usually this should not make such a big difference for MATSim, * because the shortest path is found anyway. However, if one wants to predict * travel times one should state that the NetworkRoutingModule has a bias by the @@ -208,19 +208,19 @@ public void testRoutingVsSimulation() { @Test /* - * The same test as above, but here the full stack MATSim setup is used (i.e. the + * The same test as above, but here the full stack MATSim setup is used (i.e. the * NetworkRoutingModule, etc. are created implicitly by the Controler). */ public void testRoutingVsSimulationFullStack() { Config config = ConfigUtils.createConfig(); - - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); - + + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); + ActivityParams activityParams = new ActivityParams("A"); activityParams.setTypicalDuration(100.0); - config.planCalcScore().addActivityParams(activityParams); - + config.scoring().addActivityParams(activityParams); + Scenario scenario = ScenarioUtils.createScenario(config); Network network = scenario.getNetwork(); @@ -266,11 +266,11 @@ public void testRoutingVsSimulationFullStack() { Plan plan = population.getFactory().createPlan(); person.addPlan(plan); - + plan.addActivity(startActivity); plan.addLeg(population.getFactory().createLeg(TransportMode.car)); plan.addActivity(endActivity); - + DepartureArrivalListener listener = new DepartureArrivalListener(); Controler controler = new Controler(scenario); @@ -280,7 +280,7 @@ public void install() { addEventHandlerBinding().toInstance(listener); } }); - + controler.run(); double netsimTravelTime = listener.arrivalTime - listener.departureTime; @@ -293,7 +293,7 @@ public void install() { Assert.assertEquals(netsimTravelTime, 303.0, 1e-3); Assert.assertEquals(adjustedRoutingTravelTime, 202.0, 1e-3); } - + class DepartureArrivalListener implements PersonDepartureEventHandler, PersonArrivalEventHandler { public double departureTime = Double.NaN; public double arrivalTime = Double.NaN; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/NodeTransitionTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/NodeTransitionTest.java index 5aeef0878d4..954f61a3eda 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/NodeTransitionTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/NodeTransitionTest.java @@ -46,7 +46,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.NodeTransition; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.controler.PrepareForSimUtils; @@ -59,22 +59,22 @@ /** * Test the different node transition options that one can choose in the qsim config group. * EmptyBufferAfterBuffer and blockNodeWhenSingleOutlinkFull = false currently is the MATSim standard. - * - * This test checks the throughput of links in two different scenarios: + * + * This test checks the throughput of links in two different scenarios: * 1. A merge situation, where agents coming from three different links all want to enter the same downstream link with restricted capacity. * 2. An intersection, where agents coming from two different links do not use same links but might affect each other when the flag blockNodeWhenSingleOutlinkFull is set to true. - * + * * While implementing and significantly testing the new node transitions some bugs have been found in QueueWithBuffer regarding half empty buffers and time step sizes < 1. * This tests therefore also validates the bug fixes (see e.g. testNodeTransitionWithTimeStepSizeSmallerOne). - * + * * The results should be the same independently of slow/fast capacity update. That's why the test is run for both (parameterized). - * + * * @author tthunig * */ @RunWith(Parameterized.class) public class NodeTransitionTest { - + @Parameterized.Parameters(name = "{index}: useFastCapUpdate == {0};") public static Collection parameterObjects() { return Arrays.asList(new Object[][]{ @@ -82,19 +82,19 @@ public static Collection parameterObjects() { {false} }); } - + private boolean useFastCapUpdate; - + public NodeTransitionTest(boolean useFastCapUpdate) { this.useFastCapUpdate = useFastCapUpdate; } - + @Test public void testMergeSituationWithEmptyBufferAfterBufferRandomDistribution() { Scenario scenario = Fixture.createMergeScenario(); scenario.getConfig().qsim().setNodeTransitionLogic(NodeTransition.emptyBufferAfterBufferRandomDistribution_dontBlockNode); scenario.getConfig().qsim().setUsingFastCapacityUpdate(useFastCapUpdate); - + EventsManager events = EventsUtils.createEventsManager(); List> linksOfInterest = new LinkedList<>(); linksOfInterest.add(Id.createLinkId("2_7")); @@ -102,14 +102,14 @@ public void testMergeSituationWithEmptyBufferAfterBufferRandomDistribution() { linksOfInterest.add(Id.createLinkId("6_7")); ThroughputAnalyzer throughputAnalyzer = new ThroughputAnalyzer(linksOfInterest); events.addHandler(throughputAnalyzer); - + PrepareForSimUtils.createDefaultPrepareForSim(scenario).run(); new QSimBuilder(scenario.getConfig()) .useDefaults() .build(scenario, events) .run(); - + // this is the time before the downstream link (7_8) gets full and with that no inflow capacity is valid int timeInterval1Start = 110; int timeInterval1End = 180; Map, Double> avgThroughputFreeFlow = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(timeInterval1Start, timeInterval1End, 1); @@ -124,31 +124,31 @@ public void testMergeSituationWithEmptyBufferAfterBufferRandomDistribution() { + "\t; time interval [" + timeInterval2Start + ", " + timeInterval2End + "]: " + avgThroughputCongestedTwoLinks.get(link) + "\t; time interval [" + timeInterval3Start + ", " + timeInterval3End + "]: " + avgThroughputCongestedThreeLinks.get(link)); } - - /* since this node dynamic is a random distribution we allow a somewhat bigger difference here. + + /* since this node dynamic is a random distribution we allow a somewhat bigger difference here. * otherwise we would need to run the test for a longer period or different random seeds which would increase the run time of this test. */ double delta = 0.1; - + // test throughput for the first time interval - /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. + /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. * the commodity on link 6_7 has not begun to send vehicles, i.e. the corresponding throughput should be 0 */ Assert.assertEquals("Troughput on link 2_7 is wrong", 1, avgThroughputFreeFlow.get(Id.createLinkId("2_7")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 4_7 is wrong", 2, avgThroughputFreeFlow.get(Id.createLinkId("4_7")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 6_7 is wrong", 0, avgThroughputFreeFlow.get(Id.createLinkId("6_7")), MatsimTestUtils.EPSILON); - + // test throughput for the second time interval - /* with probability of 2/3 link 4_7 is selected and sends all vehicles from its buffer, i.e. 2; + /* with probability of 2/3 link 4_7 is selected and sends all vehicles from its buffer, i.e. 2; * with probability of 1/3 link 2_7 is selected and sends all vehicles from its buffer, i.e. 1 and afterwards link 4_7 can send the remaining 1. * this means, the expected average throughput of link 2_7 is 1/3 and the expected average throughput of link 4_7 is 2*2/3 + 1/3 = 5/3. */ Assert.assertEquals("Troughput on link 2_7 is wrong", 1./3, avgThroughputCongestedTwoLinks.get(Id.createLinkId("2_7")), delta); // 0.25384615384615383 Assert.assertEquals("Troughput on link 4_7 is wrong", 5./3, avgThroughputCongestedTwoLinks.get(Id.createLinkId("4_7")), delta); // 1.7461538461538462 Assert.assertEquals("Troughput on link 6_7 is wrong", 0, avgThroughputCongestedTwoLinks.get(Id.createLinkId("6_7")), MatsimTestUtils.EPSILON); - + // test throughput for the third time interval /* with probability of 2/5 link 4_7 is selected and sends all vehicles from its buffer, i.e. 2; - * with probability of 2/5 link 6_7 is selected and sends all vehicles from its buffer, i.e. 2; + * with probability of 2/5 link 6_7 is selected and sends all vehicles from its buffer, i.e. 2; * with probability of 1/5 link 2_7 is selected and sends all vehicles from its buffer, i.e. 1 and afterwards link 4_7 or link 6_7 can send the remaining 1. * this means, the expected average throughput of link 2_7 is 1/5 and the expected average throughput of link 4_7 and link 6_7 is 2*2/5 + 1/10 = 9/10. */ @@ -156,13 +156,13 @@ public void testMergeSituationWithEmptyBufferAfterBufferRandomDistribution() { Assert.assertEquals("Troughput on link 4_7 is wrong", 9./10, avgThroughputCongestedThreeLinks.get(Id.createLinkId("4_7")), delta); // 0.8928571428571429 Assert.assertEquals("Troughput on link 6_7 is wrong", 9./10, avgThroughputCongestedThreeLinks.get(Id.createLinkId("6_7")), delta); // 0.9285714285714286 } - + @Test public void testMergeSituationWithMoveVehByVehRandomDistribution() { Scenario scenario = Fixture.createMergeScenario(); scenario.getConfig().qsim().setNodeTransitionLogic(NodeTransition.moveVehByVehRandomDistribution_dontBlockNode); scenario.getConfig().qsim().setUsingFastCapacityUpdate(useFastCapUpdate); - + EventsManager events = EventsUtils.createEventsManager(); List> linksOfInterest = new LinkedList<>(); linksOfInterest.add(Id.createLinkId("2_7")); @@ -170,14 +170,14 @@ public void testMergeSituationWithMoveVehByVehRandomDistribution() { linksOfInterest.add(Id.createLinkId("6_7")); ThroughputAnalyzer throughputAnalyzer = new ThroughputAnalyzer(linksOfInterest); events.addHandler(throughputAnalyzer); - + PrepareForSimUtils.createDefaultPrepareForSim(scenario).run(); new QSimBuilder(scenario.getConfig()) .useDefaults() .build(scenario, events) .run(); - + // this is the time before the downstream link (7_8) gets full and with that no inflow capacity is valid int timeInterval1Start = 110; int timeInterval1End = 180; Map, Double> avgThroughputFreeFlow = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(timeInterval1Start, timeInterval1End, 1); @@ -192,32 +192,32 @@ public void testMergeSituationWithMoveVehByVehRandomDistribution() { + "\t; time interval [" + timeInterval2Start + ", " + timeInterval2End + "]: " + avgThroughputCongestedTwoLinks.get(link) + "\t; time interval [" + timeInterval3Start + ", " + timeInterval3End + "]: " + avgThroughputCongestedThreeLinks.get(link)); } - - /* since this node dynamic is a random distribution we allow a somewhat bigger difference here. + + /* since this node dynamic is a random distribution we allow a somewhat bigger difference here. * otherwise we would need to run the test for a longer period or different random seeds which would increase the run time of this test. * note, that these random values can even differ when all tests are run after each other or when they are run separately */ double delta = 0.04; - + // test throughput for the first time interval - /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. + /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. * the commodity on link 6_7 has not begun to send vehicles, i.e. the corresponding throughput should be 0 */ Assert.assertEquals("Troughput on link 2_7 is wrong", 1, avgThroughputFreeFlow.get(Id.createLinkId("2_7")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 4_7 is wrong", 2, avgThroughputFreeFlow.get(Id.createLinkId("4_7")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 6_7 is wrong", 0, avgThroughputFreeFlow.get(Id.createLinkId("6_7")), MatsimTestUtils.EPSILON); - + // test throughput for the second time interval /* with probability of 2/3 link 4_7 is selected and sends one vehicle; afterwards with probability of 2/3 link 4_7 is allowed to send the second vehicle, with probability 1/3 link 2_7 is allowed to send one. * with probability of 1/3 link 2_7 is selected and sends one vehicle; afterwards link 4_7 will send the remaining one, because the buffer of link 2_7 is empty anyway. * this means, the expected average throughput of link 2_7 will get underestimated because the random distribution is cut at one and will never overestimate above this number. * consequently, the expected average throughput of link 4_7 will get overestimated. - * the numbers are as follows: the expected average throughput of link 2_7 is 2/3*1/3*1 + 1/3*1 = 5/9 + * the numbers are as follows: the expected average throughput of link 2_7 is 2/3*1/3*1 + 1/3*1 = 5/9 * and the expected average throughput of link 4_7 is 2/3*2/3*2 + 2/3*1/3*1 + 1/3*1 = 13/9 */ Assert.assertEquals("Troughput on link 2_7 is wrong", 5./9, avgThroughputCongestedTwoLinks.get(Id.createLinkId("2_7")), delta); // 0.5307692307692308 Assert.assertEquals("Troughput on link 4_7 is wrong", 13./9, avgThroughputCongestedTwoLinks.get(Id.createLinkId("4_7")), delta); // 1.4692307692307693 Assert.assertEquals("Troughput on link 6_7 is wrong", 0, avgThroughputCongestedTwoLinks.get(Id.createLinkId("6_7")), MatsimTestUtils.EPSILON); - + // test throughput for the third time interval /* the first vehicle is send by link 2_7 with probability of 1/5 and by one of the other two links with probability 2/5. * if link 4_7 or 6_7 have send the first vehicle, the same probability will hold for the second vehicle. @@ -231,14 +231,14 @@ public void testMergeSituationWithMoveVehByVehRandomDistribution() { Assert.assertEquals("Troughput on link 4_7 is wrong", 41./50, avgThroughputCongestedThreeLinks.get(Id.createLinkId("4_7")), delta); // 0.8 Assert.assertEquals("Troughput on link 6_7 is wrong", 41./50, avgThroughputCongestedThreeLinks.get(Id.createLinkId("6_7")), delta); // 0.8571428571428571 } - + @Test public void testMergeSituationWithMoveVehByVehDeterministicPriorities() { Scenario scenario = Fixture.createMergeScenario(); scenario.getConfig().qsim().setNodeTransitionLogic(NodeTransition.moveVehByVehDeterministicPriorities_nodeBlockedWhenSingleOutlinkFull); // note: the deterministic node transition is only implemented for the case when the node is blocked as soon as one outgoing link is full scenario.getConfig().qsim().setUsingFastCapacityUpdate(useFastCapUpdate); - + EventsManager events = EventsUtils.createEventsManager(); List> linksOfInterest = new LinkedList<>(); linksOfInterest.add(Id.createLinkId("2_7")); @@ -246,14 +246,14 @@ public void testMergeSituationWithMoveVehByVehDeterministicPriorities() { linksOfInterest.add(Id.createLinkId("6_7")); ThroughputAnalyzer throughputAnalyzer = new ThroughputAnalyzer(linksOfInterest); events.addHandler(throughputAnalyzer); - + PrepareForSimUtils.createDefaultPrepareForSim(scenario).run(); new QSimBuilder(scenario.getConfig()) .useDefaults() .build(scenario, events) .run(); - + // this is the time before the downstream link (7_8) gets full and with that no inflow capacity is valid int timeInterval1Start = 110; int timeInterval1End = 180; Map, Double> avgThroughputFreeFlow = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(timeInterval1Start, timeInterval1End, 1); @@ -268,22 +268,22 @@ public void testMergeSituationWithMoveVehByVehDeterministicPriorities() { + "\t; time interval [" + timeInterval2Start + ", " + timeInterval2End + "]: " + avgThroughputCongestedTwoLinks.get(link) + "\t; time interval [" + timeInterval3Start + ", " + timeInterval3End + "]: " + avgThroughputCongestedThreeLinks.get(link)); } - - /* since this node dynamic does not rely on a random distribution but updates link priorities each time step, - * i.e. remembers decisions made in previous time steps, + + /* since this node dynamic does not rely on a random distribution but updates link priorities each time step, + * i.e. remembers decisions made in previous time steps, * the difference to the expected values should be much smaller compared to the other node transition logic. * still, for periodic numbers a higher accuracy would only be reached by longer simulation times */ double delta = MatsimTestUtils.EPSILON; double deltaPeriodic = 0.01; - + // test throughput for the first time interval - /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. + /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. * the commodity on link 6_7 has not begun to send vehicles, i.e. the corresponding throughput should be 0 */ Assert.assertEquals("Troughput on link 2_7 is wrong", 1, avgThroughputFreeFlow.get(Id.createLinkId("2_7")), delta); Assert.assertEquals("Troughput on link 4_7 is wrong", 2, avgThroughputFreeFlow.get(Id.createLinkId("4_7")), delta); Assert.assertEquals("Troughput on link 6_7 is wrong", 0, avgThroughputFreeFlow.get(Id.createLinkId("6_7")), delta); - + // test throughput for the second time interval /* the deterministic node transition should distribute the free slots on the downstream link exactly proportional to the outflow capacity of the links, * i.e. 1:2 in this case @@ -291,7 +291,7 @@ public void testMergeSituationWithMoveVehByVehDeterministicPriorities() { Assert.assertEquals("Troughput on link 2_7 is wrong", 1./3 * 2, avgThroughputCongestedTwoLinks.get(Id.createLinkId("2_7")), deltaPeriodic); // 0.6692307692307692 Assert.assertEquals("Troughput on link 4_7 is wrong", 2./3 * 2, avgThroughputCongestedTwoLinks.get(Id.createLinkId("4_7")), deltaPeriodic); // 1.3307692307692307 Assert.assertEquals("Troughput on link 6_7 is wrong", 0, avgThroughputCongestedTwoLinks.get(Id.createLinkId("6_7")), delta); - + // test throughput for the third time interval /* the deterministic node transition should distribute the free slots on the downstream link exactly proportional to the outflow capacity of the links, * i.e. 1:2:2 in this case. @@ -300,13 +300,13 @@ public void testMergeSituationWithMoveVehByVehDeterministicPriorities() { Assert.assertEquals("Troughput on link 4_7 is wrong", 2./5 * 2, avgThroughputCongestedThreeLinks.get(Id.createLinkId("4_7")), delta); // 0.8 Assert.assertEquals("Troughput on link 6_7 is wrong", 2./5 * 2, avgThroughputCongestedThreeLinks.get(Id.createLinkId("6_7")), delta); // 0.8 } - + @Test public void testBlockedNodeSituationWithEmptyBufferAfterBufferRandomDistribution() { Scenario scenario = Fixture.createBlockedNodeScenario(); scenario.getConfig().qsim().setNodeTransitionLogic(NodeTransition.emptyBufferAfterBufferRandomDistribution_nodeBlockedWhenSingleOutlinkFull); scenario.getConfig().qsim().setUsingFastCapacityUpdate(useFastCapUpdate); - + EventsManager events = EventsUtils.createEventsManager(); List> linksOfInterest = new LinkedList<>(); linksOfInterest.add(Id.createLinkId("2_5")); @@ -314,25 +314,25 @@ public void testBlockedNodeSituationWithEmptyBufferAfterBufferRandomDistribution linksOfInterest.add(Id.createLinkId("5_8")); ThroughputAnalyzer throughputAnalyzer = new ThroughputAnalyzer(linksOfInterest); events.addHandler(throughputAnalyzer); - + PrepareForSimUtils.createDefaultPrepareForSim(scenario).run(); new QSimBuilder(scenario.getConfig()) .useDefaults() .build(scenario, events) .run(); - + // // output for debugging // for (int start = 0; start <= 800; start+=10) { // Map, Double> avgThroughputThisInterval = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(start, start+10, 1); -// System.out.println("[" + start + ", " + (start+10) + "]. link 2_5: " + avgThroughputThisInterval.get(Id.createLinkId("2_5")) +// System.out.println("[" + start + ", " + (start+10) + "]. link 2_5: " + avgThroughputThisInterval.get(Id.createLinkId("2_5")) // + ", link 4_5: " + avgThroughputThisInterval.get(Id.createLinkId("4_5")) -// + ", link 5_8: " + avgThroughputThisInterval.get(Id.createLinkId("5_8"))); +// + ", link 5_8: " + avgThroughputThisInterval.get(Id.createLinkId("5_8"))); // } // Map, Double> avgThroughputUntil210 = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(0, 210, 1); // System.out.println("absolute throughput [" + 0 + ", " + 210 + "]. link 2_5: " + (avgThroughputUntil210.get(Id.createLinkId("2_5")) * 210 / 1) // + ", link 4_5: " + (avgThroughputUntil210.get(Id.createLinkId("4_5")) * 210 / 1) ); - + // this is the time before the downstream link (5_8) gets full and with that no inflow capacity is valid and no node is blocked int timeInterval1Start = 110; int timeInterval1End = 200; Map, Double> avgThroughputFreeFlow = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(timeInterval1Start, timeInterval1End, 1); @@ -347,20 +347,20 @@ public void testBlockedNodeSituationWithEmptyBufferAfterBufferRandomDistribution + "\t; time interval [" + timeInterval2Start + ", " + timeInterval2End + "]: " + avgThroughputCongestedNodeBlocked.get(link) + "\t; time interval [" + timeInterval3Start + ", " + timeInterval3End + "]: " + avgThroughputCongestedRestrictFlow.get(link)); } - - /* since this node dynamic is a random distribution we allow a somewhat bigger difference here. + + /* since this node dynamic is a random distribution we allow a somewhat bigger difference here. * otherwise we would need to run the test for a longer period or different random seeds which would increase the run time of this test. */ double delta = 0.04; - + // test throughput for the first time interval - /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. + /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be zero here. */ Assert.assertEquals("Troughput on link 2_5 is wrong", 2, avgThroughputFreeFlow.get(Id.createLinkId("2_5")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 4_5 is wrong", 1, avgThroughputFreeFlow.get(Id.createLinkId("4_5")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 5_8 is wrong", 0, avgThroughputFreeFlow.get(Id.createLinkId("5_8")), MatsimTestUtils.EPSILON); - + // test throughput for the second time interval /* with probability 1/3 link 4_5 is selected first and can send all its vehicles from the buffer (i.e. one) before link 2_5 blocks the intersection. * if link 2_5 is selected first the intersection is blocked immediately. @@ -369,25 +369,25 @@ public void testBlockedNodeSituationWithEmptyBufferAfterBufferRandomDistribution Assert.assertEquals("Troughput on link 2_5 is wrong", 0, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("2_5")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 4_5 is wrong", 1./3, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("4_5")), delta); // 0.36666666666666664 Assert.assertEquals("Troughput on link 5_8 is wrong", 0, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("5_8")), MatsimTestUtils.EPSILON); - + // test throughput for the third time interval /* with probability 1/3 link 4_5 is selected first and can send all its vehicles from the buffer (i.e. one) before link 2_5 sends its first one and blocks the intersection. * with probability 2/3 link 2_5 is selected first, sends one vehicle and thereby blocks the intersection. * this means the correct expected throughput values are: 1/3*1 for link 4_5 and 1/3*1 + 2/3*1 = 1 for link 2_5. - * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be equal to the flow + * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be equal to the flow * capacity of link 5_8 here, i.e. 1 veh per time step (=sec). */ Assert.assertEquals("Troughput on link 2_5 is wrong", 1, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("2_5")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 4_5 is wrong", 1./3, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("4_5")), delta); // 0.3263157894736842 Assert.assertEquals("Troughput on link 5_8 is wrong", 1, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("5_8")), MatsimTestUtils.EPSILON); } - + @Test public void testBlockedNodeSituationWithMoveVehByVehRandomDistribution() { Scenario scenario = Fixture.createBlockedNodeScenario(); scenario.getConfig().qsim().setNodeTransitionLogic(NodeTransition.moveVehByVehRandomDistribution_nodeBlockedWhenSingleOutlinkFull); scenario.getConfig().qsim().setUsingFastCapacityUpdate(useFastCapUpdate); - + EventsManager events = EventsUtils.createEventsManager(); List> linksOfInterest = new LinkedList<>(); linksOfInterest.add(Id.createLinkId("2_5")); @@ -395,25 +395,25 @@ public void testBlockedNodeSituationWithMoveVehByVehRandomDistribution() { linksOfInterest.add(Id.createLinkId("5_8")); ThroughputAnalyzer throughputAnalyzer = new ThroughputAnalyzer(linksOfInterest); events.addHandler(throughputAnalyzer); - + PrepareForSimUtils.createDefaultPrepareForSim(scenario).run(); new QSimBuilder(scenario.getConfig()) .useDefaults() .build(scenario, events) - .run(); + .run(); // // output for debugging // for (int start = 0; start <= 800; start+=10) { // Map, Double> avgThroughputThisInterval = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(start, start+10, 1); -// System.out.println("[" + start + ", " + (start+10) + "]. link 2_5: " + avgThroughputThisInterval.get(Id.createLinkId("2_5")) +// System.out.println("[" + start + ", " + (start+10) + "]. link 2_5: " + avgThroughputThisInterval.get(Id.createLinkId("2_5")) // + ", link 4_5: " + avgThroughputThisInterval.get(Id.createLinkId("4_5")) -// + ", link 5_8: " + avgThroughputThisInterval.get(Id.createLinkId("5_8"))); +// + ", link 5_8: " + avgThroughputThisInterval.get(Id.createLinkId("5_8"))); // } // Map, Double> avgThroughputUntil210 = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(0, 210, 1); // System.out.println("absolute throughput [" + 0 + ", " + 210 + "]. link 2_5: " + (avgThroughputUntil210.get(Id.createLinkId("2_5")) * 210 / 1) // + ", link 4_5: " + (avgThroughputUntil210.get(Id.createLinkId("4_5")) * 210 / 1) ); - + // this is the time before the downstream link (5_8) gets full and with that no inflow capacity is valid and no node is blocked int timeInterval1Start = 110; int timeInterval1End = 200; Map, Double> avgThroughputFreeFlow = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(timeInterval1Start, timeInterval1End, 1); @@ -428,20 +428,20 @@ public void testBlockedNodeSituationWithMoveVehByVehRandomDistribution() { + "\t; time interval [" + timeInterval2Start + ", " + timeInterval2End + "]: " + avgThroughputCongestedNodeBlocked.get(link) + "\t; time interval [" + timeInterval3Start + ", " + timeInterval3End + "]: " + avgThroughputCongestedRestrictFlow.get(link)); } - - /* since this node dynamic is a random distribution we allow a somewhat bigger difference here. + + /* since this node dynamic is a random distribution we allow a somewhat bigger difference here. * otherwise we would need to run the test for a longer period or different random seeds which would increase the run time of this test. */ double delta = 0.02; - + // test throughput for the first time interval - /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. + /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be zero here. */ Assert.assertEquals("Troughput on link 2_5 is wrong", 2, avgThroughputFreeFlow.get(Id.createLinkId("2_5")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 4_5 is wrong", 1, avgThroughputFreeFlow.get(Id.createLinkId("4_5")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 5_8 is wrong", 0, avgThroughputFreeFlow.get(Id.createLinkId("5_8")), MatsimTestUtils.EPSILON); - + // test throughput for the second time interval /* with probability 1/3 link 4_5 is selected first and can send one vehicle before link 2_5 blocks the intersection. * if link 2_5 is selected first the intersection is blocked immediately. @@ -450,26 +450,26 @@ public void testBlockedNodeSituationWithMoveVehByVehRandomDistribution() { Assert.assertEquals("Troughput on link 2_5 is wrong", 0, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("2_5")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 4_5 is wrong", 1./3, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("4_5")), delta); // 0.3333333333333333 Assert.assertEquals("Troughput on link 5_8 is wrong", 0, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("5_8")), MatsimTestUtils.EPSILON); - + // test throughput for the third time interval /* with probability 1/3 link 4_5 is selected first and can send one vehicle before link 2_5 sends its first one and blocks the intersection. - * with probability 2/3 link 2_5 is selected first and sends one vehicle; + * with probability 2/3 link 2_5 is selected first and sends one vehicle; * afterwards with probability 1/3 link 4_5 sends one vehicle before link 2_5 blocks the intersection, with probability 2/3 it is blocked immediately. * this means the correct expected throughput values are: 1/3*1 + 2/3*1/3*1 = 5/9 for link 4_5 and 1/3*1 + 2/3*1 = 1 for link 2_5. - * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be equal to the flow + * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be equal to the flow * capacity of link 5_8 here, i.e. 1 veh per time step (=sec). */ Assert.assertEquals("Troughput on link 2_5 is wrong", 1, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("2_5")), MatsimTestUtils.EPSILON); Assert.assertEquals("Troughput on link 4_5 is wrong", 5./9, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("4_5")), delta); // 0.5736842105263158 Assert.assertEquals("Troughput on link 5_8 is wrong", 1, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("5_8")), MatsimTestUtils.EPSILON); } - + @Test public void testBlockedNodeSituationWithMoveVehByVehDeterministicPriorities() { Scenario scenario = Fixture.createBlockedNodeScenario(); scenario.getConfig().qsim().setNodeTransitionLogic(NodeTransition.moveVehByVehDeterministicPriorities_nodeBlockedWhenSingleOutlinkFull); scenario.getConfig().qsim().setUsingFastCapacityUpdate(useFastCapUpdate); - + EventsManager events = EventsUtils.createEventsManager(); List> linksOfInterest = new LinkedList<>(); linksOfInterest.add(Id.createLinkId("2_5")); @@ -477,25 +477,25 @@ public void testBlockedNodeSituationWithMoveVehByVehDeterministicPriorities() { linksOfInterest.add(Id.createLinkId("5_8")); ThroughputAnalyzer throughputAnalyzer = new ThroughputAnalyzer(linksOfInterest); events.addHandler(throughputAnalyzer); - + PrepareForSimUtils.createDefaultPrepareForSim(scenario).run(); new QSimBuilder(scenario.getConfig()) .useDefaults() .build(scenario, events) .run(); - + // // output for debugging // for (int start = 0; start <= 800; start+=10) { // Map, Double> avgThroughputThisInterval = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(start, start+10, 1); -// System.out.println("[" + start + ", " + (start+10) + "]. link 2_5: " + avgThroughputThisInterval.get(Id.createLinkId("2_5")) +// System.out.println("[" + start + ", " + (start+10) + "]. link 2_5: " + avgThroughputThisInterval.get(Id.createLinkId("2_5")) // + ", link 4_5: " + avgThroughputThisInterval.get(Id.createLinkId("4_5")) -// + ", link 5_8: " + avgThroughputThisInterval.get(Id.createLinkId("5_8"))); +// + ", link 5_8: " + avgThroughputThisInterval.get(Id.createLinkId("5_8"))); // } // Map, Double> avgThroughputUntil210 = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(0, 210, 1); // System.out.println("absolute throughput [" + 0 + ", " + 210 + "]. link 2_5: " + (avgThroughputUntil210.get(Id.createLinkId("2_5")) * 210 / 1) // + ", link 4_5: " + (avgThroughputUntil210.get(Id.createLinkId("4_5")) * 210 / 1) ); - + // this is the time before the downstream link (5_8) gets full and with that no inflow capacity is valid and no node is blocked int timeInterval1Start = 110; int timeInterval1End = 200; Map, Double> avgThroughputFreeFlow = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(timeInterval1Start, timeInterval1End, 1); @@ -510,21 +510,21 @@ public void testBlockedNodeSituationWithMoveVehByVehDeterministicPriorities() { + "\t; time interval [" + timeInterval2Start + ", " + timeInterval2End + "]: " + avgThroughputCongestedNodeBlocked.get(link) + "\t; time interval [" + timeInterval3Start + ", " + timeInterval3End + "]: " + avgThroughputCongestedRestrictFlow.get(link)); } - - /* since this node dynamic does not rely on a random distribution but updates link priorities each time step, - * i.e. remembers decisions made in previous time steps, + + /* since this node dynamic does not rely on a random distribution but updates link priorities each time step, + * i.e. remembers decisions made in previous time steps, * the difference to the expected values should be much smaller compared to the other node transition logic. */ double delta = MatsimTestUtils.EPSILON; - + // test throughput for the first time interval - /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. + /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be zero here. */ Assert.assertEquals("Troughput on link 2_5 is wrong", 2, avgThroughputFreeFlow.get(Id.createLinkId("2_5")), delta); Assert.assertEquals("Troughput on link 4_5 is wrong", 1, avgThroughputFreeFlow.get(Id.createLinkId("4_5")), delta); Assert.assertEquals("Troughput on link 5_8 is wrong", 0, avgThroughputFreeFlow.get(Id.createLinkId("5_8")), delta); - + // test throughput for the second time interval /* the deterministic node transition should reduce the outflow of all links by the same percentage with which the outflow of links has to be reduced that lead to congested links. * in this case link 2_5 needs to be reduced by 100%, i.e. link 4_5 is also reduced by 100%, i.e. no link is allowed to send vehicles. @@ -534,20 +534,20 @@ public void testBlockedNodeSituationWithMoveVehByVehDeterministicPriorities() { Assert.assertEquals("Troughput on link 2_5 is wrong", 0, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("2_5")), delta); Assert.assertEquals("Troughput on link 4_5 is wrong", 0, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("4_5")), delta); Assert.assertEquals("Troughput on link 5_8 is wrong", 0, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("5_8")), delta); - + // test throughput for the third time interval /* the deterministic node transition should reduce the outflow of all links by the same percentage with which the outflow of links has to be reduced that lead to congested links. * in this case link 2_5 needs to be reduced by 1/2, i.e. link 4_5 is also reduced by 1/2. - * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be equal to the flow + * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be equal to the flow * capacity of link 5_8 here, i.e. 1 veh per time step (=sec). */ Assert.assertEquals("Troughput on link 2_5 is wrong", 1./2 * 2, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("2_5")), delta); Assert.assertEquals("Troughput on link 4_5 is wrong", 1./2 * 1, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("4_5")), delta); Assert.assertEquals("Troughput on link 5_8 is wrong", 1, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("5_8")), delta); } - + /** - * Test single intersection scenario with old emptyBufferAfterBuffer node transition and blockNode=false. Use time bin size 0.5 seconds. + * Test single intersection scenario with old emptyBufferAfterBuffer node transition and blockNode=false. Use time bin size 0.5 seconds. * With that the tests validates the following things: * 1. correct throughput for a time bin size smaller than 1 (see e.g. former bug in QueueWithBuffer removeFirstVehicle); * 2. correct storage capacity bounds for a time bin size smaller than 1 (see e.g. former bug in QueueWithBuffer calculateStorageCapacity); @@ -559,7 +559,7 @@ public void testNodeTransitionWithTimeStepSizeSmallerOne() { scenario.getConfig().qsim().setNodeTransitionLogic(NodeTransition.emptyBufferAfterBufferRandomDistribution_dontBlockNode); scenario.getConfig().qsim().setTimeStepSize(0.5); scenario.getConfig().qsim().setUsingFastCapacityUpdate(useFastCapUpdate); - + EventsManager events = EventsUtils.createEventsManager(); List> linksOfInterest = new LinkedList<>(); linksOfInterest.add(Id.createLinkId("2_5")); @@ -567,25 +567,25 @@ public void testNodeTransitionWithTimeStepSizeSmallerOne() { linksOfInterest.add(Id.createLinkId("5_8")); ThroughputAnalyzer throughputAnalyzer = new ThroughputAnalyzer(linksOfInterest); events.addHandler(throughputAnalyzer); - + PrepareForSimUtils.createDefaultPrepareForSim(scenario).run(); new QSimBuilder(scenario.getConfig()) .useDefaults() .build(scenario, events) .run(); - + // // output for debugging // for (int start = 0; start <= 800; start+=10) { // Map, Double> avgThroughputThisInterval = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(start, start+10, 0.5); -// System.out.println("[" + start + ", " + (start+10) + "]. link 2_5: " + avgThroughputThisInterval.get(Id.createLinkId("2_5")) +// System.out.println("[" + start + ", " + (start+10) + "]. link 2_5: " + avgThroughputThisInterval.get(Id.createLinkId("2_5")) // + ", link 4_5: " + avgThroughputThisInterval.get(Id.createLinkId("4_5")) -// + ", link 5_8: " + avgThroughputThisInterval.get(Id.createLinkId("5_8"))); +// + ", link 5_8: " + avgThroughputThisInterval.get(Id.createLinkId("5_8"))); // } // Map, Double> avgThroughputUntil210 = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(0, 210, 0.5); // System.out.println("absolute throughput [" + 0 + ", " + 210 + "]. link 2_5: " + (avgThroughputUntil210.get(Id.createLinkId("2_5")) * 210 / 0.5) -// + ", link 4_5: " + (avgThroughputUntil210.get(Id.createLinkId("4_5")) * 210 / 0.5) ); - +// + ", link 4_5: " + (avgThroughputUntil210.get(Id.createLinkId("4_5")) * 210 / 0.5) ); + // this is the time before the downstream link (5_8) gets full and with that no inflow capacity is valid and no node is blocked int timeInterval1Start = 110; int timeInterval1End = 200; Map, Double> avgThroughputFreeFlow = throughputAnalyzer.calculateAvgThroughputPerTimeStepOfTimeInterval(timeInterval1Start, timeInterval1End, 0.5); @@ -600,21 +600,21 @@ public void testNodeTransitionWithTimeStepSizeSmallerOne() { + "\t; time interval [" + timeInterval2Start + ", " + timeInterval2End + "]: " + avgThroughputCongestedNodeBlocked.get(link) + "\t; time interval [" + timeInterval3Start + ", " + timeInterval3End + "]: " + avgThroughputCongestedRestrictFlow.get(link)); } - - /* since this node dynamic does not rely on a random distribution but updates link priorities each time step, - * i.e. remembers decisions made in previous time steps, + + /* since this node dynamic does not rely on a random distribution but updates link priorities each time step, + * i.e. remembers decisions made in previous time steps, * the difference to the expected values should be much smaller compared to the other node transition logic. */ double delta = MatsimTestUtils.EPSILON; - + // test throughput for the first time interval - /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. + /* the downstream link is not full, i.e. the links can send vehicles with their full outflow capacity. * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be zero here. */ Assert.assertEquals("Troughput on link 2_5 is wrong", 1, avgThroughputFreeFlow.get(Id.createLinkId("2_5")), delta); Assert.assertEquals("Troughput on link 4_5 is wrong", 0.5, avgThroughputFreeFlow.get(Id.createLinkId("4_5")), delta); Assert.assertEquals("Troughput on link 5_8 is wrong", 0.0, avgThroughputFreeFlow.get(Id.createLinkId("5_8")), delta); - + // test throughput for the second time interval /* the downstream link of 2_5 is full, i.e. no vehicles can leave 2_5 in this time interval. * link 4_5 is not affected by this, because blockNodeWhenSingleOutlinkFull is set to false. @@ -623,31 +623,31 @@ public void testNodeTransitionWithTimeStepSizeSmallerOne() { Assert.assertEquals("Troughput on link 2_5 is wrong", 0, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("2_5")), delta); Assert.assertEquals("Troughput on link 4_5 is wrong", 0.5, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("4_5")), delta); Assert.assertEquals("Troughput on link 5_8 is wrong", 0.0, avgThroughputCongestedNodeBlocked.get(Id.createLinkId("5_8")), delta); - + // test throughput for the third time interval /* the downstream link of 2_5 lets 1 veh in every two time steps, i.e. throughput of link 2_5 should be 0.5 per time step. * link 4_5 should still be not affected by this and send vehicles with its outflow capacity, i.e 0.5 per time step. - * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be equal to the flow + * the first vehicles reach the end of link 5_8 around sec 300, i.e. throughput of link 5_8 should be equal to the flow * capacity of link 5_8 here, i.e. 0.5 veh per time step. */ Assert.assertEquals("Troughput on link 2_5 is wrong", 0.5, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("2_5")), delta); Assert.assertEquals("Troughput on link 4_5 is wrong", 0.5, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("4_5")), delta); Assert.assertEquals("Troughput on link 5_8 is wrong", 0.5, avgThroughputCongestedRestrictFlow.get(Id.createLinkId("5_8")), delta); } - + private static final class Fixture { - + static Scenario createMergeScenario() { MatsimRandom.reset(); Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); config.qsim().setStuckTime(24*3600); config.qsim().setRemoveStuckVehicles(false); - PlanCalcScoreConfigGroup.ActivityParams dummyAct = new PlanCalcScoreConfigGroup.ActivityParams("dummy"); + ScoringConfigGroup.ActivityParams dummyAct = new ScoringConfigGroup.ActivityParams("dummy"); dummyAct.setTypicalDuration(12 * 3600); - config.planCalcScore().addActivityParams(dummyAct); - + config.scoring().addActivityParams(dummyAct); + Scenario scenario = ScenarioUtils.createScenario(config); /* build network */ @@ -674,21 +674,21 @@ static Scenario createMergeScenario() { fillPopulationWithOneCommodity(scenario.getPopulation(), 1, 500, 0, link12.getId(), link89.getId()); fillPopulationWithOneCommodity(scenario.getPopulation(), 2, 500, 0, link34.getId(), link89.getId()); fillPopulationWithOneCommodity(scenario.getPopulation(), 2, 250, 250, link56.getId(), link89.getId()); - + return scenario; } - + static Scenario createBlockedNodeScenario() { MatsimRandom.reset(); Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); config.qsim().setStuckTime(24*3600); config.qsim().setRemoveStuckVehicles(false); - PlanCalcScoreConfigGroup.ActivityParams dummyAct = new PlanCalcScoreConfigGroup.ActivityParams("dummy"); + ScoringConfigGroup.ActivityParams dummyAct = new ScoringConfigGroup.ActivityParams("dummy"); dummyAct.setTypicalDuration(12 * 3600); - config.planCalcScore().addActivityParams(dummyAct); - + config.scoring().addActivityParams(dummyAct); + Scenario scenario = ScenarioUtils.createScenario(config); /* build network */ @@ -714,13 +714,13 @@ static Scenario createBlockedNodeScenario() { /* build plans */ fillPopulationWithOneCommodity(scenario.getPopulation(), 2, 500, 0, link12.getId(), link89.getId()); fillPopulationWithOneCommodity(scenario.getPopulation(), 1, 500, 0, link34.getId(), link67.getId()); - + return scenario; } - + private static void fillPopulationWithOneCommodity(Population population, double agentsPerSec, double simulationPeriod, double startTime, Id sourceLink, Id sinkLink) { - + for (int i=0; i< agentsPerSec * simulationPeriod; i++) { // create a person Person person = population.getFactory().createPerson(Id.createPersonId("agent-" + sourceLink + "-" + sinkLink + "-" + i)); @@ -743,21 +743,21 @@ private static void fillPopulationWithOneCommodity(Population population, double plan.addActivity(drainAct); } } - + } - + private final class ThroughputAnalyzer implements LinkLeaveEventHandler { private final List> linksOfInterest; private Map, Map> absoluteThroughputPerTimeStep_veh = new HashMap<>(); - + public ThroughputAnalyzer(List> linksOfInterest) { this.linksOfInterest = linksOfInterest; for (Id link : linksOfInterest) { absoluteThroughputPerTimeStep_veh.put(link, new TreeMap<>()); } } - + @Override public void reset(int iteration) { for (Id link : linksOfInterest) { @@ -777,13 +777,13 @@ public void handleEvent(LinkLeaveEvent event) { } } } - + public Map, Double> calculateAvgThroughputPerTimeStepOfTimeInterval(int startTime, int endTime, double timeStepSize) { Map, Double> avgThroughputPerLink = new HashMap<>(); for (Id link : linksOfInterest) { avgThroughputPerLink.put(link, 0.); } - + // sum up link leave events of this time interval for (double time = startTime; time < endTime; time += timeStepSize) { for (Id link : linksOfInterest) { @@ -796,10 +796,10 @@ public Map, Double> calculateAvgThroughputPerTimeStepOfTimeInterval(int for (Id link : linksOfInterest) { avgThroughputPerLink.put(link, avgThroughputPerLink.get(link) * timeStepSize / (endTime - startTime)); } - + return avgThroughputPerLink; } - + } - + } diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/QSimEventsIntegrationTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/QSimEventsIntegrationTest.java index 20d617bca25..09c873c3f2c 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/QSimEventsIntegrationTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/QSimEventsIntegrationTest.java @@ -62,8 +62,8 @@ public void netsimEngineHandlesExceptionCorrectly() { @Test public void controlerHandlesExceptionCorrectly_syncOnSimSteps() { Config config = utils.loadConfig("test/scenarios/equil/config_plans1.xml"); - config.parallelEventHandling().setNumberOfThreads(1); - config.parallelEventHandling().setSynchronizeOnSimSteps(true); + config.eventsManager().setNumberOfThreads(1); + config.eventsManager().setSynchronizeOnSimSteps(true); Controler controler = new Controler(config); controler.getEvents().addHandler((LinkLeaveEventHandler)event -> { @@ -77,8 +77,8 @@ public void controlerHandlesExceptionCorrectly_syncOnSimSteps() { @Test public void controlerHandlesExceptionCorrectly_noSyncOnSimSteps() { Config config = utils.loadConfig("test/scenarios/equil/config_plans1.xml"); - config.parallelEventHandling().setNumberOfThreads(1); - config.parallelEventHandling().setSynchronizeOnSimSteps(false); + config.eventsManager().setNumberOfThreads(1); + config.eventsManager().setSynchronizeOnSimSteps(false); Controler controler = new Controler(config); controler.getEvents().addHandler((LinkLeaveEventHandler)event -> { diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/TeleportationEngineWDistanceCheckTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/TeleportationEngineWDistanceCheckTest.java index 83375ff6dd3..9e722b5eaa6 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/TeleportationEngineWDistanceCheckTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/TeleportationEngineWDistanceCheckTest.java @@ -39,8 +39,8 @@ import org.matsim.api.core.v01.population.PopulationFactory; 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.StrategyConfigGroup.StrategySettings; +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.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -55,27 +55,27 @@ */ public class TeleportationEngineWDistanceCheckTest { private static final Logger log = LogManager.getLogger( TeleportationEngineWDistanceCheckTest.class ) ; - + @Rule public MatsimTestUtils utils = new MatsimTestUtils() ; - + @Test public final void test() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); - config.controler().setLastIteration(0); - + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setLastIteration(0); + ActivityParams params = new ActivityParams("dummy" ) ; - config.planCalcScore().addActivityParams(params); + config.scoring().addActivityParams(params); params.setScoringThisActivityAtAll(false); - + StrategySettings stratSets = new StrategySettings() ; stratSets.setStrategyName( DefaultSelector.ChangeExpBeta.toString() ); stratSets.setWeight(1.); - config.strategy().addStrategySettings( stratSets ); - + config.replanning().addStrategySettings( stratSets ); + Scenario scenario = ScenarioUtils.createScenario( config ) ; - + Network network = scenario.getNetwork() ; NetworkFactory nf = network.getFactory() ; @@ -93,13 +93,13 @@ public final void test() { Population population = scenario.getPopulation() ; PopulationFactory pf = population.getFactory() ; - + Person person = pf.createPerson( Id.createPersonId(0) ) ; population.addPerson( person ); - + Plan plan = pf.createPlan(); person.addPlan( plan ) ; - { + { Activity act = pf.createActivityFromCoord("dummy",new Coord(0.,-10000.) ) ; plan.addActivity(act); act.setEndTime(0.); @@ -108,11 +108,11 @@ public final void test() { Leg leg = pf.createLeg( TransportMode.car ) ; plan.addLeg( leg ); } - { + { Activity act = pf.createActivityFromCoord("dummy",new Coord(20000.,-1.) ) ; plan.addActivity(act); } - + Controler controler = new Controler( scenario ) ; controler.addOverridingModule( new AbstractModule(){ @Override public void install() { @@ -120,14 +120,14 @@ public final void test() { @Override public void reset(int iteration) { } @Override public void handleEvent(Event event) { - log.warn( event.toString() ) ; + log.warn( event.toString() ) ; } - + }); } - + }); - + controler.run(); } diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/VehicleSourceTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/VehicleSourceTest.java index 87fa01efee0..069f22b616b 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/VehicleSourceTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/VehicleSourceTest.java @@ -37,7 +37,7 @@ import org.matsim.api.core.v01.population.*; 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.ScoringConfigGroup.ActivityParams; import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup.VehiclesSource; import org.matsim.core.controler.AbstractModule; @@ -57,7 +57,7 @@ /** * A test to check the functionality of the VehicleSource. - * + * * @author amit */ @@ -124,17 +124,17 @@ public void main() { config.qsim().setVehiclesSource(this.vehiclesSource ); config.qsim().setUsePersonIdForMissingVehicleId(this.usingPersonIdForMissingVehicleId ); - config.controler().setOutputDirectory(helper.getOutputDirectory()); - config.controler().setLastIteration(0); - config.controler().setWriteEventsInterval(1); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); + config.controller().setOutputDirectory(helper.getOutputDirectory()); + config.controller().setLastIteration(0); + config.controller().setWriteEventsInterval(1); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); - config.planCalcScore().addActivityParams( new ActivityParams("h").setTypicalDuration(1. * 3600. ) ); - config.planCalcScore().addActivityParams( new ActivityParams("w").setTypicalDuration(1. * 3600. ) ); + config.scoring().addActivityParams( new ActivityParams("h").setTypicalDuration(1. * 3600. ) ); + config.scoring().addActivityParams( new ActivityParams("w").setTypicalDuration(1. * 3600. ) ); final Controler cont = new Controler(scenario); - cont.getConfig().controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + cont.getConfig().controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); Map, Map, Double>> vehicleLinkTravelTimes = new HashMap<>(); final VehicleLinkTravelTimeEventHandler handler = new VehicleLinkTravelTimeEventHandler(vehicleLinkTravelTimes); @@ -184,7 +184,7 @@ public void install() { Map, Double> travelTime1 = vehicleLinkTravelTimes.get(Id.create("0_bike", Vehicle.class)); Map, Double> travelTime2 = vehicleLinkTravelTimes.get(carId); - int bikeTravelTime = travelTime1.get(Id.create("2", Link.class)).intValue(); + int bikeTravelTime = travelTime1.get(Id.create("2", Link.class)).intValue(); int carTravelTime = travelTime2.get(Id.create("2", Link.class)).intValue(); switch (this.vehiclesSource ) { diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/DeparturesOnSameLinkSameTimeTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/DeparturesOnSameLinkSameTimeTest.java index 0315b827d69..f6af0e77d91 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/DeparturesOnSameLinkSameTimeTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/DeparturesOnSameLinkSameTimeTest.java @@ -59,32 +59,32 @@ public class DeparturesOnSameLinkSameTimeTest { *

        Since, the flow capacity of link l_1 is 1 PCU per sec, both motorbike should be able to leave the link l_1 at the same time * whereas cars should leave at a gap of one second. */ - @Test + @Test public void test4LinkEnterTimeOfCarAndBike () { - + Id firstAgent = Id.createVehicleId(1); Id secondAgent = Id.createVehicleId(2); - + Id departureLink = Id.createLinkId(1); - + Map,Map, Double>> motorbikeLinkLeaveTime = getLinkEnterTime("motorbike",3600); Map,Map, Double>> carLinkLeaveTime = getLinkEnterTime(TransportMode.car,3600); - + double diff_carAgents_departureLink_LeaveTimes = carLinkLeaveTime.get(secondAgent).get(departureLink) - carLinkLeaveTime.get(firstAgent).get(departureLink); Assert.assertEquals("Both car agents should leave at the gap of 1 sec.", 1., Math.abs(diff_carAgents_departureLink_LeaveTimes), MatsimTestUtils.EPSILON ); - + double diff_motorbikeAgents_departureLink_LeaveTimes = motorbikeLinkLeaveTime.get(secondAgent).get(departureLink) - motorbikeLinkLeaveTime.get(firstAgent).get(departureLink); Assert.assertEquals("Both motorbike agents should leave at the same time.", 0., diff_motorbikeAgents_departureLink_LeaveTimes, MatsimTestUtils.EPSILON ); - + // for flow cap more than 3600, both cars also should leave link l_1 at the same time. carLinkLeaveTime = getLinkEnterTime(TransportMode.car,3601); - + diff_carAgents_departureLink_LeaveTimes = carLinkLeaveTime.get(secondAgent).get(departureLink) - carLinkLeaveTime.get(firstAgent).get(departureLink); Assert.assertEquals("Both car agents should leave at the same time", 0., diff_carAgents_departureLink_LeaveTimes, MatsimTestUtils.EPSILON ); } private Map,Map, Double>> getLinkEnterTime (String travelMode, double departureLinkCapacity){ - + PseudoInputs inputs = new PseudoInputs(travelMode); inputs.createNetwork(departureLinkCapacity); inputs.createPopulation(); @@ -101,19 +101,19 @@ public void reset(int iteration) { @Override public void handleEvent(LinkLeaveEvent event) { - + if(linkLeaveTimes.containsKey(event.getVehicleId())){ - + Map, Double> times = linkLeaveTimes.get(event.getVehicleId()); times.put(event.getLinkId(), event.getTime()); linkLeaveTimes.put(event.getVehicleId(), times); - + } else { - + Map, Double> times = new HashMap, Double>(); times.put(event.getLinkId(), event.getTime()); linkLeaveTimes.put(event.getVehicleId(), times); - + } } }); @@ -150,10 +150,10 @@ public PseudoInputs(String travelMode) { //following is necessary for mixed traffic, providing a route was obstructing // the requirement of these which might be all right in some cases. Amit Jan'18 - config.plansCalcRoute().setNetworkModes(Arrays.asList(travelMode)); + config.routing().setNetworkModes(Arrays.asList(travelMode)); config.travelTimeCalculator().setAnalyzedModesAsString(travelMode ); config.travelTimeCalculator().setSeparateModes(true); - config.planCalcScore().getOrCreateModeParams(travelMode); + config.scoring().getOrCreateModeParams(travelMode); network = this.scenario.getNetwork(); population = this.scenario.getPopulation(); @@ -177,7 +177,7 @@ private void createNetwork(double departureLinkCapacity){ private void createPopulation(){ - // Vehicles info + // Vehicles info // scenario.getConfig().qsim().setUseDefaultVehicles(false); scenario.getConfig().qsim().setVehiclesSource( VehiclesSource.fromVehiclesData ) ; scenario.getConfig().qsim().setUsingFastCapacityUpdate(true); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowEfficiencyCalculatorTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowEfficiencyCalculatorTest.java index f4c7741a970..c343ec924ae 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowEfficiencyCalculatorTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowEfficiencyCalculatorTest.java @@ -37,7 +37,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -130,13 +130,13 @@ public void handleEvent(PersonArrivalEvent event) { private Scenario createScenario() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); ActivityParams genericParams = new ActivityParams("generic"); genericParams.setTypicalDuration(1.0); - config.planCalcScore().addActivityParams(genericParams); + config.scoring().addActivityParams(genericParams); Scenario scenario = ScenarioUtils.createScenario(config); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/LinkSpeedCalculatorIntegrationTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/LinkSpeedCalculatorIntegrationTest.java index e66ca94331a..a73e82a5b3e 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/LinkSpeedCalculatorIntegrationTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/LinkSpeedCalculatorIntegrationTest.java @@ -147,7 +147,7 @@ public void testIntegration_Fast() { final Scenario scenario = f.scenario ; final Config config = scenario.getConfig() ; - config.controler().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); // Collection defaultsModules = new ArrayList<>() ; // defaultsModules.add( new ScenarioByInstanceModule( scenario ) ) ; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/QSimComponentsTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/QSimComponentsTest.java index 2baccef0720..8915e730af2 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/QSimComponentsTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/QSimComponentsTest.java @@ -40,9 +40,9 @@ public void testRemoveNetsimEngine() { // be teleported if netsim engine is missing. Thus, the RuntimeException confirms that removing the module worked. Config config = ConfigUtils.loadConfig( IOUtils.extendUrl( ExamplesUtils.getTestScenarioURL( "equil" ), "config.xml" ) ); - config.controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); - config.controler().setLastIteration( 0 ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setLastIteration( 0 ); + config.controller().setOutputDirectory(utils.getOutputDirectory()); // remove the module: (There is also syntax at some intermediate level for this, but I prefer the syntax at config level. kai, oct'22) QSimComponentsConfigGroup componentsConfig = ConfigUtils.addOrGetModule( config, QSimComponentsConfigGroup.class ); @@ -62,9 +62,9 @@ public void testReplaceQNetworkFactory() { // here we try to replace the QNetworkFactory. Complains that QNetworkFactory is bound multiple times. Config config = ConfigUtils.loadConfig( IOUtils.extendUrl( ExamplesUtils.getTestScenarioURL( "equil" ), "config.xml" ) ); - config.controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); - config.controler().setLastIteration( 0 ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setLastIteration( 0 ); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Scenario scenario = ScenarioUtils.loadScenario( config ); @@ -88,9 +88,9 @@ public void testReplaceQNetworkFactory2() { // here we try to replace the QNetworkFactory at AbstractQSimModule. This works. Config config = ConfigUtils.loadConfig( IOUtils.extendUrl( ExamplesUtils.getTestScenarioURL( "equil" ), "config.xml" ) ); - config.controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); - config.controler().setLastIteration( 0 ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setLastIteration( 0 ); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Scenario scenario = ScenarioUtils.loadScenario( config ); @@ -110,9 +110,9 @@ public void testOverridingQSimModule() { // use the newly implemented install _overriding_ qsim module. With this, replacing the QNetworkFactory now works as part of AbstractModule. Config config = ConfigUtils.loadConfig( IOUtils.extendUrl( ExamplesUtils.getTestScenarioURL( "equil" ), "config.xml" ) ); - config.controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); - config.controler().setLastIteration( 0 ); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setLastIteration( 0 ); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Scenario scenario = ScenarioUtils.loadScenario( config ); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/RunConfigurableQNetworkFactoryExampleTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/RunConfigurableQNetworkFactoryExampleTest.java index 36556c44b3f..958ba50b9ea 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/RunConfigurableQNetworkFactoryExampleTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/RunConfigurableQNetworkFactoryExampleTest.java @@ -37,14 +37,14 @@ public class RunConfigurableQNetworkFactoryExampleTest { public final void testMain() { try { Config config = ConfigUtils.createConfig() ; - config.controler().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); - config.controler().setLastIteration(5); + config.controller().setOverwriteFileSetting( OverwriteFileSetting.deleteDirectoryIfExists ); + config.controller().setLastIteration(5); RunConfigurableQNetworkFactoryExample.run(config); } catch ( Exception ee ) { throw new RuntimeException("something went wrong", ee); } - - + + } } diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SimulatedLaneFlowCapacityTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SimulatedLaneFlowCapacityTest.java index cbb4f9fcea2..62966d8493f 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SimulatedLaneFlowCapacityTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SimulatedLaneFlowCapacityTest.java @@ -48,7 +48,7 @@ import org.matsim.core.api.experimental.events.handler.LaneLeaveEventHandler; 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.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.PrepareForSimUtils; import org.matsim.core.events.EventsUtils; import org.matsim.core.mobsim.qsim.QSimBuilder; @@ -211,7 +211,7 @@ private static void initPopulation(Population population) { Config config = ConfigUtils.createConfig(); ActivityParams dummyAct = new ActivityParams("dummy"); dummyAct.setTypicalDuration(12 * 3600); - config.planCalcScore().addActivityParams(dummyAct); + config.scoring().addActivityParams(dummyAct); MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config); initNetwork(scenario.getNetwork()); @@ -238,7 +238,7 @@ private static void initPopulation(Population population) { Config config = ConfigUtils.createConfig(); ActivityParams dummyAct = new ActivityParams("dummy"); dummyAct.setTypicalDuration(12 * 3600); - config.planCalcScore().addActivityParams(dummyAct); + config.scoring().addActivityParams(dummyAct); MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config); initNetwork(scenario.getNetwork()); @@ -269,7 +269,7 @@ private static void initPopulation(Population population) { Config config = ConfigUtils.createConfig(); ActivityParams dummyAct = new ActivityParams("dummy"); dummyAct.setTypicalDuration(12 * 3600); - config.planCalcScore().addActivityParams(dummyAct); + config.scoring().addActivityParams(dummyAct); MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config); initNetwork(scenario.getNetwork()); @@ -301,7 +301,7 @@ private static void initPopulation(Population population) { Config config = ConfigUtils.createConfig(); ActivityParams dummyAct = new ActivityParams("dummy"); dummyAct.setTypicalDuration(12 * 3600); - config.planCalcScore().addActivityParams(dummyAct); + config.scoring().addActivityParams(dummyAct); MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config); initNetwork(scenario.getNetwork()); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SpeedCalculatorTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SpeedCalculatorTest.java index 1e1068185fc..cea3d9d7d25 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SpeedCalculatorTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SpeedCalculatorTest.java @@ -92,7 +92,7 @@ public class SpeedCalculatorTest{ // (dto) } private double getSpeedOnLink( Link link, QVehicle vehicle ){ - config.controler().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); Scenario scenario = ScenarioUtils.createScenario( config ); AbstractQSimModule module = new AbstractQSimModule(){ @Override public void configureQSim(){ diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehicleHandlerTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehicleHandlerTest.java index dda8873ec28..48bf9fbc37a 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehicleHandlerTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehicleHandlerTest.java @@ -44,7 +44,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -185,14 +185,14 @@ public void handleEvent(PersonArrivalEvent event) { private Scenario createScenario() { Config config = ConfigUtils.createConfig(); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(utils.getOutputDirectory()); ActivityParams genericParams = new ActivityParams("generic"); genericParams.setTypicalDuration(1.0); - config.planCalcScore().addActivityParams(genericParams); + config.scoring().addActivityParams(genericParams); Scenario scenario = ScenarioUtils.createScenario(config); diff --git a/matsim/src/test/java/org/matsim/core/network/io/NetworkReprojectionIOTest.java b/matsim/src/test/java/org/matsim/core/network/io/NetworkReprojectionIOTest.java index c23569a6922..3fe86ebe824 100644 --- a/matsim/src/test/java/org/matsim/core/network/io/NetworkReprojectionIOTest.java +++ b/matsim/src/test/java/org/matsim/core/network/io/NetworkReprojectionIOTest.java @@ -143,9 +143,9 @@ public void testWithControlerAndAttributes() { TARGET_CRS, ProjectionUtils.getCRS(scenario.getNetwork())); - config.controler().setLastIteration( 0 ); + config.controller().setLastIteration( 0 ); final String outputDirectory = utils.getOutputDirectory()+"/output/"; - config.controler().setOutputDirectory( outputDirectory ); + config.controller().setOutputDirectory( outputDirectory ); final Controler controler = new Controler( scenario ); controler.run(); @@ -197,9 +197,9 @@ public void testWithControlerAndConfigParameters() { MatsimTestUtils.EPSILON ); } - config.controler().setLastIteration( 0 ); + config.controller().setLastIteration( 0 ); final String outputDirectory = utils.getOutputDirectory()+"/output/"; - config.controler().setOutputDirectory( outputDirectory ); + config.controller().setOutputDirectory( outputDirectory ); final Controler controler = new Controler( scenario ); controler.run(); diff --git a/matsim/src/test/java/org/matsim/core/population/io/PopulationReprojectionIOIT.java b/matsim/src/test/java/org/matsim/core/population/io/PopulationReprojectionIOIT.java index 6746f3dd945..853af4157eb 100644 --- a/matsim/src/test/java/org/matsim/core/population/io/PopulationReprojectionIOIT.java +++ b/matsim/src/test/java/org/matsim/core/population/io/PopulationReprojectionIOIT.java @@ -215,9 +215,9 @@ public void testWithControlerAndAttributes() { ProjectionUtils.getCRS(scenario.getPopulation())); // do not perform ANY mobsim run - config.controler().setLastIteration( -1 ); + config.controller().setLastIteration( -1 ); final String outputDirectory = utils.getOutputDirectory()+"/output/"; - config.controler().setOutputDirectory( outputDirectory ); + config.controller().setOutputDirectory( outputDirectory ); final Controler controler = new Controler( scenario ); controler.run(); @@ -319,9 +319,9 @@ public void testWithControlerAndConfigParameters() { } // do not perform ANY mobsim run - config.controler().setLastIteration( -1 ); + config.controller().setLastIteration( -1 ); final String outputDirectory = utils.getOutputDirectory()+"/output/"; - config.controler().setOutputDirectory( outputDirectory ); + config.controller().setOutputDirectory( outputDirectory ); final Controler controler = new Controler( scenario ); controler.run(); diff --git a/matsim/src/test/java/org/matsim/core/population/routes/RouteFactoryIntegrationTest.java b/matsim/src/test/java/org/matsim/core/population/routes/RouteFactoryIntegrationTest.java index 9aa09ca65bb..bcecf3f052a 100644 --- a/matsim/src/test/java/org/matsim/core/population/routes/RouteFactoryIntegrationTest.java +++ b/matsim/src/test/java/org/matsim/core/population/routes/RouteFactoryIntegrationTest.java @@ -26,7 +26,7 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.*; 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.Controler; import org.matsim.core.population.routes.heavycompressed.HeavyCompressedNetworkRoute; import org.matsim.core.population.routes.heavycompressed.HeavyCompressedNetworkRouteFactory; @@ -53,7 +53,7 @@ public class RouteFactoryIntegrationTest { public void testRouteFactoryIntegration() { Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); config.plans().setInputFile("plans2.xml"); - Collection settings = config.strategy().getStrategySettings(); + Collection settings = config.replanning().getStrategySettings(); for (StrategySettings setting: settings) { if ("ReRoute".equals(setting.getStrategyName())) { setting.setWeight(1.0); @@ -61,13 +61,13 @@ public void testRouteFactoryIntegration() { setting.setWeight(0.0); } } - config.controler().setLastIteration(1); + config.controller().setLastIteration(1); // test the default - config.controler().setOutputDirectory(utils.getOutputDirectory() + "/default"); + config.controller().setOutputDirectory(utils.getOutputDirectory() + "/default"); Controler controler = new Controler(config); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setWriteEventsInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(0); controler.run(); Population population = controler.getScenario().getPopulation(); @@ -78,7 +78,7 @@ public void testRouteFactoryIntegration() { Leg leg = (Leg) pe; Route route = leg.getRoute(); Assert.assertTrue(route instanceof NetworkRoute || route instanceof GenericRouteImpl ); // that must be different from the class used below - // yy I added the "|| route instanceof GenericRouteImpl" to compensate for the added walk legs; a more precise + // yy I added the "|| route instanceof GenericRouteImpl" to compensate for the added walk legs; a more precise // test would be better. kai, feb'16 } } @@ -86,14 +86,14 @@ public void testRouteFactoryIntegration() { } // test another setting - config.controler().setOutputDirectory(utils.getOutputDirectory() + "/variant1"); + config.controller().setOutputDirectory(utils.getOutputDirectory() + "/variant1"); MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config); scenario.getPopulation().getFactory().getRouteFactories().setRouteFactory(NetworkRoute.class, new HeavyCompressedNetworkRouteFactory(scenario.getNetwork(), TransportMode.car)); ScenarioUtils.loadScenario(scenario); Controler controler2 = new Controler(scenario); - controler2.getConfig().controler().setCreateGraphs(false); - controler2.getConfig().controler().setWriteEventsInterval(0); + controler2.getConfig().controller().setCreateGraphs(false); + controler2.getConfig().controller().setWriteEventsInterval(0); controler2.run(); Population population2 = controler2.getScenario().getPopulation(); @@ -107,7 +107,7 @@ public void testRouteFactoryIntegration() { Route route = leg.getRoute(); Assert.assertTrue("person: " + person.getId() + "; plan: " + planCounter, route instanceof HeavyCompressedNetworkRoute || route instanceof GenericRouteImpl ); - // yy I added the "|| route instanceof GenericRouteImpl" to compensate for the added walk legs; a more precise + // yy I added the "|| route instanceof GenericRouteImpl" to compensate for the added walk legs; a more precise // test would be better. kai, feb'16 } } diff --git a/matsim/src/test/java/org/matsim/core/replanning/annealing/ReplanningAnnealerTest.java b/matsim/src/test/java/org/matsim/core/replanning/annealing/ReplanningAnnealerTest.java index 03c88662950..1a04ffdf6cb 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/annealing/ReplanningAnnealerTest.java +++ b/matsim/src/test/java/org/matsim/core/replanning/annealing/ReplanningAnnealerTest.java @@ -10,7 +10,7 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.StrategyConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.replanning.StrategyManager; import org.matsim.core.scenario.ScenarioUtils; @@ -167,26 +167,26 @@ public void setup() { this.saConfigVar = new ReplanningAnnealerConfigGroup.AnnealingVariable(); this.saConfig.addAnnealingVariable(this.saConfigVar); - StrategyConfigGroup.StrategySettings s1 = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings s1 = new ReplanningConfigGroup.StrategySettings(); s1.setStrategyName("ReRoute"); s1.setWeight(0.2); - this.config.strategy().addStrategySettings(s1); - StrategyConfigGroup.StrategySettings s2 = new StrategyConfigGroup.StrategySettings(); + this.config.replanning().addStrategySettings(s1); + ReplanningConfigGroup.StrategySettings s2 = new ReplanningConfigGroup.StrategySettings(); s2.setStrategyName("SubtourModeChoice"); s2.setWeight(0.2); - this.config.strategy().addStrategySettings(s2); - StrategyConfigGroup.StrategySettings s3 = new StrategyConfigGroup.StrategySettings(); + this.config.replanning().addStrategySettings(s2); + ReplanningConfigGroup.StrategySettings s3 = new ReplanningConfigGroup.StrategySettings(); s3.setStrategyName("ChangeExpBeta"); // shouldn't be affected s3.setWeight(0.5); - this.config.strategy().addStrategySettings(s3); + this.config.replanning().addStrategySettings(s3); - this.config.controler().setCreateGraphs(false); - this.config.controler().setDumpDataAtEnd(false); - this.config.controler().setWriteEventsInterval(0); - this.config.controler().setWritePlansInterval(0); - this.config.controler().setWriteSnapshotsInterval(0); - this.config.controler().setLastIteration(10); - this.config.controler().setOutputDirectory(this.utils.getOutputDirectory() + "annealOutput"); + this.config.controller().setCreateGraphs(false); + this.config.controller().setDumpDataAtEnd(false); + this.config.controller().setWriteEventsInterval(0); + this.config.controller().setWritePlansInterval(0); + this.config.controller().setWriteSnapshotsInterval(0); + this.config.controller().setLastIteration(10); + this.config.controller().setOutputDirectory(this.utils.getOutputDirectory() + "annealOutput"); this.scenario = ScenarioUtils.createScenario(this.config); } @@ -288,7 +288,7 @@ public void testParameterAnneal() throws IOException { controler.run(); Assert.assertEquals(expectedParameterAnneal, readResult(controler.getControlerIO().getOutputFilename(FILENAME_ANNEAL))); - Assert.assertEquals(0.0, controler.getConfig().planCalcScore().getBrainExpBeta(), 1e-4); + Assert.assertEquals(0.0, controler.getConfig().scoring().getBrainExpBeta(), 1e-4); } @Test @@ -308,7 +308,7 @@ public void testTwoParameterAnneal() throws IOException { controler.run(); Assert.assertEquals(expectedTwoParameterAnneal, readResult(controler.getControlerIO().getOutputFilename(FILENAME_ANNEAL))); - Assert.assertEquals(0.0, controler.getConfig().planCalcScore().getBrainExpBeta(), 1e-4); + Assert.assertEquals(0.0, controler.getConfig().scoring().getBrainExpBeta(), 1e-4); StrategyManager sm = controler.getInjector().getInstance(StrategyManager.class); List weights = sm.getWeights(null); @@ -318,7 +318,7 @@ public void testTwoParameterAnneal() throws IOException { @Test public void testInnovationSwitchoffAnneal() throws IOException { - this.config.strategy().setFractionOfIterationsToDisableInnovation(0.5); + this.config.replanning().setFractionOfIterationsToDisableInnovation(0.5); this.saConfigVar.setAnnealType("msa"); this.saConfigVar.setShapeFactor(1.0); this.saConfigVar.setStartValue(0.5); @@ -359,12 +359,12 @@ public void testSubpopulationAnneal() throws IOException { this.saConfigVar.setEndValue(0.0); this.saConfigVar.setStartValue(0.5); this.saConfigVar.setDefaultSubpopulation(targetSubpop); - this.config.strategy().getStrategySettings().forEach(s -> s.setSubpopulation(targetSubpop)); - StrategyConfigGroup.StrategySettings s = new StrategyConfigGroup.StrategySettings(); + this.config.replanning().getStrategySettings().forEach(s -> s.setSubpopulation(targetSubpop)); + ReplanningConfigGroup.StrategySettings s = new ReplanningConfigGroup.StrategySettings(); s.setStrategyName("TimeAllocationMutator"); s.setWeight(0.25); s.setSubpopulation("noAnneal"); - this.config.strategy().addStrategySettings(s); + this.config.replanning().addStrategySettings(s); Controler controler = new Controler(this.scenario); controler.run(); diff --git a/matsim/src/test/java/org/matsim/core/replanning/modules/ExternalModuleTest.java b/matsim/src/test/java/org/matsim/core/replanning/modules/ExternalModuleTest.java index a68ffca463a..d7a8f260215 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/modules/ExternalModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/replanning/modules/ExternalModuleTest.java @@ -33,11 +33,9 @@ import org.matsim.api.core.v01.replanning.PlanStrategyModule; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.*; -import org.matsim.core.controler.corelisteners.ControlerDefaultCoreListenersModule; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.io.PopulationReader; import org.matsim.core.replanning.ReplanningContext; -import org.matsim.core.scenario.ScenarioByInstanceModule; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.testcases.MatsimTestUtils; @@ -56,8 +54,8 @@ public void setUp() { originalScenario = ScenarioUtils.loadScenario(utils.loadConfig("test/scenarios/equil/config.xml")); final String outputDirectory = utils.getOutputDirectory(); outputDirectoryHierarchy = new OutputDirectoryHierarchy( - outputDirectory, OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists, this.scenario.getConfig().controler().getCompressionType()); - scenario.getConfig().controler().setOutputDirectory( outputDirectory ); + outputDirectory, OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists, this.scenario.getConfig().controller().getCompressionType()); + scenario.getConfig().controller().setOutputDirectory( outputDirectory ); // scenario.getConfig().controler().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); // // the following includes all retrofittings that were added later: diff --git a/matsim/src/test/java/org/matsim/core/replanning/planInheritance/PlanInheritanceTest.java b/matsim/src/test/java/org/matsim/core/replanning/planInheritance/PlanInheritanceTest.java new file mode 100644 index 00000000000..c15436d3391 --- /dev/null +++ b/matsim/src/test/java/org/matsim/core/replanning/planInheritance/PlanInheritanceTest.java @@ -0,0 +1,129 @@ +package org.matsim.core.replanning.planInheritance; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +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.population.Person; +import org.matsim.api.core.v01.population.Plan; +import org.matsim.core.config.Config; +import org.matsim.core.controler.Controler; +import org.matsim.core.population.algorithms.PersonAlgorithm; +import org.matsim.core.population.io.StreamingPopulationReader; +import org.matsim.core.replanning.inheritance.PlanInheritanceModule; +import org.matsim.core.replanning.inheritance.PlanInheritanceRecord; +import org.matsim.core.replanning.inheritance.PlanInheritanceRecordReader; +import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.testcases.MatsimTestUtils; + + + +public class PlanInheritanceTest { + /** + * @author alex94263 + */ + + + @Rule + public MatsimTestUtils util = new MatsimTestUtils(); + + @Test + public void testPlanInheritanceEnabled() throws IOException { + String outputDirectory = util.getOutputDirectory(); + + Config config = this.util.loadConfig("test/scenarios/equil/config_plans1.xml"); + config.controller().setLastIteration(10); + config.controller().setOutputDirectory(outputDirectory); + config.planInheritance().setEnabled(true); + Controler c = new Controler(config); + + c.run(); + File csv = new File(outputDirectory, "planInheritanceRecords.csv.gz"); + + assertThat(csv).exists(); + + + List personList = new ArrayList(); + final Scenario scenario = ScenarioUtils.createScenario(config); + StreamingPopulationReader spr = new StreamingPopulationReader(scenario); + spr.addAlgorithm(new PersonAlgorithm() { + @Override + public void run(Person person) { + personList.add(person); + } + }); + spr.readFile(util.getOutputDirectory()+"output_plans.xml.gz"); + for(Person per : personList) { + for(Plan p : per.getPlans()) { + assert(p.getAttributes().getAsMap().keySet().contains(PlanInheritanceModule.PLAN_MUTATOR)); + assert(p.getAttributes().getAsMap().keySet().contains(PlanInheritanceModule.ITERATION_CREATED)); + assert(p.getAttributes().getAsMap().keySet().contains(PlanInheritanceModule.PLAN_ID)); + } + + } + + PlanInheritanceRecordReader reader = new PlanInheritanceRecordReader(outputDirectory+"planInheritanceRecords.csv.gz"); + List records = reader.read(); + assert(records.size()==2); + assert( ((PlanInheritanceRecord) records.get(0)).getAgentId().equals(Id.createPersonId("1"))); + assert( ((PlanInheritanceRecord) records.get(0)).getAncestorId().equals(Id.create("NONE",Plan.class))); + assert( ((PlanInheritanceRecord) records.get(0)).getMutatedBy().equals(PlanInheritanceModule.INITIAL_PLAN)); + assert( ((PlanInheritanceRecord) records.get(0)).getIterationCreated() == 0); + assert( ((PlanInheritanceRecord) records.get(0)).getIterationRemoved() == -1); + assert( ((PlanInheritanceRecord) records.get(0)).getPlanId().equals(Id.create("1",Plan.class))); + assert( ((PlanInheritanceRecord) records.get(0)).getIterationsSelected().equals(Arrays.asList(0, 1, 2, 3, 4, 6, 7, 8, 9, 10))); + + assert( ((PlanInheritanceRecord) records.get(1)).getAgentId().equals(Id.createPersonId("1"))); + assert( ((PlanInheritanceRecord) records.get(1)).getAncestorId().equals(Id.create("1",Plan.class))); + assert( ((PlanInheritanceRecord) records.get(1)).getMutatedBy().equals("RandomPlanSelector_ReRoute")); + assert( ((PlanInheritanceRecord) records.get(1)).getIterationCreated() == 5); + assert( ((PlanInheritanceRecord) records.get(1)).getIterationRemoved() == -1); + assert( ((PlanInheritanceRecord) records.get(1)).getPlanId().equals(Id.create("2",Plan.class))); + assert( ((PlanInheritanceRecord) records.get(1)).getIterationsSelected().equals(Arrays.asList(5))); + + + + } + + @Test + public void testPlanInheritanceDisabled() throws IOException { + String outputDirectory = util.getOutputDirectory(); + + Config config = this.util.loadConfig("test/scenarios/equil/config_plans1.xml"); + config.controller().setLastIteration(1); + config.controller().setOutputDirectory(outputDirectory); + Controler c = new Controler(config); + + c.run(); + + File csv = new File(outputDirectory, "planInheritanceRecords.csv.gz"); + + assertThat(csv).doesNotExist(); + + List personList = new ArrayList(); + final Scenario scenario = ScenarioUtils.createScenario(config); + StreamingPopulationReader spr = new StreamingPopulationReader(scenario); + spr.addAlgorithm(new PersonAlgorithm() { + @Override + public void run(Person person) { + personList.add(person); + } + }); + spr.readFile(util.getOutputDirectory()+"output_plans.xml.gz"); + for(Person per : personList) { + for(Plan p : per.getPlans()) { + assert(!p.getAttributes().getAsMap().keySet().contains(PlanInheritanceModule.PLAN_MUTATOR)); + assert(!p.getAttributes().getAsMap().keySet().contains(PlanInheritanceModule.ITERATION_CREATED)); + assert(!p.getAttributes().getAsMap().keySet().contains(PlanInheritanceModule.PLAN_ID)); + } + + } + } +} diff --git a/matsim/src/test/java/org/matsim/core/replanning/selectors/ExpBetaPlanSelectorTest.java b/matsim/src/test/java/org/matsim/core/replanning/selectors/ExpBetaPlanSelectorTest.java index 6633c641ce4..5de64cd172d 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/selectors/ExpBetaPlanSelectorTest.java +++ b/matsim/src/test/java/org/matsim/core/replanning/selectors/ExpBetaPlanSelectorTest.java @@ -54,14 +54,14 @@ public class ExpBetaPlanSelectorTest extends AbstractPlanSelectorTest { @Override protected ExpBetaPlanSelector getPlanSelector() { - return new ExpBetaPlanSelector(this.config.planCalcScore()); + return new ExpBetaPlanSelector(this.config.scoring()); } /** * Test that plans are selected depending on their weight, use beta = 2.0. */ @Test public void testExpBeta2() { - this.config.planCalcScore().setBrainExpBeta(2.0); + this.config.scoring().setBrainExpBeta(2.0); Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); // weight = Math.exp(this.beta * (plan.getScore() - maxScore)); Plan plan1 = PersonUtils.createAndAddPlan(person, false); // weight: 0.0003.35462627902512 @@ -75,7 +75,7 @@ protected ExpBetaPlanSelector getPlanSelector() { Plan plan5 = PersonUtils.createAndAddPlan(person, false);// weight: 1 plan5.setScore(100.0); - ExpBetaPlanSelector selector = new ExpBetaPlanSelector(this.config.planCalcScore()); + ExpBetaPlanSelector selector = new ExpBetaPlanSelector(this.config.scoring()); int cnt1 = 0; int cnt2 = 0; int cnt3 = 0; @@ -113,7 +113,7 @@ protected ExpBetaPlanSelector getPlanSelector() { * Test that plans are selected depending on their weight, use beta = 2.0. */ @Test public void testExpBeta1() { - this.config.planCalcScore().setBrainExpBeta(1.0); + this.config.scoring().setBrainExpBeta(1.0); Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); // weight = Math.exp(this.beta * (plan.getScore() - maxScore)); // weight: 0.018315638888734186 @@ -134,7 +134,7 @@ protected ExpBetaPlanSelector getPlanSelector() { - ExpBetaPlanSelector selector = new ExpBetaPlanSelector(this.config.planCalcScore()); + ExpBetaPlanSelector selector = new ExpBetaPlanSelector(this.config.scoring()); int cnt1 = 0; int cnt2 = 0; int cnt3 = 0; @@ -175,7 +175,7 @@ protected ExpBetaPlanSelector getPlanSelector() { */ final double EPSILON_R = 1e-7; - this.config.planCalcScore().setBrainExpBeta(2.0); + this.config.scoring().setBrainExpBeta(2.0); Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); Plan plan1 = PersonUtils.createAndAddPlan(person, false); plan1.setScore(180.0); @@ -186,7 +186,7 @@ protected ExpBetaPlanSelector getPlanSelector() { Plan plan4 = PersonUtils.createAndAddPlan(person, false); plan4.setScore(169.9); - ExpBetaPlanSelector testee = new ExpBetaPlanSelector(this.config.planCalcScore()); + ExpBetaPlanSelector testee = new ExpBetaPlanSelector(this.config.scoring()); assertEquals(0.2024421, ExpBetaPlanSelector.getSelectionProbability(testee, person, plan1), EPSILON_R); assertEquals(0.2472634, ExpBetaPlanSelector.getSelectionProbability(testee, person, plan2), EPSILON_R); diff --git a/matsim/src/test/java/org/matsim/core/replanning/selectors/PathSizeLogitSelectorTest.java b/matsim/src/test/java/org/matsim/core/replanning/selectors/PathSizeLogitSelectorTest.java index 56025703943..f21680b1ea9 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/selectors/PathSizeLogitSelectorTest.java +++ b/matsim/src/test/java/org/matsim/core/replanning/selectors/PathSizeLogitSelectorTest.java @@ -60,8 +60,8 @@ public class PathSizeLogitSelectorTest extends AbstractPlanSelectorTest { @Before public void setUp() { this.config = utils.loadConfig((String)null); // required for planCalcScore.beta to be defined - config.planCalcScore().setBrainExpBeta(2.0); - config.planCalcScore().setPathSizeLogitBeta(2.0); + config.scoring().setBrainExpBeta(2.0); + config.scoring().setPathSizeLogitBeta(2.0); this.network = null; } @@ -72,7 +72,7 @@ public class PathSizeLogitSelectorTest extends AbstractPlanSelectorTest { @Override protected PlanSelector getPlanSelector() { - return new PathSizeLogitSelector(config.planCalcScore(), createNetwork()); + return new PathSizeLogitSelector(config.scoring(), createNetwork()); } @Override @@ -287,7 +287,7 @@ protected PlanSelector getPlanSelector() { p3.setScore(-10.0); person.addPlan(p3); - PathSizeLogitSelector selector = new PathSizeLogitSelector(this.config.planCalcScore(), network); + PathSizeLogitSelector selector = new PathSizeLogitSelector(this.config.scoring(), network); int cnt1 = 0; int cnt2 = 0; int cnt3 = 0; diff --git a/matsim/src/test/java/org/matsim/core/replanning/strategies/DeterministicMultithreadedReplanningIT.java b/matsim/src/test/java/org/matsim/core/replanning/strategies/DeterministicMultithreadedReplanningIT.java index 809249f84d7..122f9acc428 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/strategies/DeterministicMultithreadedReplanningIT.java +++ b/matsim/src/test/java/org/matsim/core/replanning/strategies/DeterministicMultithreadedReplanningIT.java @@ -69,26 +69,26 @@ public class DeterministicMultithreadedReplanningIT { public void testTimeAllocationMutator() { int lastIteration = 5; Config config = testUtils.loadConfig("test/scenarios/equil/config.xml"); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); config.global().setNumberOfThreads(4); // just use any number > 1 { StrategyManager strategyManager = new StrategyManager(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + "/run1/"); + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + "/run1/"); TestControler controler = new TestControler(config, strategyManager); PlanStrategyImpl strategy = new PlanStrategyImpl(new RandomPlanSelector()); - strategy.addStrategyModule(new TimeAllocationMutatorModule(TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler.getScenario() ), config.plans(), config.timeAllocationMutator(), config.global()) ); + strategy.addStrategyModule(new TimeAllocationMutatorModule( config.timeAllocationMutator(), config.global()) ); strategyManager.addStrategy( strategy, null, 1.0 ); controler.run(); } { StrategyManager strategyManager = new StrategyManager(); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + "/run2/"); + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + "/run2/"); TestControler controler = new TestControler(config, strategyManager); PlanStrategyImpl strategy = new PlanStrategyImpl(new RandomPlanSelector()); - strategy.addStrategyModule(new TimeAllocationMutatorModule(TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler.getScenario() ), config.plans(), config.timeAllocationMutator(), config.global()) ); + strategy.addStrategyModule(new TimeAllocationMutatorModule(config.timeAllocationMutator(), config.global()) ); strategyManager.addStrategy( strategy, null, 1.0 ); controler.run(); } @@ -116,7 +116,7 @@ public void testTimeAllocationMutator() { public void testReRouteTimeAllocationMutator() { int lastIteration = 5; Config config = testUtils.loadConfig("test/scenarios/equil/config.xml"); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); config.global().setNumberOfThreads(4); // just use any number > 1 { @@ -126,10 +126,10 @@ public void testReRouteTimeAllocationMutator() { PlanStrategyImpl strategy = new PlanStrategyImpl(new RandomPlanSelector()); strategyManager.addStrategy( strategy, null, 1.0 ); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + "/run1/"); + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + "/run1/"); TestControler controler = new TestControler(config, strategyManager); strategy.addStrategyModule(new ReRoute(controler.getScenario(), TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler.getScenario()), TimeInterpretation.create(config))); // finish strategy configuration - strategy.addStrategyModule(new TimeAllocationMutatorModule(TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler.getScenario() ), config.plans(), config.timeAllocationMutator(), config.global()) ); + strategy.addStrategyModule(new TimeAllocationMutatorModule( config.timeAllocationMutator(), config.global()) ); controler.run(); } { @@ -139,10 +139,10 @@ public void testReRouteTimeAllocationMutator() { PlanStrategyImpl strategy2 = new PlanStrategyImpl(new RandomPlanSelector()); strategyManager2.addStrategy( strategy2, null, 1.0 ); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + "/run2/"); + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + "/run2/"); TestControler controler2 = new TestControler(config, strategyManager2); strategy2.addStrategyModule(new ReRoute(controler2.getScenario(), TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler2.getScenario()), TimeInterpretation.create(config))); // finish strategy configuration - strategy2.addStrategyModule(new TimeAllocationMutatorModule(TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler2.getScenario() ), config.plans(), config.timeAllocationMutator(), config.global()) ); + strategy2.addStrategyModule(new TimeAllocationMutatorModule(config.timeAllocationMutator(), config.global()) ); controler2.run(); } @@ -172,7 +172,7 @@ public void testReRouteOneAgent() { Config config = testUtils.loadConfig("test/scenarios/equil/config.xml"); // yy this seems to be taking the input from the matsim-examples module. No idea by what automagic it ends up there. kai, feb'19 - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); config.global().setNumberOfThreads(4); // just use any number > 1 config.plans().setInputFile(IOUtils.extendUrl(testUtils.classInputResourcePath(), "plans1.xml").toString()); { @@ -181,7 +181,7 @@ public void testReRouteOneAgent() { StrategyManager strategyManager = new StrategyManager(); strategyManager.addStrategy( strategy, null, 1.0 ); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + "/run1/"); + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + "/run1/"); TestControler controler = new TestControler(config, strategyManager); strategy.addStrategyModule(new ReRoute(controler.getScenario(), TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler.getScenario()), TimeInterpretation.create(config))); controler.run(); @@ -193,7 +193,7 @@ public void testReRouteOneAgent() { StrategyManager strategyManager2 = new StrategyManager(); strategyManager2.addStrategy( strategy2, null, 1.0 ); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + "/run2/"); + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + "/run2/"); TestControler controler2 = new TestControler(config, strategyManager2); strategy2.addStrategyModule(new ReRoute(controler2.getScenario(), TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler2.getScenario()), TimeInterpretation.create(config))); @@ -224,7 +224,7 @@ public void testReRouteOneAgent() { public void testReRoute() { int lastIteration = 5; Config config = testUtils.loadConfig("test/scenarios/equil/config.xml"); - config.controler().setLastIteration(lastIteration); + config.controller().setLastIteration(lastIteration); config.global().setNumberOfThreads(4); // just use any number > 1 { @@ -233,7 +233,7 @@ public void testReRoute() { StrategyManager strategyManager = new StrategyManager(); strategyManager.addStrategy( strategy, null, 1.0 ); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + "/run1/"); + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + "/run1/"); TestControler controler = new TestControler(config, strategyManager); strategy.addStrategyModule(new ReRoute(controler.getScenario(), TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler.getScenario()), TimeInterpretation.create(config))); controler.run(); @@ -246,7 +246,7 @@ public void testReRoute() { StrategyManager strategyManager2 = new StrategyManager(); strategyManager2.addStrategy( strategy2, null, 1.0 ); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + "/run2/"); + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + "/run2/"); TestControler controler2 = new TestControler(config, strategyManager2); strategy2.addStrategyModule(new ReRoute(controler2.getScenario(), TripRouterFactoryBuilderWithDefaults.createDefaultTripRouterFactoryImpl(controler2.getScenario()), TimeInterpretation.create(config))); controler2.run(); @@ -275,7 +275,7 @@ public void testReRoute() { private static class TestControler { Controler controler ; - private StrategyManager manager; + private final StrategyManager manager; public TestControler(final Config config, final StrategyManager manager) { this( ScenarioUtils.loadScenario( config ) , manager ); @@ -283,9 +283,9 @@ public TestControler(final Config config, final StrategyManager manager) { public TestControler(final Scenario scenario, final StrategyManager manager) { controler = new Controler( scenario ) ; - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setWriteEventsInterval(1); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(1); + controler.getConfig().controller().setDumpDataAtEnd(false); this.manager = manager ; controler.addOverridingModule(new AbstractModule() { @Override diff --git a/matsim/src/test/java/org/matsim/core/replanning/strategies/InnovationSwitchOffTest.java b/matsim/src/test/java/org/matsim/core/replanning/strategies/InnovationSwitchOffTest.java index d96d29b24aa..9c81aee55f2 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/strategies/InnovationSwitchOffTest.java +++ b/matsim/src/test/java/org/matsim/core/replanning/strategies/InnovationSwitchOffTest.java @@ -18,7 +18,7 @@ * *********************************************************************** */ /** - * + * */ package org.matsim.core.replanning.strategies; @@ -31,8 +31,8 @@ import org.matsim.api.core.v01.Id; 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.StrategyConfigGroup.StrategySettings; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ReplanningConfigGroup.StrategySettings; import org.matsim.core.controler.*; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Injector; @@ -64,7 +64,7 @@ public class InnovationSwitchOffTest { @Test public void testInnovationSwitchOff() { Config config = ConfigUtils.createConfig(ExamplesUtils.getTestScenarioURL("equil")); - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); config.network().setInputFile("network.xml"); config.plans().setInputFile("plans2.xml"); @@ -73,44 +73,44 @@ public void testInnovationSwitchOff() { StrategySettings settings = new StrategySettings(Id.create(1, StrategySettings.class)); settings.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.BestScore.toString()); settings.setWeight(0.5); - config.strategy().addStrategySettings(settings); + config.replanning().addStrategySettings(settings); } { StrategySettings settings = new StrategySettings(Id.create(2, StrategySettings.class)); settings.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta.toString()); settings.setWeight(0.5); - config.strategy().addStrategySettings(settings); + config.replanning().addStrategySettings(settings); } { StrategySettings settings = new StrategySettings(Id.create(3, StrategySettings.class)); settings.setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.TimeAllocationMutator.toString()); settings.setWeight(0.1); - config.strategy().addStrategySettings(settings); + config.replanning().addStrategySettings(settings); } { StrategySettings settings = new StrategySettings(Id.create(4, StrategySettings.class)); settings.setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.ReRoute.toString()); settings.setWeight(0.1); settings.setDisableAfter(11); - config.strategy().addStrategySettings(settings); + config.replanning().addStrategySettings(settings); } - config.strategy().setFractionOfIterationsToDisableInnovation(0.66); + config.replanning().setFractionOfIterationsToDisableInnovation(0.66); - config.controler().setFirstIteration(10); - config.controler().setLastIteration(16); + config.controller().setFirstIteration(10); + config.controller().setLastIteration(16); { ActivityParams params = new ActivityParams("h"); params.setTypicalDuration(12. * 3600.); - config.planCalcScore().addActivityParams(params); + config.scoring().addActivityParams(params); } { ActivityParams params = new ActivityParams("w"); params.setTypicalDuration(8. * 3600.); - config.planCalcScore().addActivityParams(params); + config.scoring().addActivityParams(params); } - config.controler().setCreateGraphs(false); + config.controller().setCreateGraphs(false); com.google.inject.Injector injector = Injector.createInjector(config, new AbstractModule() { diff --git a/matsim/src/test/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorModuleTest.java b/matsim/src/test/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorModuleTest.java index 54ff79db0e3..00e5fa6b164 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorModuleTest.java @@ -22,40 +22,31 @@ import static org.junit.Assert.assertTrue; -import jakarta.inject.Provider; - +import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; -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.core.config.Config; -import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.TimeAllocationMutatorConfigGroup.TimeAllocationMutatorSubpopulationSettings; +import org.matsim.api.core.v01.population.*; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.algorithms.PlanAlgorithm; -import org.matsim.core.population.algorithms.PlanMutateTimeAllocation; -import org.matsim.core.population.algorithms.PlanMutateTimeAllocationSimplified; -import org.matsim.core.population.algorithms.TripPlanMutateTimeAllocation; -import org.matsim.core.router.TripRouter; -import org.matsim.core.router.TripStructureUtils.StageActivityHandling; -import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.core.population.algorithms.MutateActivityTimeAllocation; import org.matsim.core.utils.misc.Time; +import org.matsim.pt.PtConstants; import org.matsim.testcases.MatsimTestUtils; +import java.util.Random; + /** * Tests the functionality of {@link TimeAllocationMutatorModule}, mainly that the - * correct mutation range is handed over to the underlying {@link PlanMutateTimeAllocation}. + * correct mutation range is handed over to the underlying {@link MutateActivityTimeAllocation}. * * @author mrieser */ @@ -65,141 +56,11 @@ public class TimeAllocationMutatorModuleTest { public MatsimTestUtils utils = new MatsimTestUtils(); - /** - * Tests that the mutation range given in the constructor is respected. - * - * @author mrieser - */ - @Test public void testMutationRangeParam() { - boolean affectingDuration = true ; - - runMutationRangeTest(new TripPlanMutateTimeAllocation(750, affectingDuration, MatsimRandom.getLocalInstance()), 750); - runMutationRangeTest(new TripPlanMutateTimeAllocation(7200, affectingDuration, MatsimRandom.getLocalInstance()), 7200); - } - @Test public void testSimplifiedMutation() { boolean affectingDuration = true ; - runSimplifiedMutationRangeTest(new PlanMutateTimeAllocationSimplified(StageActivityHandling.ExcludeStageActivities, 750, affectingDuration, MatsimRandom.getLocalInstance()), 750); - runSimplifiedMutationRangeTest(new PlanMutateTimeAllocationSimplified(StageActivityHandling.ExcludeStageActivities, 7200, affectingDuration, MatsimRandom.getLocalInstance()), 7200); - } - - @Test public void testSubpopulations() { - - String cbSubpopulation = "cb"; - String freightSubpopulation = "freight"; - - Config config = ConfigUtils.createConfig(); -// config.plans().setSubpopulationAttributeName("subpopulation"); - config.timeAllocationMutator().setUseIndividualSettingsForSubpopulations(true); - config.timeAllocationMutator().setMutationRange(1800.0); - - TimeAllocationMutatorSubpopulationSettings cbSettings = (TimeAllocationMutatorSubpopulationSettings) config.timeAllocationMutator().createParameterSet(TimeAllocationMutatorSubpopulationSettings.SET_NAME); - cbSettings.setSubpopulation(cbSubpopulation); - cbSettings.setAffectingDuration(false); - cbSettings.setMutationRange(100.0); - config.timeAllocationMutator().addParameterSet(cbSettings); - - TimeAllocationMutatorSubpopulationSettings freightSettings = (TimeAllocationMutatorSubpopulationSettings) config.timeAllocationMutator().createParameterSet(TimeAllocationMutatorSubpopulationSettings.SET_NAME); - freightSettings.setSubpopulation(freightSubpopulation); - freightSettings.setAffectingDuration(true); - freightSettings.setMutationRange(7200.0); - config.timeAllocationMutator().addParameterSet(freightSettings); - - Provider tripRouterProvider = null; - - TimeAllocationMutatorModule mutator = new TimeAllocationMutatorModule(tripRouterProvider, config.plans(), config.timeAllocationMutator(), config.global()); - - Scenario scenario = ScenarioUtils.createScenario(config); - - TimeAllocationMutatorModule cbMutator = new TimeAllocationMutatorModule(tripRouterProvider, config.plans(), config.timeAllocationMutator(), config.global(), scenario.getPopulation()); -// assertEquals(false, cbMutator.affectingDuration); -// assertEquals(100.0, cbMutator.mutationRange); -// -// TimeAllocationMutator freightMutator = new TimeAllocationMutator(tripRouterProvider, config.plans(), config.timeAllocationMutator(), config.global(), scenario.getPopulation()); -// assertEquals(true, freightMutator.affectingDuration); -// assertEquals(7200.0, freightMutator.mutationRange); - } - - /** - * Internal helper method to run the real test, but with different setups. - * Basically, it creates one plan and calls the given TimeAllocationMutator - * several times with this plans, each time measuring how much the activity - * durations have changed and thus ensuring, the differences are within the - * expected range. - * - * @param tripPlanMutateTimeAllocation A preset TimeAllocationMutator to be used for the tests. - * @param expectedMutationRange The expected range for mutation. - */ - private static void runMutationRangeTest( final PlanAlgorithm tripPlanMutateTimeAllocation, final int expectedMutationRange ) { - // setup network - Network network = NetworkUtils.createNetwork(); - network.setCapacityPeriod(Time.parseTime("01:00:00")); - Node node1 = NetworkUtils.createAndAddNode(network, Id.create("1", Node.class), new Coord((double) 0, (double) 0)); - Node node2 = NetworkUtils.createAndAddNode(network, Id.create("2", Node.class), new Coord((double) 100, (double) 0)); - Node node3 = NetworkUtils.createAndAddNode(network, Id.create("3", Node.class), new Coord((double) 200, (double) 0)); - Node node4 = NetworkUtils.createAndAddNode(network, Id.create("4", Node.class), new Coord((double) 300, (double) 0)); - final Node fromNode = node1; - final Node toNode = node2; - Link link1 = NetworkUtils.createAndAddLink(network,Id.create("0", Link.class), fromNode, toNode, (double) 100, (double) 5, (double) 100, (double) 1 ); - final Node fromNode1 = node2; - final Node toNode1 = node3; - NetworkUtils.createAndAddLink(network,Id.create("1", Link.class), fromNode1, toNode1, (double) 100, (double) 5, (double) 100, (double) 1 ); - final Node fromNode2 = node3; - final Node toNode2 = node4; - NetworkUtils.createAndAddLink(network,Id.create("2", Link.class), fromNode2, toNode2, (double) 100, (double) 5, (double) 100, (double) 1 ); - - // setup person - Plan plan; - Activity act1, act2; - try { - /* The chosen times for the activity durations are such that it is likely - * for the random mutation to reach midnight (either at 00:00:00 or at 24:00:00). - */ - Person person = PopulationUtils.getFactory().createPerson(Id.create("1", Person.class)); - plan = PersonUtils.createAndAddPlan(person, true); - act1 = PopulationUtils.createAndAddActivityFromLinkId(plan, "h", link1.getId()); - act1.setEndTime(4*3600); - PopulationUtils.createAndAddLeg( plan, TransportMode.car ); - act2 = PopulationUtils.createAndAddActivityFromLinkId(plan, "w", link1.getId()); - act2.setMaximumDuration(14*3600); - PopulationUtils.createAndAddLeg( plan, TransportMode.car ); - PopulationUtils.createAndAddActivityFromLinkId(plan, "h", link1.getId()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - // run test - double act1Dur = act1.getEndTime().seconds(); - double minDiff1 = Double.POSITIVE_INFINITY; - double maxDiff1 = Double.NEGATIVE_INFINITY; - double act2Dur = act2.getMaximumDuration().seconds(); - double minDiff2 = Double.POSITIVE_INFINITY; - double maxDiff2 = Double.NEGATIVE_INFINITY; - for (int i = 0; i < 150; i++) { - tripPlanMutateTimeAllocation.run(plan); - // test duration of act1 - double diff = act1Dur - act1.getMaximumDuration().seconds(); - if (diff > maxDiff1) maxDiff1 = diff; - if (diff < minDiff1) minDiff1 = diff; - act1Dur = act1.getMaximumDuration().seconds(); - assertTrue("activity duration cannot be smaller than 0, is " + act1Dur, act1Dur >= 0.0); - // test duration of act2 - diff = act2Dur - act2.getMaximumDuration().seconds(); - if (diff > maxDiff2) maxDiff2 = diff; - if (diff < minDiff2) minDiff2 = diff; - act2Dur = act2.getMaximumDuration().seconds(); - assertTrue("activity duration cannot be smaller than 0, is " + act2Dur, act2Dur >= 0.0); - } - assertTrue("mutation range differences wrong (act1).", minDiff1 <= maxDiff1); - assertTrue("mutation range differences wrong (act2).", minDiff2 <= maxDiff2); - - /* The following asserts are dependent on random numbers. - * But I would still expect that we get up to at least 95% of the limit... */ - assertValueInRange("mutation range out of range (maxDiff1).", maxDiff1, expectedMutationRange*0.95, expectedMutationRange); - assertValueInRange("mutation range out of range (minDiff1).", minDiff1, -expectedMutationRange, -expectedMutationRange*0.95); - assertValueInRange("mutation range out of range (maxDiff2).", maxDiff1, expectedMutationRange*0.95, expectedMutationRange); - assertValueInRange("mutation range out of range (minDiff2).", minDiff2, -expectedMutationRange, -expectedMutationRange*0.95); + runSimplifiedMutationRangeTest(new MutateActivityTimeAllocation( 750, affectingDuration, MatsimRandom.getLocalInstance(),24*3600,false,1), 750); + runSimplifiedMutationRangeTest(new MutateActivityTimeAllocation( 7200, affectingDuration, MatsimRandom.getLocalInstance(),24*3600,false,1), 7200); } /** @@ -216,19 +77,19 @@ private void runSimplifiedMutationRangeTest(final PlanAlgorithm tripPlanMutateTi // setup network Network network = NetworkUtils.createNetwork(); network.setCapacityPeriod(Time.parseTime("01:00:00")); - Node node1 = NetworkUtils.createAndAddNode(network, Id.create("1", Node.class), new Coord((double) 0, (double) 0)); - Node node2 = NetworkUtils.createAndAddNode(network, Id.create("2", Node.class), new Coord((double) 100, (double) 0)); - Node node3 = NetworkUtils.createAndAddNode(network, Id.create("3", Node.class), new Coord((double) 200, (double) 0)); - Node node4 = NetworkUtils.createAndAddNode(network, Id.create("4", Node.class), new Coord((double) 300, (double) 0)); + 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(100, 0)); + Node node3 = NetworkUtils.createAndAddNode(network, Id.create("3", Node.class), new Coord(200, 0)); + Node node4 = NetworkUtils.createAndAddNode(network, Id.create("4", Node.class), new Coord(300, 0)); final Node fromNode = node1; final Node toNode = node2; - Link link1 = NetworkUtils.createAndAddLink(network,Id.create("0", Link.class), fromNode, toNode, (double) 100, (double) 5, (double) 100, (double) 1 ); + Link link1 = NetworkUtils.createAndAddLink(network,Id.create("0", Link.class), fromNode, toNode, 100, 5, 100, 1); final Node fromNode1 = node2; final Node toNode1 = node3; - NetworkUtils.createAndAddLink(network,Id.create("1", Link.class), fromNode1, toNode1, (double) 100, (double) 5, (double) 100, (double) 1 ); + NetworkUtils.createAndAddLink(network,Id.create("1", Link.class), fromNode1, toNode1, 100, 5, 100, 1); final Node fromNode2 = node3; final Node toNode2 = node4; - NetworkUtils.createAndAddLink(network,Id.create("2", Link.class), fromNode2, toNode2, (double) 100, (double) 5, (double) 100, (double) 1 ); + NetworkUtils.createAndAddLink(network,Id.create("2", Link.class), fromNode2, toNode2, 100, 5, 100, 1); // setup person Plan plan; @@ -286,4 +147,134 @@ private void runSimplifiedMutationRangeTest(final PlanAlgorithm tripPlanMutateTi private static void assertValueInRange(final String message, final double actual, final double lowerLimit, final double upperLimit) { assertTrue(message + " actual: " + actual + ", range: " + lowerLimit + "..." + upperLimit, (lowerLimit <= actual) && (actual <= upperLimit)); } + + + @Test + public void testRun() { + // setup population with one person + Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); + Plan plan = PersonUtils.createAndAddPlan(person, true); + Activity act = PopulationUtils.createAndAddActivityFromCoord(plan, "home", new Coord(0, 0)); + act.setEndTime(8.0 * 3600); + PopulationUtils.createAndAddLeg( plan, TransportMode.transit_walk ); + Activity ptAct1 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, new Coord(0, 100)); + ptAct1.setMaximumDuration(0); + PopulationUtils.createAndAddLeg( plan, TransportMode.pt ); + Activity ptAct2 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, new Coord(0, 100)); + ptAct2.setMaximumDuration(0); + PopulationUtils.createAndAddLeg( plan, TransportMode.transit_walk ); + act = PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord(0, 500)); + act.setEndTime(16*3600); + PopulationUtils.createAndAddLeg( plan, TransportMode.transit_walk ); + Activity ptAct3 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, new Coord(0, 100)); + ptAct3.setMaximumDuration(0); + PopulationUtils.createAndAddLeg( plan, TransportMode.pt ); + Activity ptAct4 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, new Coord(0, 100)); + ptAct4.setMaximumDuration(0); + PopulationUtils.createAndAddLeg( plan, TransportMode.transit_walk ); + PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord(0, 500)); + boolean affectingDuration = true ; + + MutateActivityTimeAllocation mutator = + new MutateActivityTimeAllocation( + 3600., + affectingDuration, new Random(2011),24*3600,false,1); + mutator.run(plan); + + Assert.assertEquals(0.0, ptAct1.getMaximumDuration().seconds(), 1e-8); + Assert.assertEquals(0.0, ptAct2.getMaximumDuration().seconds(), 1e-8); + Assert.assertEquals(0.0, ptAct3.getMaximumDuration().seconds(), 1e-8); + Assert.assertEquals(0.0, ptAct4.getMaximumDuration().seconds(), 1e-8); + } + + @Test + public void testRunLatestEndTime() { + // setup population with one person + Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); + Plan plan = PersonUtils.createAndAddPlan(person, true); + Activity act = PopulationUtils.createAndAddActivityFromCoord(plan, "home", new Coord(0, 0)); + act.setEndTime(8.0 * 3600); + PopulationUtils.createAndAddLeg(plan, TransportMode.transit_walk); + Activity ptAct1 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, + new Coord(0, 100)); + ptAct1.setMaximumDuration(0); + PopulationUtils.createAndAddLeg(plan, TransportMode.pt); + Activity ptAct2 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, + new Coord(0, 100)); + ptAct2.setMaximumDuration(0); + PopulationUtils.createAndAddLeg(plan, TransportMode.transit_walk); + act = PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord(0, 500)); + act.setEndTime(38 * 3600); + PopulationUtils.createAndAddLeg(plan, TransportMode.transit_walk); + Activity ptAct3 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, + new Coord(0, 100)); + ptAct3.setMaximumDuration(0); + PopulationUtils.createAndAddLeg(plan, TransportMode.pt); + Activity ptAct4 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, + new Coord(0, 100)); + ptAct4.setMaximumDuration(0); + PopulationUtils.createAndAddLeg(plan, TransportMode.transit_walk); + PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord(0, 500)); + + boolean affectingDuration = true; + final double latestEndTime = 30. * 3600; + + MutateActivityTimeAllocation mutator = + new MutateActivityTimeAllocation( + 3600., + affectingDuration, new Random(2011),latestEndTime,false,1); + + mutator.run(plan); + + Assert.assertEquals(0.0, ptAct1.getMaximumDuration().seconds(), 1e-8); + Assert.assertEquals(0.0, ptAct2.getMaximumDuration().seconds(), 1e-8); + Assert.assertEquals(0.0, ptAct3.getMaximumDuration().seconds(), 1e-8); + Assert.assertEquals(0.0, ptAct4.getMaximumDuration().seconds(), 1e-8); + + // check whether activity times are equal or less than latestEndTime + for (PlanElement pe : plan.getPlanElements()) { + if (pe instanceof Activity activity) { + if (activity.getStartTime().isDefined()) { + Assert.assertTrue(activity.getStartTime().seconds() <= latestEndTime); + } + if (activity.getEndTime().isDefined()) { + Assert.assertTrue(activity.getEndTime().seconds() <= latestEndTime); + } + } + } + } + @Test + public void testLegTimesAreSetCorrectly() { + // setup population with one person + Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); + Plan plan = PersonUtils.createAndAddPlan(person, true); + Activity act = PopulationUtils.createAndAddActivityFromCoord(plan, "home", new Coord(0, 0)); + act.setEndTime(8.0 * 3600); + Leg leg1 = PopulationUtils.createAndAddLeg( plan, TransportMode.walk ); + leg1.setDepartureTime(8.0*3600); + leg1.setTravelTime(1800.); + Activity act2 = PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord(0, 500)); + act2.setMaximumDuration(8*3600); + Leg leg2 = PopulationUtils.createAndAddLeg( plan, TransportMode.walk ); + leg2.setDepartureTime(16.5*3600); + leg2.setTravelTime(1800.0); + PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord(0, 500)); + boolean affectingDuration = true ; + + MutateActivityTimeAllocation mutator = + new MutateActivityTimeAllocation( + 3600., + affectingDuration, new Random(2011),24*3600,false,1); + mutator.run(plan); + + double firstActEndTime = act.getEndTime().seconds(); + double secondActDuration = act2.getMaximumDuration().seconds(); + Assert.assertEquals(firstActEndTime,leg1.getDepartureTime().seconds(), MatsimTestUtils.EPSILON); + Assert.assertEquals(firstActEndTime+secondActDuration+leg1.getTravelTime().seconds(),leg2.getDepartureTime().seconds(), MatsimTestUtils.EPSILON); + + + + } + + } diff --git a/matsim/src/test/java/org/matsim/core/router/AStarEuclideanTest.java b/matsim/src/test/java/org/matsim/core/router/AStarEuclideanTest.java index 1892e6324ba..7d005bcac3f 100644 --- a/matsim/src/test/java/org/matsim/core/router/AStarEuclideanTest.java +++ b/matsim/src/test/java/org/matsim/core/router/AStarEuclideanTest.java @@ -21,7 +21,7 @@ package org.matsim.core.router; import org.matsim.api.core.v01.network.Network; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.PreProcessEuclidean; @@ -30,7 +30,7 @@ public class AStarEuclideanTest extends AbstractLeastCostPathCalculatorTest { @Override protected LeastCostPathCalculator getLeastCostPathCalculator(Network network) { - FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new PlanCalcScoreConfigGroup()); + FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new ScoringConfigGroup()); PreProcessEuclidean preProcessData = new PreProcessEuclidean(travelTimeCostCalculator); preProcessData.run(network); return new AStarEuclidean(network, preProcessData, travelTimeCostCalculator); diff --git a/matsim/src/test/java/org/matsim/core/router/AStarLandmarksTest.java b/matsim/src/test/java/org/matsim/core/router/AStarLandmarksTest.java index 80797fa250e..8a5b7f711f1 100644 --- a/matsim/src/test/java/org/matsim/core/router/AStarLandmarksTest.java +++ b/matsim/src/test/java/org/matsim/core/router/AStarLandmarksTest.java @@ -21,7 +21,7 @@ package org.matsim.core.router; import org.matsim.api.core.v01.network.Network; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.PreProcessLandmarks; @@ -30,7 +30,7 @@ public class AStarLandmarksTest extends AbstractLeastCostPathCalculatorTest { @Override protected LeastCostPathCalculator getLeastCostPathCalculator(Network network) { - FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new PlanCalcScoreConfigGroup()); + FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new ScoringConfigGroup()); PreProcessLandmarks preProcessData = new PreProcessLandmarks(travelTimeCostCalculator); preProcessData.run(network); return new AStarLandmarks(network, preProcessData, travelTimeCostCalculator); diff --git a/matsim/src/test/java/org/matsim/core/router/DijkstraTest.java b/matsim/src/test/java/org/matsim/core/router/DijkstraTest.java index 8a1660e7360..99bd6b09de4 100644 --- a/matsim/src/test/java/org/matsim/core/router/DijkstraTest.java +++ b/matsim/src/test/java/org/matsim/core/router/DijkstraTest.java @@ -21,7 +21,7 @@ package org.matsim.core.router; import org.matsim.api.core.v01.network.Network; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; import org.matsim.core.router.util.LeastCostPathCalculator; @@ -32,7 +32,7 @@ public class DijkstraTest extends AbstractLeastCostPathCalculatorTest { @Override protected LeastCostPathCalculator getLeastCostPathCalculator(final Network network) { - FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new PlanCalcScoreConfigGroup()); + FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new ScoringConfigGroup()); return new Dijkstra(network, travelTimeCostCalculator, travelTimeCostCalculator); } diff --git a/matsim/src/test/java/org/matsim/core/router/FallbackRoutingModuleTest.java b/matsim/src/test/java/org/matsim/core/router/FallbackRoutingModuleTest.java index 413a557987a..2357da20138 100644 --- a/matsim/src/test/java/org/matsim/core/router/FallbackRoutingModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/router/FallbackRoutingModuleTest.java @@ -19,12 +19,11 @@ import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -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.replanning.strategies.DefaultPlanStrategiesModule; import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.facilities.Facility; import org.matsim.testcases.MatsimTestUtils; public class FallbackRoutingModuleTest{ @@ -34,13 +33,13 @@ public class FallbackRoutingModuleTest{ public void calcRoute(){ Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory( utils.getOutputDirectory() ); - config.controler().setLastIteration( 1 ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setLastIteration( 1 ); - StrategyConfigGroup.StrategySettings sets = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings sets = new ReplanningConfigGroup.StrategySettings(); sets.setStrategyName( DefaultPlanStrategiesModule.DefaultStrategy.ReRoute ); sets.setWeight( 1. ); - config.strategy().addStrategySettings( sets ); + config.replanning().addStrategySettings( sets ); Scenario scenario = ScenarioUtils.createScenario( config ); diff --git a/matsim/src/test/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModuleTest.java b/matsim/src/test/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModuleTest.java index 61c3b7c51c3..6f53a8f7363 100644 --- a/matsim/src/test/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModuleTest.java @@ -16,11 +16,11 @@ import org.matsim.api.core.v01.population.*; 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.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; 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; @@ -103,24 +103,24 @@ private Config createConfig() { Config config = ConfigUtils.createConfig(); config.qsim().setUsePersonIdForMissingVehicleId(true); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); - final PlanCalcScoreConfigGroup.ActivityParams homeParams = new PlanCalcScoreConfigGroup.ActivityParams("home"); + final ScoringConfigGroup.ActivityParams homeParams = new ScoringConfigGroup.ActivityParams("home"); homeParams.setTypicalDuration(1); - config.planCalcScore().addActivityParams(homeParams); + config.scoring().addActivityParams(homeParams); - final PlanCalcScoreConfigGroup.ActivityParams workParams = new PlanCalcScoreConfigGroup.ActivityParams("work"); + final ScoringConfigGroup.ActivityParams workParams = new ScoringConfigGroup.ActivityParams("work"); workParams.setTypicalDuration(1); - config.planCalcScore().addActivityParams(workParams); + config.scoring().addActivityParams(workParams); - StrategyConfigGroup.StrategySettings replanning = new StrategyConfigGroup.StrategySettings(); + ReplanningConfigGroup.StrategySettings replanning = new ReplanningConfigGroup.StrategySettings(); replanning.setStrategyName("ReRoute"); replanning.setWeight(1.0); - config.strategy().addStrategySettings(replanning); + config.replanning().addStrategySettings(replanning); return config; } @@ -187,14 +187,14 @@ public void calcRoute_modeVehiclesFromVehiclesData_differentTypesTakeDifferentRo config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.modeVehicleTypesFromVehiclesData); config.qsim().setMainModes(modes); - config.plansCalcRoute().setNetworkModes(modes); - PlanCalcScoreConfigGroup scoring = config.planCalcScore(); + config.routing().setNetworkModes(modes); + ScoringConfigGroup scoring = config.scoring(); - PlanCalcScoreConfigGroup.ModeParams slowParams = new PlanCalcScoreConfigGroup.ModeParams(SLOW_MODE); + ScoringConfigGroup.ModeParams slowParams = new ScoringConfigGroup.ModeParams(SLOW_MODE); slowParams.setMarginalUtilityOfTraveling(-1); scoring.addModeParams(slowParams); - PlanCalcScoreConfigGroup.ModeParams fastParams = new PlanCalcScoreConfigGroup.ModeParams(FAST_MODE); + ScoringConfigGroup.ModeParams fastParams = new ScoringConfigGroup.ModeParams(FAST_MODE); fastParams.setMarginalUtilityOfTraveling(-1); scoring.addModeParams(fastParams); @@ -263,7 +263,7 @@ public void useAccessEgressTimeFromLinkAttributes() { Config config = createConfig(); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.defaultVehicle); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.walkConstantTimeToLink); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.walkConstantTimeToLink); Scenario scenario = createScenario(config); NetworkUtils.setLinkAccessTime(scenario.getNetwork().getLinks().get(Id.createLinkId(START_LINK)),TransportMode.car,75); NetworkUtils.setLinkEgressTime(scenario.getNetwork().getLinks().get(Id.createLinkId(END_LINK)),TransportMode.car,180); @@ -284,7 +284,7 @@ public void useAccessEgressTimeFromConstantAndWalkTime() { Config config = createConfig(); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.defaultVehicle); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLinkPlusTimeConstant); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLinkPlusTimeConstant); Scenario scenario = createScenario(config); NetworkUtils.setLinkAccessTime(scenario.getNetwork().getLinks().get(Id.createLinkId(START_LINK)),TransportMode.car,75); NetworkUtils.setLinkEgressTime(scenario.getNetwork().getLinks().get(Id.createLinkId(END_LINK)),TransportMode.car,180); @@ -301,13 +301,13 @@ public void useAccessEgressTimeFromConstantAndWalkTime() { Assert.equals(90.0,legs.get(0).getTravelTime().seconds()); Assert.equals(180.0,legs.get(2).getTravelTime().seconds()); } - + @Test public void routingModeInEvents() { Config config = createConfig(); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.defaultVehicle); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLinkPlusTimeConstant); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLinkPlusTimeConstant); Scenario scenario = createScenario(config); NetworkUtils.setLinkAccessTime(scenario.getNetwork().getLinks().get(Id.createLinkId(START_LINK)),TransportMode.car,75); NetworkUtils.setLinkEgressTime(scenario.getNetwork().getLinks().get(Id.createLinkId(END_LINK)),TransportMode.car,180); @@ -318,10 +318,10 @@ public void routingModeInEvents() { scenario.getPopulation().addPerson(person); Controler controler = createControler(scenario); - + Set legModes = new HashSet<>(); Set routingModes = new HashSet<>(); - + controler.addOverridingModule(new AbstractModule() { @Override public void install() { @@ -334,9 +334,9 @@ public void handleEvent(PersonDepartureEvent event) { }); } }); - + controler.run(); - + Assert.equals(2, legModes.size()); Assert.equals(1, routingModes.size()); Assert.isTrue(legModes.contains("walk")); @@ -349,7 +349,7 @@ public void failifNoAccessTimeSet() { Config config = createConfig(); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.defaultVehicle); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.walkConstantTimeToLink); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.walkConstantTimeToLink); Scenario scenario = createScenario(config); NetworkUtils.setLinkAccessTime(scenario.getNetwork().getLinks().get(Id.createLinkId(START_LINK)),TransportMode.car,75); Person person = createPerson("slow-person", TransportMode.car, scenario.getPopulation().getFactory()); @@ -364,7 +364,7 @@ public void failifNoEgressTimeSet() { Config config = createConfig(); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.defaultVehicle); - config.plansCalcRoute().setAccessEgressType(AccessEgressType.walkConstantTimeToLink); + config.routing().setAccessEgressType(AccessEgressType.walkConstantTimeToLink); Scenario scenario = createScenario(config); NetworkUtils.setLinkEgressTime(scenario.getNetwork().getLinks().get(Id.createLinkId(END_LINK)),TransportMode.car,180); Person person = createPerson("slow-person", TransportMode.car, scenario.getPopulation().getFactory()); @@ -378,7 +378,7 @@ public void calcAccessTimeFromDistanceToLink() { Config config = createConfig(); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.defaultVehicle); - config.plansCalcRoute().setAccessEgressType(PlansCalcRouteConfigGroup.AccessEgressType.accessEgressModeToLink); + config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); Scenario scenario = createScenario(config); NetworkUtils.setLinkAccessTime(scenario.getNetwork().getLinks().get(Id.createLinkId(START_LINK)),TransportMode.car,75); NetworkUtils.setLinkAccessTime(scenario.getNetwork().getLinks().get(Id.createLinkId(END_LINK)),TransportMode.car,180); @@ -403,7 +403,7 @@ public void noBushwackingLegs() { Config config = createConfig(); config.qsim().setVehiclesSource(QSimConfigGroup.VehiclesSource.defaultVehicle); - config.plansCalcRoute().setAccessEgressType(AccessEgressType.none); + config.routing().setAccessEgressType(AccessEgressType.none); Scenario scenario = createScenario(config); NetworkUtils.setLinkAccessTime(scenario.getNetwork().getLinks().get(Id.createLinkId(START_LINK)),TransportMode.car,75); NetworkUtils.setLinkAccessTime(scenario.getNetwork().getLinks().get(Id.createLinkId(END_LINK)),TransportMode.car,180); diff --git a/matsim/src/test/java/org/matsim/core/router/NetworkRoutingModuleTest.java b/matsim/src/test/java/org/matsim/core/router/NetworkRoutingModuleTest.java index 465af0ffb00..ac63754fd20 100644 --- a/matsim/src/test/java/org/matsim/core/router/NetworkRoutingModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/router/NetworkRoutingModuleTest.java @@ -85,7 +85,7 @@ public void testRouteLegWithDistance() { fromAct.setLinkId(Id.create("1", Link.class)); Activity toAct = PopulationUtils.createActivityFromCoord("h", new Coord(0, 3000)); toAct.setLinkId(Id.create("3", Link.class)); - + TravelTime timeObject = TravelTimeCalculator.create(f.s.getNetwork(), f.s.getConfig().travelTimeCalculator()).getLinkTravelTimes() ; { @@ -113,10 +113,10 @@ public void testRouteLegWithDistance() { Assert.assertEquals(0.3333333333, route.getTravelCost(), 1e-8 ) ; } // and now with a monetary distance rate different from zero: - + { double monetaryDistanceRateCar = -1.; - f.s.getConfig().planCalcScore().getModes().get(TransportMode.car).setMonetaryDistanceRate(monetaryDistanceRateCar); + f.s.getConfig().scoring().getModes().get(TransportMode.car).setMonetaryDistanceRate(monetaryDistanceRateCar); TravelDisutility costObject = new RandomizingTimeDistanceTravelDisutilityFactory( TransportMode.car, f.s.getConfig() ).createTravelDisutility(timeObject ); @@ -132,8 +132,8 @@ public void testRouteLegWithDistance() { List result = router.calcRoute( DefaultRoutingRequest.withoutAttributes( FacilitiesUtils.toFacility(fromAct, f.s.getActivityFacilities() ), FacilitiesUtils.toFacility(toAct, f.s.getActivityFacilities() ), 7.*3600, person ) ) ; - - Assert.assertEquals( 1, result.size() ) ; + + Assert.assertEquals( 1, result.size() ) ; Leg leg = (Leg) result.get(0) ; Assert.assertEquals(100.0, leg.getTravelTime().seconds(), 1e-8); @@ -148,7 +148,7 @@ private static class Fixture { public final Scenario s = ScenarioUtils.createScenario(ConfigUtils.createConfig()); Fixture() { - s.getConfig().plansCalcRoute().setRoutingRandomness( 0. ); + s.getConfig().routing().setRoutingRandomness( 0. ); Network net = this.s.getNetwork(); NetworkFactory nf = net.getFactory(); diff --git a/matsim/src/test/java/org/matsim/core/router/PersonalizableDisutilityIntegrationTest.java b/matsim/src/test/java/org/matsim/core/router/PersonalizableDisutilityIntegrationTest.java index fdb79a4b356..a2822d64d4a 100644 --- a/matsim/src/test/java/org/matsim/core/router/PersonalizableDisutilityIntegrationTest.java +++ b/matsim/src/test/java/org/matsim/core/router/PersonalizableDisutilityIntegrationTest.java @@ -30,6 +30,7 @@ import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.population.PopulationUtils; +import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.LeastCostPathCalculatorFactory; import org.matsim.core.router.util.PreProcessEuclidean; @@ -44,33 +45,18 @@ * @author mrieser / senozon */ public class PersonalizableDisutilityIntegrationTest { - + @Test public void testPersonAvailableForDisutility_Dijkstra() { Fixture f = new Fixture(); - + Dijkstra router = new Dijkstra(f.network, f.costFunction, new FreeSpeedTravelTime()); router.calcLeastCostPath( - f.network.getNodes().get(Id.create("2", Node.class)), + f.network.getNodes().get(Id.create("2", Node.class)), f.network.getNodes().get(Id.create("1", Node.class)), 07*3600, f.person, f.vehicle); // hopefully there was no Exception until here... - - Assert.assertEquals(22, f.costFunction.cnt); // make sure the costFunction was actually used - } - - @Test - public void testPersonAvailableForDisutility_FastDijkstra() { - Fixture f = new Fixture(); - - LeastCostPathCalculatorFactory routerFactory = new FastDijkstraFactory(); - LeastCostPathCalculator router = routerFactory.createPathCalculator(f.network, f.costFunction, new FreeSpeedTravelTime()); - router.calcLeastCostPath( - f.network.getNodes().get(Id.create("2", Node.class)), - f.network.getNodes().get(Id.create("1", Node.class)), - 07*3600, f.person, f.vehicle); - // hopefully there was no Exception until here... - + Assert.assertEquals(22, f.costFunction.cnt); // make sure the costFunction was actually used } @@ -81,86 +67,57 @@ public void testPersonAvailableForDisutility_AStarEuclidean() { preprocess.run(f.network); AStarEuclidean router = new AStarEuclidean(f.network, preprocess, new FreeSpeedTravelTime()); router.calcLeastCostPath( - f.network.getNodes().get(Id.create("2", Node.class)), - f.network.getNodes().get(Id.create("1", Node.class)), - 07*3600, f.person, f.vehicle); - // hopefully there was no Exception until here... - - Assert.assertEquals(22, f.costFunction.cnt); // make sure the costFunction was actually used - } - - @Test - public void testPersonAvailableForDisutility_FastAStarEuclidean() { - Fixture f = new Fixture(); - PreProcessEuclidean preprocess = new PreProcessEuclidean(f.costFunction); - preprocess.run(f.network); - AStarEuclidean router = new AStarEuclidean(f.network, preprocess, new FreeSpeedTravelTime()); - router.calcLeastCostPath( - f.network.getNodes().get(Id.create("2", Node.class)), - f.network.getNodes().get(Id.create("1", Node.class)), + f.network.getNodes().get(Id.create("2", Node.class)), + f.network.getNodes().get(Id.create("1", Node.class)), 07*3600, f.person, f.vehicle); // hopefully there was no Exception until here... - - Assert.assertEquals(22, f.costFunction.cnt); // make sure the costFunction was actually used - } - @Test - public void testPersonAvailableForDisutility_AStarLandmarks() { - Fixture f = new Fixture(); - LeastCostPathCalculatorFactory routerFactory = new FastAStarEuclideanFactory(); - LeastCostPathCalculator router = routerFactory.createPathCalculator(f.network, f.costFunction, new FreeSpeedTravelTime()); - router.calcLeastCostPath( - f.network.getNodes().get(Id.create("2", Node.class)), - f.network.getNodes().get(Id.create("1", Node.class)), - 07*3600, f.person, f.vehicle); - // hopefully there was no Exception until here... - Assert.assertEquals(22, f.costFunction.cnt); // make sure the costFunction was actually used } - + @Test - public void testPersonAvailableForDisutility_FastAStarLandmarks() { + public void testPersonAvailableForDisutility_SpeedyALT() { Fixture f = new Fixture(); - LeastCostPathCalculatorFactory routerFactory = new FastAStarLandmarksFactory(2); + LeastCostPathCalculatorFactory routerFactory = new SpeedyALTFactory(); LeastCostPathCalculator router = routerFactory.createPathCalculator(f.network, f.costFunction, new FreeSpeedTravelTime()); router.calcLeastCostPath( - f.network.getNodes().get(Id.create("2", Node.class)), - f.network.getNodes().get(Id.create("1", Node.class)), + f.network.getNodes().get(Id.create("2", Node.class)), + f.network.getNodes().get(Id.create("1", Node.class)), 07*3600, f.person, f.vehicle); // hopefully there was no Exception until here... - + Assert.assertEquals(22, f.costFunction.cnt); // make sure the costFunction was actually used } - + private static class Fixture { /*package*/ final Scenario scenario; /*package*/ final Network network; /*package*/ final Vehicle vehicle; /*package*/ final Person person; /*package*/ final PersonEnforcingTravelDisutility costFunction; - + public Fixture() { this.scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); new MatsimNetworkReader(this.scenario.getNetwork()).readFile("test/scenarios/equil/network.xml"); - + this.person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); Id dummyId = Id.createVehicleId( "dummy" ) ; VehicleType dummyType = VehicleUtils.createVehicleType( Id.create( "dummyVehicleType", VehicleType.class ) ); this.vehicle = VehicleUtils.createVehicle(dummyId, dummyType ); - + this.costFunction = new PersonEnforcingTravelDisutility(); this.costFunction.setExpectations(this.person, this.vehicle); - + this.network = this.scenario.getNetwork(); } } - + private static class PersonEnforcingTravelDisutility implements TravelDisutility { private Person person = null; private Vehicle veh = null; - + /*package*/ int cnt = 0; /*package*/ void setExpectations(final Person person, final Vehicle veh) { diff --git a/matsim/src/test/java/org/matsim/core/router/PseudoTransitRoutingModuleTest.java b/matsim/src/test/java/org/matsim/core/router/PseudoTransitRoutingModuleTest.java index a7a9630d4d9..eeb366c2f68 100644 --- a/matsim/src/test/java/org/matsim/core/router/PseudoTransitRoutingModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/router/PseudoTransitRoutingModuleTest.java @@ -37,7 +37,7 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.TeleportedModeParams; +import org.matsim.core.config.groups.RoutingConfigGroup.TeleportedModeParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.ControlerDefaultsModule; import org.matsim.core.controler.Injector; @@ -65,7 +65,7 @@ public void testRouteLeg() { final Fixture f = new Fixture(); FreespeedTravelTimeAndDisutility freespeed = new FreespeedTravelTimeAndDisutility(-6.0/3600, +6.0/3600, 0.0); LeastCostPathCalculator routeAlgo = new Dijkstra(f.s.getNetwork(), freespeed, freespeed); - + Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); Leg leg = PopulationUtils.createLeg(TransportMode.pt); Activity fromAct = PopulationUtils.createActivityFromCoord("h", new Coord(0, 0)); @@ -98,14 +98,14 @@ public void testRouteLeg() { // the following test is newer than the ones above. I wanted to test the freespeed limit. But could not do it in the same way // above since it is not in FreespeedTravelTimeAndDisutility. Could have modified that disutility. But preferred to test in context. // Thus the more complicated injector thing. kai, nov'16 - + TeleportedModeParams params = new TeleportedModeParams("mode") ; params.setTeleportedModeFreespeedFactor(2.); params.setBeelineDistanceFactor(1.); params.setTeleportedModeFreespeedLimit(5.); - f.s.getConfig().plansCalcRoute().addModeRoutingParams(params); - f.s.getConfig().controler().setOutputDirectory(utils.getOutputDirectory()); - + f.s.getConfig().routing().addModeRoutingParams(params); + f.s.getConfig().controller().setOutputDirectory(utils.getOutputDirectory()); + com.google.inject.Injector injector = Injector.createInjector(f.s.getConfig(), new AbstractModule() { @Override public void install() { install(new NewControlerModule()); @@ -114,12 +114,12 @@ public void testRouteLeg() { install(new ScenarioByInstanceModule(f.s)); } }); - + TripRouter tripRouter = injector.getInstance(TripRouter.class) ; - + Facility fromFacility = FacilitiesUtils.toFacility(fromAct, f.s.getActivityFacilities() ) ; Facility toFacility = FacilitiesUtils.toFacility(toAct, f.s.getActivityFacilities() ); - + List result = tripRouter.calcRoute("mode", fromFacility, toFacility, 7.0*3600., person, new AttributesImpl()) ; Gbl.assertIf( result.size()==1); Leg newLeg = (Leg) result.get(0) ; @@ -134,12 +134,12 @@ private static class Fixture { public final Scenario s = ScenarioUtils.createScenario(ConfigUtils.createConfig()); public Fixture() { - s.getConfig().controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + s.getConfig().controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); TeleportedModeParams walk = new TeleportedModeParams(TransportMode.walk); walk.setBeelineDistanceFactor(1.3); walk.setTeleportedModeSpeed(3.0 / 3.6); - s.getConfig().plansCalcRoute().addModeRoutingParams(walk); - + s.getConfig().routing().addModeRoutingParams(walk); + Network net = this.s.getNetwork(); NetworkFactory nf = net.getFactory(); Node n1 = nf.createNode(Id.create("1", Node.class), new Coord(0, 0)); diff --git a/matsim/src/test/java/org/matsim/core/router/RoutingIT.java b/matsim/src/test/java/org/matsim/core/router/RoutingIT.java index 1539991fadc..0d1fc62702e 100644 --- a/matsim/src/test/java/org/matsim/core/router/RoutingIT.java +++ b/matsim/src/test/java/org/matsim/core/router/RoutingIT.java @@ -54,7 +54,7 @@ public class RoutingIT { /*package*/ static final Logger log = LogManager.getLogger(RoutingIT.class); - + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); private interface RouterProvider { @@ -75,19 +75,6 @@ public LeastCostPathCalculatorFactory getFactory(final Network network, final Tr }); } @Test - public void testFastDijkstra() { - doTest(new RouterProvider() { - @Override - public String getName() { - return "FastDijkstra"; - } - @Override - public LeastCostPathCalculatorFactory getFactory(final Network network, final TravelDisutility costCalc, final TravelTime timeCalc) { - return new FastDijkstraFactory(); - } - }); - } - @Test public void testSpeedyDijkstra() { doTest(new RouterProvider() { @Override @@ -113,20 +100,8 @@ public LeastCostPathCalculatorFactory getFactory(final Network network, final Tr } }); } + @Test - public void testFastDijkstraPruneDeadEnds() { - doTest(new RouterProvider() { - @Override - public String getName() { - return "FastDijkstraPruneDeadends"; - } - @Override - public LeastCostPathCalculatorFactory getFactory(final Network network, final TravelDisutility costCalc, final TravelTime timeCalc) { - return new FastDijkstraFactory(); - } - }); - } - @Test public void testAStarEuclidean() { doTest(new RouterProvider() { @Override @@ -140,19 +115,6 @@ public LeastCostPathCalculatorFactory getFactory(final Network network, final Tr }); } @Test - public void testFastAStarEuclidean() { - doTest(new RouterProvider() { - @Override - public String getName() { - return "FastAStarEuclidean"; - } - @Override - public LeastCostPathCalculatorFactory getFactory(final Network network, final TravelDisutility costCalc, final TravelTime timeCalc) { - return new FastAStarEuclideanFactory(); - } - }); - } - @Test public void testAStarLandmarks() { doTest(new RouterProvider() { @Override @@ -165,19 +127,7 @@ public LeastCostPathCalculatorFactory getFactory(final Network network, final Tr } }); } - @Test - public void testFastAStarLandmarks() { - doTest(new RouterProvider() { - @Override - public String getName() { - return "FastAStarLandmarks"; - } - @Override - public LeastCostPathCalculatorFactory getFactory(final Network network, final TravelDisutility costCalc, final TravelTime timeCalc) { - return new FastAStarLandmarksFactory(2); - } - }); - } + @Test public void testSpeedyALT() { doTest(new RouterProvider() { @@ -200,13 +150,13 @@ private void doTest(final RouterProvider provider) { // final String inPlansName = "test/input/" + this.getClass().getCanonicalName().replace('.', '/') + "/plans.xml.gz"; final String inPlansName = utils.getClassInputDirectory() + "/plans.xml.gz" ; new PopulationReader(scenario).readFile(inPlansName); - + calcRoute(provider, scenario); final Scenario referenceScenario = ScenarioUtils.createScenario(config); new MatsimNetworkReader(referenceScenario.getNetwork()).readFile(config.network().getInputFile()); new PopulationReader(referenceScenario).readFile(inPlansName); - + final boolean isEqual = PopulationUtils.equalPopulation(referenceScenario.getPopulation(), scenario.getPopulation()); if ( !isEqual ) { new PopulationWriter(referenceScenario.getPopulation(), scenario.getNetwork()).write(this.utils.getOutputDirectory() + "/reference_population.xml.gz"); @@ -223,7 +173,7 @@ private static void calcRoute( final FreespeedTravelTimeAndDisutility calculator = new FreespeedTravelTimeAndDisutility( - scenario.getConfig().planCalcScore() ); + scenario.getConfig().scoring() ); final LeastCostPathCalculatorFactory factory1 = provider.getFactory( scenario.getNetwork(), calculator, @@ -251,9 +201,9 @@ public TravelDisutility createTravelDisutility(TravelTime timeCalculator) { final TripRouter tripRouter = injector.getInstance(TripRouter.class); final PersonAlgorithm router = new PlanRouter(tripRouter, injector.getInstance(TimeInterpretation.class)); - + for ( Person p : scenario.getPopulation().getPersons().values() ) { router.run(p); } } -} \ No newline at end of file +} diff --git a/matsim/src/test/java/org/matsim/core/router/TripRouterFactoryImplTest.java b/matsim/src/test/java/org/matsim/core/router/TripRouterFactoryImplTest.java index 43e9fb87900..25948e78d56 100644 --- a/matsim/src/test/java/org/matsim/core/router/TripRouterFactoryImplTest.java +++ b/matsim/src/test/java/org/matsim/core/router/TripRouterFactoryImplTest.java @@ -33,7 +33,7 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Injector; import org.matsim.core.population.PopulationUtils; @@ -44,7 +44,6 @@ import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.timing.TimeInterpretationModule; import org.matsim.facilities.Facility; -import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesImpl; import jakarta.inject.Provider; @@ -111,7 +110,7 @@ public void install() { public void install() { install(new ScenarioByInstanceModule(scenario)); install(new TimeInterpretationModule()); - addTravelTimeBinding("car").toInstance(new FreespeedTravelTimeAndDisutility( config.planCalcScore() )); + addTravelTimeBinding("car").toInstance(new FreespeedTravelTimeAndDisutility( config.scoring() )); addTravelDisutilityFactoryBinding("car").toInstance(new OnlyTimeDependentTravelDisutilityFactory()); } })); @@ -131,7 +130,7 @@ public void install() { PopulationUtils.getFactory().createPerson(Id.create("toto", Person.class)), new AttributesImpl()); Leg l = (Leg) trip.get( 0 ); - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { l = (Leg) trip.get(2) ; } @@ -190,7 +189,7 @@ public void install() { install(AbstractModule.override(Arrays.asList(new TripRouterModule()), new AbstractModule() { @Override public void install() { - addTravelTimeBinding("car").toInstance(new FreespeedTravelTimeAndDisutility( config.planCalcScore() )); + addTravelTimeBinding("car").toInstance(new FreespeedTravelTimeAndDisutility( config.scoring() )); addTravelDisutilityFactoryBinding("car").toInstance(new OnlyTimeDependentTravelDisutilityFactory()); } })); @@ -207,7 +206,7 @@ public void install() { PopulationUtils.getFactory().createPerson(Id.create("toto", Person.class)), new AttributesImpl()); Leg l = (Leg) trip.get( 0 ); - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { l = (Leg) trip.get(2) ; } diff --git a/matsim/src/test/java/org/matsim/core/router/TripRouterModuleTest.java b/matsim/src/test/java/org/matsim/core/router/TripRouterModuleTest.java index 0515a70156a..4bb4c1df8ed 100644 --- a/matsim/src/test/java/org/matsim/core/router/TripRouterModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/router/TripRouterModuleTest.java @@ -28,7 +28,7 @@ import org.matsim.api.core.v01.Scenario; 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.ControlerDefaults; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.LeastCostPathCalculatorFactory; @@ -43,9 +43,9 @@ public class TripRouterModuleTest { @Test public void testRouterCreation() { - for (ControlerConfigGroup.RoutingAlgorithmType routingAlgorithmType : ControlerConfigGroup.RoutingAlgorithmType.values()) { + for (ControllerConfigGroup.RoutingAlgorithmType routingAlgorithmType : ControllerConfigGroup.RoutingAlgorithmType.values()) { Config config = ConfigUtils.createConfig(); - config.controler().setRoutingAlgorithmType(routingAlgorithmType); + config.controller().setRoutingAlgorithmType(routingAlgorithmType); Scenario scenario = ScenarioUtils.createScenario(config); LeastCostPathCalculatorFactory defaultLeastCostPathCalculatorFactory = TripRouterFactoryBuilderWithDefaults.createDefaultLeastCostPathCalculatorFactory(scenario); LeastCostPathCalculator pathCalculator = defaultLeastCostPathCalculatorFactory.createPathCalculator( diff --git a/matsim/src/test/java/org/matsim/core/router/costcalculators/RandomizingTimeDistanceTravelDisutilityTest.java b/matsim/src/test/java/org/matsim/core/router/costcalculators/RandomizingTimeDistanceTravelDisutilityTest.java index cd4e2a72f30..1cee2106490 100644 --- a/matsim/src/test/java/org/matsim/core/router/costcalculators/RandomizingTimeDistanceTravelDisutilityTest.java +++ b/matsim/src/test/java/org/matsim/core/router/costcalculators/RandomizingTimeDistanceTravelDisutilityTest.java @@ -39,8 +39,8 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.router.DefaultRoutingRequest; @@ -58,46 +58,46 @@ public class RandomizingTimeDistanceTravelDisutilityTest { @Test public void testRoutesForDifferentSigmas() { - + { Set routes = new HashSet<>(); for (int i = 0; i<=5; i++) { NetworkRoute route = computeRoute(0.); - routes.add(route.getLinkIds().toString()); + routes.add(route.getLinkIds().toString()); } System.out.println("Route (sigma = 0.0): " + routes.toString()); Assert.assertEquals("There should only be a single route in the sigma = 0 case.", 1, routes.size()); } - + { Set routes = new HashSet<>(); for (int i = 0; i<=5; i++) { NetworkRoute route = computeRoute(3.); - routes.add(route.getLinkIds().toString()); + routes.add(route.getLinkIds().toString()); } System.out.println("Route (sigma = 3.0): " + routes.toString()); Assert.assertEquals("There should be two routes in the sigma = 3 case.", 2, routes.size()); } } - + public NetworkRoute computeRoute(double sigma) { Fixture f = new Fixture(); // PlanCalcScoreConfigGroup planCalcScoreCfg = new PlanCalcScoreConfigGroup(); Config config = ConfigUtils.createConfig(); - PlanCalcScoreConfigGroup planCalcScoreCfg = config.planCalcScore(); + ScoringConfigGroup planCalcScoreCfg = config.scoring(); ModeParams modeParams = new ModeParams(TransportMode.car); modeParams.setMonetaryDistanceRate(-0.1); planCalcScoreCfg.addModeParams(modeParams); - config.plansCalcRoute().setRoutingRandomness( sigma ); - + config.routing().setRoutingRandomness( sigma ); + RandomizingTimeDistanceTravelDisutilityFactory factory = new RandomizingTimeDistanceTravelDisutilityFactory(TransportMode.car, config); TravelTimeCalculator.Builder builder = new TravelTimeCalculator.Builder(f.s.getNetwork()); - TravelTimeCalculator calculator = builder.build(); - + TravelTimeCalculator calculator = builder.build(); + TravelTime travelTime = calculator.getLinkTravelTimes(); TravelDisutility disutility = factory.createTravelDisutility(travelTime); LeastCostPathCalculator router = TripRouterFactoryBuilderWithDefaults.createDefaultLeastCostPathCalculatorFactory(f.s).createPathCalculator(f.s.getNetwork(), disutility, travelTime); - + Person person = PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); Activity fromAct = PopulationUtils.createActivityFromCoord("h", new Coord(0, 0)); fromAct.setLinkId(Id.create("1", Link.class)); @@ -113,7 +113,7 @@ public NetworkRoute computeRoute(double sigma) { Facility toFacility = FacilitiesUtils.toFacility( toAct, f.s.getActivityFacilities() ); List result = routingModule.calcRoute(DefaultRoutingRequest.withoutAttributes(fromFacility, toFacility, 7.0*3600, person)) ; Assert.assertEquals(1, result.size() ); - Leg leg = (Leg) result.get(0) ; + Leg leg = (Leg) result.get(0) ; return (NetworkRoute) leg.getRoute(); } diff --git a/matsim/src/test/java/org/matsim/core/router/old/PlanRouterTest.java b/matsim/src/test/java/org/matsim/core/router/old/PlanRouterTest.java index 3437b92c3cd..511a141c8a2 100644 --- a/matsim/src/test/java/org/matsim/core/router/old/PlanRouterTest.java +++ b/matsim/src/test/java/org/matsim/core/router/old/PlanRouterTest.java @@ -32,7 +32,7 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Injector; import org.matsim.core.population.routes.NetworkRoute; @@ -69,7 +69,7 @@ public void install() { install(new TripRouterModule()); install(new ScenarioByInstanceModule(scenario)); install(new TimeInterpretationModule()); - addTravelTimeBinding("car").toInstance(new FreespeedTravelTimeAndDisutility(config.planCalcScore())); + addTravelTimeBinding("car").toInstance(new FreespeedTravelTimeAndDisutility(config.scoring())); addTravelDisutilityFactoryBinding("car").toInstance(new OnlyTimeDependentTravelDisutilityFactory()); } }); @@ -80,7 +80,7 @@ public void install() { ((NetworkRoute) TripStructureUtils.getLegs(plan).get(0).getRoute()).setVehicleId(vehicleId); testee.run(plan); - if ( config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { Assert.assertEquals("Vehicle Id transferred to new Plan", vehicleId, ((NetworkRoute) TripStructureUtils.getLegs(plan).get(0).getRoute()).getVehicleId()); } else { Assert.assertEquals("Vehicle Id transferred to new Plan", vehicleId, ((NetworkRoute) TripStructureUtils.getLegs(plan).get(1).getRoute()).getVehicleId()); @@ -110,7 +110,7 @@ public List calcRoute(RoutingRequest request) { final Facility toFacility = request.getToFacility(); final double departureTime = request.getDepartureTime(); final Person person = request.getPerson(); - + List trip = DefaultRoutingModules.createPureNetworkRouter("car", scenario.getPopulation().getFactory(), scenario.getNetwork(), leastCostAlgoFactory.createPathCalculator(scenario.getNetwork(), disutilityFactory.createTravelDisutility(travelTime), travelTime) @@ -127,7 +127,7 @@ public void install() { install(AbstractModule.override(Arrays.asList(new TripRouterModule()), new AbstractModule() { @Override public void install() { - addTravelTimeBinding("car").toInstance(new FreespeedTravelTimeAndDisutility(config.planCalcScore())); + addTravelTimeBinding("car").toInstance(new FreespeedTravelTimeAndDisutility(config.scoring())); addTravelDisutilityFactoryBinding("car").toInstance(new OnlyTimeDependentTravelDisutilityFactory()); addRoutingModuleBinding("car").toInstance( routingModule ); } @@ -138,7 +138,7 @@ public void install() { PlanRouter testee = new PlanRouter(tripRouter, TimeInterpretation.create(config)); testee.run(plan); - if ( config.plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( config.routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { Assert.assertEquals("Vehicle Id from TripRouter used", newVehicleId, ((NetworkRoute) TripStructureUtils.getLegs(plan).get(0).getRoute()).getVehicleId()); } else { Assert.assertEquals("Vehicle Id from TripRouter used", newVehicleId, ((NetworkRoute) TripStructureUtils.getLegs(plan).get(1).getRoute()).getVehicleId()); @@ -147,4 +147,4 @@ public void install() { } -} \ No newline at end of file +} diff --git a/matsim/src/test/java/org/matsim/core/router/speedy/SpeedyALTTest.java b/matsim/src/test/java/org/matsim/core/router/speedy/SpeedyALTTest.java index 5539c340c8f..959d902b321 100644 --- a/matsim/src/test/java/org/matsim/core/router/speedy/SpeedyALTTest.java +++ b/matsim/src/test/java/org/matsim/core/router/speedy/SpeedyALTTest.java @@ -21,7 +21,7 @@ package org.matsim.core.router.speedy; import org.matsim.api.core.v01.network.Network; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.AbstractLeastCostPathCalculatorTest; import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; import org.matsim.core.router.util.LeastCostPathCalculator; @@ -33,7 +33,7 @@ public class SpeedyALTTest extends AbstractLeastCostPathCalculatorTest { @Override protected LeastCostPathCalculator getLeastCostPathCalculator(final Network network) { - FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new PlanCalcScoreConfigGroup()); + FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new ScoringConfigGroup()); SpeedyGraph g = new SpeedyGraph(network); SpeedyALTData altData = new SpeedyALTData(g, 16, travelTimeCostCalculator); return new SpeedyALT(altData, travelTimeCostCalculator, travelTimeCostCalculator); diff --git a/matsim/src/test/java/org/matsim/core/router/speedy/SpeedyDijkstraTest.java b/matsim/src/test/java/org/matsim/core/router/speedy/SpeedyDijkstraTest.java index 5e389c1c2e0..a27c16c2ec9 100644 --- a/matsim/src/test/java/org/matsim/core/router/speedy/SpeedyDijkstraTest.java +++ b/matsim/src/test/java/org/matsim/core/router/speedy/SpeedyDijkstraTest.java @@ -21,7 +21,7 @@ package org.matsim.core.router.speedy; import org.matsim.api.core.v01.network.Network; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.router.AbstractLeastCostPathCalculatorTest; import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; import org.matsim.core.router.util.LeastCostPathCalculator; @@ -33,7 +33,7 @@ public class SpeedyDijkstraTest extends AbstractLeastCostPathCalculatorTest { @Override protected LeastCostPathCalculator getLeastCostPathCalculator(final Network network) { - FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new PlanCalcScoreConfigGroup()); + FreespeedTravelTimeAndDisutility travelTimeCostCalculator = new FreespeedTravelTimeAndDisutility(new ScoringConfigGroup()); SpeedyGraph g = new SpeedyGraph(network); return new SpeedyDijkstra(g, travelTimeCostCalculator, travelTimeCostCalculator); } diff --git a/matsim/src/test/java/org/matsim/core/scenario/ScenarioLoaderImplTest.java b/matsim/src/test/java/org/matsim/core/scenario/ScenarioLoaderImplTest.java index 5004d9aa606..ed651429022 100644 --- a/matsim/src/test/java/org/matsim/core/scenario/ScenarioLoaderImplTest.java +++ b/matsim/src/test/java/org/matsim/core/scenario/ScenarioLoaderImplTest.java @@ -97,33 +97,6 @@ public void testLoadScenario_loadPersonAttributes() { Assert.assertTrue( caughtException ); } - @Test - public void testLoadScenario_loadTransitLinesAttributes() { - Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(this.util.classInputResourcePath(), "transitConfig.xml")); - config.transit().setTransitLinesAttributesFile("transitLinesAttributes.xml"); - config.transit().setInsistingOnUsingDeprecatedAttributeFiles(true); - Scenario scenario = ScenarioUtils.loadScenario(config); - Assert.assertEquals( - "unexpected attribute value", - "world", - TransitScheduleUtils.getLineAttribute( - scenario.getTransitSchedule().getTransitLines().get(Id.create("Blue Line", TransitLine.class)), - "hello")); - } - - @Test - public void testLoadScenario_loadTransitStopsAttributes() { - Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(this.util.classInputResourcePath(), "transitConfig.xml")); - config.transit().setTransitStopsAttributesFile("transitStopsAttributes.xml"); - config.transit().setInsistingOnUsingDeprecatedAttributeFiles(true); - Scenario scenario = ScenarioUtils.loadScenario(config); - Assert.assertEquals( - "unexpected attribute value", - Boolean.TRUE, - TransitScheduleUtils.getStopFacilityAttribute( - scenario.getTransitSchedule().getFacilities().get(Id.create(1, TransitStopFacility.class)), - "hasP+R")); - } @Test public void testLoadScenario_loadFacilitiesAttributes() { diff --git a/matsim/src/test/java/org/matsim/core/scoring/EventsToScoreTest.java b/matsim/src/test/java/org/matsim/core/scoring/EventsToScoreTest.java index 4cdae60bc9a..48fabecebed 100644 --- a/matsim/src/test/java/org/matsim/core/scoring/EventsToScoreTest.java +++ b/matsim/src/test/java/org/matsim/core/scoring/EventsToScoreTest.java @@ -70,12 +70,12 @@ public class EventsToScoreTest { @Test public void testMsaAveraging() { Config config = ConfigUtils.createConfig() ; - config.controler().setFirstIteration(10); - config.controler().setLastIteration(110); + config.controller().setFirstIteration(10); + config.controller().setLastIteration(110); - config.planCalcScore().setMarginalUtilityOfMoney(1.); + config.scoring().setMarginalUtilityOfMoney(1.); - config.planCalcScore().setFractionOfIterationsToStartScoreMSA(0.9); + config.scoring().setFractionOfIterationsToStartScoreMSA(0.9); Scenario scenario = ScenarioUtils.createScenario(config); Population population = scenario.getPopulation(); @@ -88,7 +88,7 @@ public class EventsToScoreTest { EventsManager events = EventsUtils.createEventsManager(); EventsToScore e2s = EventsToScore.createWithScoreUpdating(scenario, sfFactory, events); - for ( int mockIteration = config.controler().getFirstIteration() ; mockIteration <= config.controler().getLastIteration() ; mockIteration++ ) { + for (int mockIteration = config.controller().getFirstIteration(); mockIteration <= config.controller().getLastIteration() ; mockIteration++ ) { e2s.beginIteration(mockIteration, false); ; events.initProcessing(); diff --git a/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationStressIT.java b/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationStressIT.java index 4da0fd39424..30f51ac024c 100644 --- a/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationStressIT.java +++ b/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationStressIT.java @@ -36,7 +36,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.ControlerListenerManagerImpl; import org.matsim.core.events.EventsUtils; import org.matsim.core.gbl.MatsimRandom; @@ -95,12 +95,12 @@ public void handleLeg(Leg leg) { public void agentStuck(double time) { throw new RuntimeException(); } - + @Override public void handleTrip( final TripStructureUtils.Trip trip ) { throw new RuntimeException(); } - + @Override public void addMoney(double amount) { throw new RuntimeException(); @@ -132,26 +132,26 @@ public void handleEvent(Event event) { @Test public void workWithNewEventsManager() { Config config = ConfigUtils.createConfig(); - config.parallelEventHandling().setOneThreadPerHandler(true); + config.eventsManager().setOneThreadPerHandler(true); work(config); } @Test public void workWithOldEventsManager() { Config config = ConfigUtils.createConfig(); - config.parallelEventHandling().setNumberOfThreads(8); + config.eventsManager().setNumberOfThreads(8); work(config); } private void work(Config config) { - PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setTypicalDuration(100.0); - config.planCalcScore().addActivityParams(work); - PlanCalcScoreConfigGroup.ModeParams car = new PlanCalcScoreConfigGroup.ModeParams("car"); + config.scoring().addActivityParams(work); + ScoringConfigGroup.ModeParams car = new ScoringConfigGroup.ModeParams("car"); car.setMarginalUtilityOfTraveling(0.0); car.setMarginalUtilityOfDistance(0.0); car.setConstant(-1.0); - config.planCalcScore().addModeParams(car); + config.scoring().addModeParams(car); final Scenario scenario = ScenarioUtils.createScenario(config); Id personId = Id.createPersonId(1); scenario.getPopulation().addPerson(scenario.getPopulation().getFactory().createPerson(personId)); @@ -177,12 +177,12 @@ public void handleLeg(Leg leg) { public void agentStuck(double time) { delegateFunction.agentStuck(time); } - + @Override public void handleTrip( final TripStructureUtils.Trip trip ) { delegateFunction.handleTrip(trip); } - + @Override public void addMoney(double amount) { delegateFunction.addMoney(amount); @@ -233,10 +233,10 @@ public void handleEvent(Event event) { } events.finishProcessing(); scoringFunctionsForPopulation.finishScoringFunctions(); - + //assert when TypicalDurationScoreComputation.uniform // assertEquals(60.0 * MAX, scoringFunctionsForPopulation.getScoringFunctionForAgent(personId).getScore(), 1.0); - + //assert when TypicalDurationScoreComputation.relative assertEquals(1.0/6.0 * MAX, scoringFunctionsForPopulation.getScoringFunctionForAgent(personId).getScore(), 1.0); } @@ -251,17 +251,17 @@ so this tests actually tests some additional (and potentially optional) behavior @Test @Ignore public void unlikelyTimingOfScoringFunctionStillWorks() { Config config = ConfigUtils.createConfig(); - config.parallelEventHandling().setNumberOfThreads(8); - config.parallelEventHandling().setOneThreadPerHandler(true); - config.parallelEventHandling().setSynchronizeOnSimSteps(false); - PlanCalcScoreConfigGroup.ActivityParams work = new PlanCalcScoreConfigGroup.ActivityParams("work"); + config.eventsManager().setNumberOfThreads(8); + config.eventsManager().setOneThreadPerHandler(true); + config.eventsManager().setSynchronizeOnSimSteps(false); + ScoringConfigGroup.ActivityParams work = new ScoringConfigGroup.ActivityParams("work"); work.setTypicalDuration(100.0); - config.planCalcScore().addActivityParams(work); - PlanCalcScoreConfigGroup.ModeParams car = new PlanCalcScoreConfigGroup.ModeParams("car"); + config.scoring().addActivityParams(work); + ScoringConfigGroup.ModeParams car = new ScoringConfigGroup.ModeParams("car"); car.setMarginalUtilityOfTraveling(0.0); car.setMarginalUtilityOfDistance(0.0); car.setConstant(-1.0); - config.planCalcScore().addModeParams(car); + config.scoring().addModeParams(car); final Scenario scenario = ScenarioUtils.createScenario(config); Id personId = Id.createPersonId(1); scenario.getPopulation().addPerson(scenario.getPopulation().getFactory().createPerson(personId)); @@ -302,7 +302,7 @@ public void agentStuck(double time) { } delegateFunction.agentStuck(time); } - + @Override public void handleTrip( final TripStructureUtils.Trip trip ) { try { @@ -312,7 +312,7 @@ public void handleTrip( final TripStructureUtils.Trip trip ) { } delegateFunction.handleTrip(trip); } - + @Override public void addMoney(double amount) { try { @@ -382,10 +382,10 @@ public void handleEvent(Event event) { } events.finishProcessing(); scoringFunctionsForPopulation.finishScoringFunctions(); - + //assert when TypicalDurationScoreComputation.uniform // assertEquals(60.0 * MAX, scoringFunctionsForPopulation.getScoringFunctionForAgent(personId).getScore(), 1.0); - + //assert when TypicalDurationScoreComputation.relative assertEquals(1.0/6.0 * MAX, scoringFunctionsForPopulation.getScoringFunctionForAgent(personId).getScore(), 1.0); } diff --git a/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelLegScoringDailyConstantsTest.java b/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelLegScoringDailyConstantsTest.java index 19ab9c2e7a7..5b143bd9623 100644 --- a/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelLegScoringDailyConstantsTest.java +++ b/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelLegScoringDailyConstantsTest.java @@ -36,7 +36,7 @@ import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; 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.ScenarioConfigGroup; import org.matsim.core.population.PopulationUtils; import org.matsim.core.scenario.ScenarioUtils; @@ -94,11 +94,11 @@ public void test1() throws Exception { scoring1.handleLeg(leg); scoring1.finish(); - + scoring2.handleLeg(leg); scoring2.finish(); } - + { final Leg leg = PopulationUtils.createLeg(TransportMode.car); leg.setDepartureTime( 0 ); @@ -131,11 +131,11 @@ public void test1() throws Exception { scoring1.handleLeg(leg); scoring1.finish(); - + scoring2.handleLeg(leg); scoring2.finish(); } - + { final Leg leg = PopulationUtils.createLeg(TransportMode.bike); leg.setDepartureTime( 0 ); @@ -168,7 +168,7 @@ public void test1() throws Exception { scoring1.handleLeg(leg); scoring1.finish(); - + scoring2.handleLeg(leg); scoring2.finish(); } @@ -178,9 +178,9 @@ public void test1() throws Exception { -12345.678, scoring1.getScore(), MatsimTestUtils.EPSILON ); - - double defaultScore = (legTravelTime1 + legTravelTime2) * new PlanCalcScoreConfigGroup().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() / 3600. - + legTravelTime3 * new PlanCalcScoreConfigGroup().getModes().get(TransportMode.bike).getMarginalUtilityOfTraveling() / 3600.; + + double defaultScore = (legTravelTime1 + legTravelTime2) * new ScoringConfigGroup().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling() / 3600. + + legTravelTime3 * new ScoringConfigGroup().getModes().get(TransportMode.bike).getMarginalUtilityOfTraveling() / 3600.; Assert.assertEquals( "wrong score; daily constants are not accounted for in the scoring.", -12345.678 + defaultScore, @@ -189,15 +189,15 @@ public void test1() throws Exception { } private CharyparNagelLegScoring createDefaultPlusConstants(Network network) { - - final PlanCalcScoreConfigGroup conf = new PlanCalcScoreConfigGroup(); - + + final ScoringConfigGroup conf = new ScoringConfigGroup(); + conf.getModes().get(TransportMode.car).setDailyUtilityConstant(-10000.); conf.getModes().get(TransportMode.car).setDailyMonetaryConstant(-2345.); conf.getModes().get(TransportMode.bike).setDailyUtilityConstant(-.078); conf.getModes().get(TransportMode.bike).setDailyMonetaryConstant(-0.6); - + final ScenarioConfigGroup scenarioConfig = new ScenarioConfigGroup(); return new CharyparNagelLegScoring( @@ -207,12 +207,12 @@ private CharyparNagelLegScoring createDefaultPlusConstants(Network network) { private static CharyparNagelLegScoring createScoringOnlyConstants(final Network network) { - final PlanCalcScoreConfigGroup conf = new PlanCalcScoreConfigGroup(); - + final ScoringConfigGroup conf = new ScoringConfigGroup(); + conf.getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(0.); conf.getModes().get(TransportMode.car).setDailyUtilityConstant(-10000.); conf.getModes().get(TransportMode.car).setDailyMonetaryConstant(-2345.); - + conf.getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(0.); conf.getModes().get(TransportMode.bike).setDailyUtilityConstant(-.078); conf.getModes().get(TransportMode.bike).setDailyMonetaryConstant(-0.6); diff --git a/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelLegScoringPtChangeTest.java b/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelLegScoringPtChangeTest.java index 870a563370d..6271fd0934c 100644 --- a/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelLegScoringPtChangeTest.java +++ b/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelLegScoringPtChangeTest.java @@ -39,7 +39,7 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.core.api.experimental.events.EventsManager; 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.ScenarioConfigGroup; import org.matsim.core.events.EventsUtils; import org.matsim.core.population.PopulationUtils; @@ -117,7 +117,7 @@ private static CharyparNagelLegScoring createScoring( final Network network) { final Random random = new Random( seed ); - final PlanCalcScoreConfigGroup conf = new PlanCalcScoreConfigGroup(); + final ScoringConfigGroup conf = new ScoringConfigGroup(); conf.setMarginalUtlOfWaitingPt_utils_hr( random.nextDouble() * 1000 ); conf.getModes().get(TransportMode.pt).setMonetaryDistanceRate(random.nextDouble() * 1000); conf.getModes().get(TransportMode.pt).setMarginalUtilityOfTraveling(random.nextDouble() * 1000); diff --git a/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelScoringFunctionTest.java b/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelScoringFunctionTest.java index a9640ce12b6..53358733184 100644 --- a/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelScoringFunctionTest.java +++ b/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelScoringFunctionTest.java @@ -46,9 +46,9 @@ import org.matsim.api.core.v01.population.Route; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.TypicalDurationScoreComputation; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.TypicalDurationScoreComputation; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; @@ -77,16 +77,16 @@ public class CharyparNagelScoringFunctionTest { private static final double EPSILON =1e-9; - + @Parameter public TypicalDurationScoreComputation typicalDurationComputation; - + @Parameterized.Parameters public static Object[] testParameters() { return new Object[] {TypicalDurationScoreComputation.relative,TypicalDurationScoreComputation.uniform}; } - - + + private ScoringFunction getScoringFunctionInstance(final Fixture f, final Person person) { CharyparNagelScoringFunctionFactory charyparNagelScoringFunctionFactory = new CharyparNagelScoringFunctionFactory( f.scenario ); @@ -102,9 +102,9 @@ private double calcScore(final Fixture f) { if (planElement instanceof Activity) { testee.handleActivity((Activity) planElement); } else if (planElement instanceof Leg) { - testee.handleLeg((Leg) planElement); + testee.handleLeg((Leg) planElement); } - } + } testee.finish(); return testee.getScore(); } @@ -119,7 +119,7 @@ private double calcScore(final Fixture f) { */ private double getZeroUtilDuration_hrs(final double typicalDuration_hrs, final double priority) { // yy could/should use static function from CharyparNagelScoringUtils. kai, nov'13 - + if(typicalDurationComputation.equals(TypicalDurationScoreComputation.uniform)){ return typicalDuration_hrs * Math.exp(-10.0 / typicalDuration_hrs / priority); } else { @@ -138,18 +138,18 @@ public void testZeroUtilityDuration() { ZeroUtilityComputation computation; if(this.typicalDurationComputation.equals(TypicalDurationScoreComputation.uniform)){ - computation = new ActivityUtilityParameters.SameAbsoluteScore(); + computation = new ActivityUtilityParameters.SameAbsoluteScore(); } else { computation = new ActivityUtilityParameters.SameRelativeScore(); } - - + + { ActivityUtilityParameters.Builder factory = new ActivityUtilityParameters.Builder(); factory.setType("w"); factory.setPriority(1.0); factory.setTypicalDuration_s(8.0 * 3600); - factory.setZeroUtilityComputation(computation); + factory.setZeroUtilityComputation(computation); ActivityUtilityParameters params = factory.build(); assertEquals(zeroUtilDurW, params.getZeroUtilityDuration_h(), EPSILON); @@ -190,10 +190,10 @@ public void testZero() { public void testTravelingAndConstantCar() { Fixture f = new Fixture(); final double traveling = -6.0; - f.config.planCalcScore().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(traveling); + f.config.scoring().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(traveling); assertEquals(-3.0, calcScore(f), EPSILON); double constantCar = -6.0; - f.config.planCalcScore().getModes().get(TransportMode.car).setConstant(constantCar); + f.config.scoring().getModes().get(TransportMode.car).setConstant(constantCar); assertEquals(-9.0, calcScore(f), EPSILON); } @@ -201,10 +201,10 @@ public void testTravelingAndConstantCar() { public void testTravelingPtAndConstantPt() { Fixture f = new Fixture(); final double travelingPt = -9.0; - f.config.planCalcScore().getModes().get(TransportMode.pt).setMarginalUtilityOfTraveling(travelingPt); + f.config.scoring().getModes().get(TransportMode.pt).setMarginalUtilityOfTraveling(travelingPt); assertEquals(-2.25, calcScore(f), EPSILON); double constantPt = -3.0; - f.config.planCalcScore().getModes().get(TransportMode.pt).setConstant(constantPt); + f.config.scoring().getModes().get(TransportMode.pt).setConstant(constantPt); assertEquals(-5.25, calcScore(f), EPSILON); } @@ -212,10 +212,10 @@ public void testTravelingPtAndConstantPt() { public void testTravelingWalkAndConstantWalk() { Fixture f = new Fixture(); final double travelingWalk = -18.0; - f.config.planCalcScore().getModes().get(TransportMode.walk).setMarginalUtilityOfTraveling(travelingWalk); + f.config.scoring().getModes().get(TransportMode.walk).setMarginalUtilityOfTraveling(travelingWalk); assertEquals(-9.0, calcScore(f), EPSILON ) ; double constantWalk = -1.0; - f.config.planCalcScore().getModes().get(TransportMode.walk).setConstant(constantWalk); + f.config.scoring().getModes().get(TransportMode.walk).setConstant(constantWalk); assertEquals(-10.0, calcScore(f), EPSILON); } @@ -223,10 +223,10 @@ public void testTravelingWalkAndConstantWalk() { public void testTravelingBikeAndConstantBike(){ Fixture f = new Fixture(); final double travelingBike = -6.0; - f.config.planCalcScore().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(travelingBike); + f.config.scoring().getModes().get(TransportMode.bike).setMarginalUtilityOfTraveling(travelingBike); assertEquals(-1.5, calcScore(f), EPSILON ) ; double constantBike = -2.0; - f.config.planCalcScore().getModes().get(TransportMode.bike).setConstant(constantBike); + f.config.scoring().getModes().get(TransportMode.bike).setConstant(constantBike); assertEquals(-3.5, calcScore(f), EPSILON); } @@ -241,14 +241,14 @@ public void testPerforming() { double zeroUtilDurW = getZeroUtilDuration_hrs(3.0, 1.0); double zeroUtilDurH = getZeroUtilDuration_hrs(15.0, 1.0); - f.config.planCalcScore().setPerforming_utils_hr(perf); - + f.config.scoring().setPerforming_utils_hr(perf); + if(typicalDurationComputation.equals(TypicalDurationScoreComputation.uniform)){ - for(ActivityParams p : f.config.planCalcScore().getActivityParams()){ + for(ActivityParams p : f.config.scoring().getActivityParams()){ p.setTypicalDurationScoreComputation(TypicalDurationScoreComputation.uniform); } - } - + } + assertEquals(perf * 3.0 * Math.log(2.5 / zeroUtilDurW) + perf * 3.0 * Math.log(2.75/zeroUtilDurW) + perf * 3.0 * Math.log(2.5/zeroUtilDurW) @@ -269,10 +269,10 @@ public void testPerforming() { public void testOpeningTime() { Fixture f = new Fixture(); double perf = +6.0; - f.config.planCalcScore().setPerforming_utils_hr(perf); + f.config.scoring().setPerforming_utils_hr(perf); double initialScore = calcScore(f); - ActivityParams wParams = f.config.planCalcScore().getActivityParams("w"); + ActivityParams wParams = f.config.scoring().getActivityParams("w"); wParams.setOpeningTime(8*3600.0); // now the agent arrives 30min early to the FIRST work activity and has to wait double score = calcScore(f); @@ -287,10 +287,10 @@ public void testOpeningTime() { public void testClosingTime() { Fixture f = new Fixture(); double perf = +6.0; - f.config.planCalcScore().setPerforming_utils_hr(perf); + f.config.scoring().setPerforming_utils_hr(perf); double initialScore = calcScore(f); - ActivityParams wParams = f.config.planCalcScore().getActivityParams("w"); + ActivityParams wParams = f.config.scoring().getActivityParams("w"); wParams.setClosingTime(15*3600.0); // now the agent stays 1h too long at the LAST work activity double score = calcScore(f); @@ -305,19 +305,19 @@ public void testClosingTime() { public void testOpeningClosingTime() { Fixture f = new Fixture(); double perf_hrs = +6.0; - f.config.planCalcScore().setPerforming_utils_hr(perf_hrs); - + f.config.scoring().setPerforming_utils_hr(perf_hrs); + if(typicalDurationComputation.equals(TypicalDurationScoreComputation.uniform)){ - for(ActivityParams p : f.config.planCalcScore().getActivityParams()){ + for(ActivityParams p : f.config.scoring().getActivityParams()){ p.setTypicalDurationScoreComputation(TypicalDurationScoreComputation.uniform); } - } - + } + double initialScore = calcScore(f); // test1: agents has to wait before and after - ActivityParams wParams = f.config.planCalcScore().getActivityParams("w"); + ActivityParams wParams = f.config.scoring().getActivityParams("w"); wParams.setOpeningTime( 8*3600.0); // the agent arrives 30min early wParams.setClosingTime(15*3600.0); // the agent stays 1h too long double score = calcScore(f); @@ -369,9 +369,9 @@ public void testOpeningClosingTime() { public void testWaitingTime() { Fixture f = new Fixture(); double waiting = -10.0; - f.config.planCalcScore().setMarginalUtlOfWaiting_utils_hr(waiting); + f.config.scoring().setMarginalUtlOfWaiting_utils_hr(waiting); - ActivityParams wParams = f.config.planCalcScore().getActivityParams("w"); + ActivityParams wParams = f.config.scoring().getActivityParams("w"); wParams.setOpeningTime( 8*3600.0); // the agent arrives 30min early wParams.setClosingTime(15*3600.0); // the agent stays 1h too long @@ -386,9 +386,9 @@ public void testWaitingTime() { public void testEarlyDeparture() { Fixture f = new Fixture(); double disutility = -10.0; - f.config.planCalcScore().setEarlyDeparture_utils_hr(disutility); + f.config.scoring().setEarlyDeparture_utils_hr(disutility); - ActivityParams wParams = f.config.planCalcScore().getActivityParams("w"); + ActivityParams wParams = f.config.scoring().getActivityParams("w"); wParams.setEarliestEndTime(10.75 * 3600.0); // require the agent to work until 16:45 // the agent left 45mins too early @@ -402,9 +402,9 @@ public void testEarlyDeparture() { public void testMinimumDuration() { Fixture f = new Fixture(); double disutility = -10.0; - f.config.planCalcScore().setEarlyDeparture_utils_hr(disutility); + f.config.scoring().setEarlyDeparture_utils_hr(disutility); - ActivityParams wParams = f.config.planCalcScore().getActivityParams("w"); + ActivityParams wParams = f.config.scoring().getActivityParams("w"); wParams.setMinimalDuration(3 * 3600.0); // require the agent to be 3 hours at every working activity // the agent overall works 1.25h too short @@ -418,9 +418,9 @@ public void testMinimumDuration() { public void testLateArrival() { Fixture f = new Fixture(); double disutility = -10.0; - f.config.planCalcScore().setLateArrival_utils_hr(disutility); + f.config.scoring().setLateArrival_utils_hr(disutility); - ActivityParams wParams = f.config.planCalcScore().getActivityParams("w"); + ActivityParams wParams = f.config.scoring().getActivityParams("w"); wParams.setLatestStartTime(13 * 3600.0); // agent should start working latest at 13 o'clock // the agent arrived 30mins late @@ -435,9 +435,9 @@ public void testLateArrival() { public void testStuckPenalty() { Fixture f = new Fixture(); // test 1 where late arrival has the biggest impact - f.config.planCalcScore().setLateArrival_utils_hr(-18.0); + f.config.scoring().setLateArrival_utils_hr(-18.0); final double traveling1 = -6.0; - f.config.planCalcScore().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(traveling1); + f.config.scoring().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(traveling1); ScoringFunction testee = getScoringFunctionInstance(f, f.person); testee.handleActivity((Activity) f.plan.getPlanElements().get(0)); @@ -452,9 +452,9 @@ public void testStuckPenalty() { assertEquals(24 * -18.0 - 6.0 * 0.50, testee.getScore(), EPSILON); // stuck penalty + 30min traveling // test 2 where traveling has the biggest impact - f.config.planCalcScore().setLateArrival_utils_hr(-3.0); + f.config.scoring().setLateArrival_utils_hr(-3.0); final double traveling = -6.0; - f.config.planCalcScore().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(traveling); + f.config.scoring().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(traveling); testee = getScoringFunctionInstance(f, f.person); testee.handleActivity((Activity) f.plan.getPlanElements().get(0)); @@ -472,17 +472,17 @@ public void testStuckPenalty() { public void testDistanceCostScoringCar() { Fixture f = new Fixture(); // test 1 where marginalUtitityOfMoney is fixed to 1.0 - f.config.planCalcScore().setMarginalUtilityOfMoney(1.0); + f.config.scoring().setMarginalUtilityOfMoney(1.0); // this.config.charyparNagelScoring().setMarginalUtlOfDistanceCar(-0.00001); double monetaryDistanceRateCar1 = -0.00001; - f.config.planCalcScore().getModes().get(TransportMode.car).setMonetaryDistanceRate(monetaryDistanceRateCar1); + f.config.scoring().getModes().get(TransportMode.car).setMonetaryDistanceRate(monetaryDistanceRateCar1); assertEquals(-0.25, calcScore(f), EPSILON); // test 2 where MonetaryDistanceCostRate is fixed to -1.0 double monetaryDistanceRateCar = -1.0; - f.config.planCalcScore().getModes().get(TransportMode.car).setMonetaryDistanceRate(monetaryDistanceRateCar); - f.config.planCalcScore().setMarginalUtilityOfMoney(0.5); + f.config.scoring().getModes().get(TransportMode.car).setMonetaryDistanceRate(monetaryDistanceRateCar); + f.config.scoring().setMarginalUtilityOfMoney(0.5); assertEquals(-12500.0, calcScore(f), EPSILON); } @@ -491,17 +491,17 @@ public void testDistanceCostScoringCar() { public void testDistanceCostScoringPt() { Fixture f = new Fixture(); // test 1 where marginalUtitityOfMoney is fixed to 1.0 - f.config.planCalcScore().setMarginalUtilityOfMoney(1.0); + f.config.scoring().setMarginalUtilityOfMoney(1.0); // this.config.charyparNagelScoring().setMarginalUtlOfDistancePt(-0.00001); double monetaryDistanceRatePt1 = -0.00001; - f.config.planCalcScore().getModes().get(TransportMode.pt).setMonetaryDistanceRate(monetaryDistanceRatePt1); + f.config.scoring().getModes().get(TransportMode.pt).setMonetaryDistanceRate(monetaryDistanceRatePt1); assertEquals(-0.20, calcScore(f), EPSILON); // test 2 where MonetaryDistanceCostRate is fixed to -1.0 double monetaryDistanceRatePt = -1.0; - f.config.planCalcScore().getModes().get(TransportMode.pt).setMonetaryDistanceRate(monetaryDistanceRatePt); - f.config.planCalcScore().setMarginalUtilityOfMoney(0.5); + f.config.scoring().getModes().get(TransportMode.pt).setMonetaryDistanceRate(monetaryDistanceRatePt); + f.config.scoring().setMarginalUtilityOfMoney(0.5); assertEquals(-10000.0, calcScore(f), EPSILON); } @@ -515,20 +515,20 @@ public void testDifferentFirstLastAct() { // change the last act to something different than the first act ((Activity) f.plan.getPlanElements().get(8)).setType("h2"); - PlanCalcScoreConfigGroup.ActivityParams params = new PlanCalcScoreConfigGroup.ActivityParams("h2"); + ScoringConfigGroup.ActivityParams params = new ScoringConfigGroup.ActivityParams("h2"); params.setTypicalDuration(8*3600); - - f.config.planCalcScore().addActivityParams(params); - f.config.planCalcScore().getActivityParams("h").setTypicalDuration(6.0 * 3600); - + + f.config.scoring().addActivityParams(params); + f.config.scoring().getActivityParams("h").setTypicalDuration(6.0 * 3600); + if(typicalDurationComputation.equals(TypicalDurationScoreComputation.uniform)){ - for(ActivityParams p : f.config.planCalcScore().getActivityParams()){ + for(ActivityParams p : f.config.scoring().getActivityParams()){ p.setTypicalDurationScoreComputation(TypicalDurationScoreComputation.uniform); } - } - + } + double perf = +6.0; - f.config.planCalcScore().setPerforming_utils_hr(perf); + f.config.scoring().setPerforming_utils_hr(perf); double zeroUtilDurW = getZeroUtilDuration_hrs(3.0, 1.0); double zeroUtilDurH = getZeroUtilDuration_hrs(6.0, 1.0); double zeroUtilDurH2 = getZeroUtilDuration_hrs(8.0, 1.0); @@ -558,15 +558,15 @@ public void testNoNightActivity() { // this would amount to a smaller-than-zero expected contribution of // the home activity at 7 hours, and smaller-than-zero contributions // are truncated, so we wouldn't test anything. :-/ - f.config.planCalcScore().getActivityParams("h").setTypicalDuration(7.0 * 3600); - f.config.planCalcScore().setPerforming_utils_hr(perf); + f.config.scoring().getActivityParams("h").setTypicalDuration(7.0 * 3600); + f.config.scoring().setPerforming_utils_hr(perf); if(typicalDurationComputation.equals(TypicalDurationScoreComputation.uniform)){ - for(ActivityParams p : f.config.planCalcScore().getActivityParams()){ + for(ActivityParams p : f.config.scoring().getActivityParams()){ p.setTypicalDurationScoreComputation(TypicalDurationScoreComputation.uniform); } - } - + } + ScoringFunction testee = getScoringFunctionInstance(f, f.person); testee.handleActivity((Activity) f.plan.getPlanElements().get(0)); testee.handleLeg((Leg) f.plan.getPlanElements().get(1)); @@ -575,7 +575,7 @@ public void testNoNightActivity() { assertEquals( perf * 3.0 * Math.log(2.5 / zeroUtilDurW) + - perf * 7.0 * Math.log(7.0 / zeroUtilDurH), + perf * 7.0 * Math.log(7.0 / zeroUtilDurH), testee.getScore(), EPSILON); } @@ -681,7 +681,7 @@ public void testUnusualMode() { exception = true ; } assertTrue( exception ) ; - f.config.planCalcScore().addParam("traveling_sackhuepfen", "-30.0"); + f.config.scoring().addParam("traveling_sackhuepfen", "-30.0"); assertEquals(-15.0, calcScore(f), EPSILON); } @@ -717,7 +717,7 @@ public Fixture() { // home 15:15 to ... this.config = ConfigUtils.createConfig(); - PlanCalcScoreConfigGroup scoring = this.config.planCalcScore(); + ScoringConfigGroup scoring = this.config.scoring(); scoring.setBrainExpBeta(2.0); scoring.getModes().get(TransportMode.car).setConstant(0.0); @@ -740,12 +740,12 @@ public Fixture() { // setup activity types h and w for scoring - PlanCalcScoreConfigGroup.ActivityParams params = new PlanCalcScoreConfigGroup.ActivityParams("h"); + ScoringConfigGroup.ActivityParams params = new ScoringConfigGroup.ActivityParams("h"); params.setTypicalDuration(15*3600); scoring.addActivityParams(params); - params = new PlanCalcScoreConfigGroup.ActivityParams("w"); + params = new ScoringConfigGroup.ActivityParams("w"); params.setTypicalDuration(3*3600); scoring.addActivityParams(params); @@ -842,6 +842,6 @@ public Fixture() { Activity fifthActivity = PopulationUtils.createAndAddActivityFromLinkId(this.plan, "h", link9.getId()); fifthActivity.setStartTime(fourthLegStartTime + fourthLegTravelTime); this.scenario.getPopulation().addPerson(this.person); - } + } } } diff --git a/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelWithSubpopulationsTest.java b/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelWithSubpopulationsTest.java index 23b1cfa276a..80043ee95e8 100644 --- a/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelWithSubpopulationsTest.java +++ b/matsim/src/test/java/org/matsim/core/scoring/functions/CharyparNagelWithSubpopulationsTest.java @@ -28,16 +28,14 @@ import org.matsim.api.core.v01.population.Route; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ModeParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ScoringParameterSet; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; +import org.matsim.core.config.groups.ScoringConfigGroup.ScoringParameterSet; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.scoring.ScoringFunction; -import java.util.Random; - /** * @author thibautd */ @@ -121,7 +119,7 @@ private Scenario createTestScenario() { PopulationUtils.putPersonAttribute( person, "subpopulation", subpop ); final double util = (double) i; - final ScoringParameterSet params = config.planCalcScore().getOrCreateScoringParameters(subpop); + final ScoringParameterSet params = config.scoring().getOrCreateScoringParameters(subpop); params.setMarginalUtlOfWaitingPt_utils_hr(-util); params.setEarlyDeparture_utils_hr(-util); diff --git a/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorModuleTest.java b/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorModuleTest.java index d3e04c32937..7a1b22936cc 100644 --- a/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorModuleTest.java @@ -98,7 +98,7 @@ public void testOneTravelTimeCalculatorPerMode() { Config config = ConfigUtils.createConfig(); // config.travelTimeCalculator().setAnalyzedModesAsString("car,bike" ); - config.plansCalcRoute().setNetworkModes( new LinkedHashSet<>( Arrays.asList( TransportMode.car, TransportMode.bike ) ) ); + config.routing().setNetworkModes( new LinkedHashSet<>( Arrays.asList( TransportMode.car, TransportMode.bike ) ) ); // (this is now newly taken from the router network modes. kai, feb'19) config.travelTimeCalculator().setSeparateModes(true); diff --git a/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorTest.java b/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorTest.java index 17ec9fd0902..a7bc3c003af 100644 --- a/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorTest.java +++ b/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorTest.java @@ -87,7 +87,7 @@ public class TravelTimeCalculatorTest { MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario( ConfigUtils.createConfig() ); TimeSlotComputation travelTimeAggregator = new TimeSlotComputation( numSlots, binSize ); TravelTimeGetter travelTimeGetter = new AveragingTravelTimeGetter( travelTimeAggregator ) ; - doTravelTimeCalculatorTest(scenario, new TravelTimeDataArrayFactory(scenario.getNetwork(), numSlots), + doTravelTimeCalculatorTest(scenario, travelTimeAggregator, binSize, endTime, compareFile, false, utils.getClassInputDirectory(), travelTimeGetter ); } @@ -102,80 +102,11 @@ public class TravelTimeCalculatorTest { MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario( ConfigUtils.createConfig() ); TimeSlotComputation aggregator = new TimeSlotComputation( numSlots, binSize ); TravelTimeGetter travelTimeGetter = new LinearInterpolatingTravelTimeGetter( numSlots, binSize, aggregator ); - doTravelTimeCalculatorTest(scenario, new TravelTimeDataArrayFactory(scenario.getNetwork(), numSlots), + doTravelTimeCalculatorTest(scenario, aggregator, binSize, endTime, compareFile, false, utils.getClassInputDirectory(), travelTimeGetter ); } - @Test public final void testTravelTimeCalculator_HashMap_Optimistic() throws IOException { - - int endTime = 30*3600; - int binSize = 15*60; - int numSlots = (endTime / binSize) + 1; - - // by default: averaging travel times - String compareFile = utils.getClassInputDirectory() + "link10_ttimes.txt"; - MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario( ConfigUtils.createConfig() ); - TimeSlotComputation travelTimeAggregator = new TimeSlotComputation( numSlots, binSize ); - TravelTimeGetter travelTimeGetter = new AveragingTravelTimeGetter( travelTimeAggregator ) ; - doTravelTimeCalculatorTest(scenario, new TravelTimeDataHashMapFactory(scenario.getNetwork()), - travelTimeAggregator, binSize, endTime, compareFile, false, utils.getClassInputDirectory(), travelTimeGetter ); - } - - @Test public final void testTravelTimeCalculator_HashMap_Optimistic_LinearInterpolation() throws IOException { - String compareFile; - MutableScenario scenario; - TimeSlotComputation aggregator; - - int endTime = 30*3600; - int binSize = 15*60; - int numSlots = (endTime / binSize) + 1; - - // use linear interpolation - compareFile = utils.getClassInputDirectory() + "link10_ttimes_linearinterpolation.txt"; - scenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); - aggregator = new TimeSlotComputation(numSlots, binSize); - TravelTimeGetter travelTimeGetter = new LinearInterpolatingTravelTimeGetter( numSlots, binSize, aggregator ); - doTravelTimeCalculatorTest(scenario, new TravelTimeDataHashMapFactory(scenario.getNetwork()), - aggregator, binSize, endTime, compareFile, false, utils.getClassInputDirectory(), travelTimeGetter ); - } - -// @Test public final void testTravelTimeCalculator_HashMap_Pessimistic() throws IOException { -// String compareFile; -// MutableScenario scenario; -// TravelTimeAggregator aggregator; -// -// int endTime = 12*3600; -// int binSize = 1*60; -// int numSlots = (endTime / binSize) + 1; -// -// // by default: averaging travel times -// compareFile = getClassInputDirectory() + "link10_ttimes_pessimistic.txt"; -// scenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); -// aggregator = new PessimisticTravelTimeAggregator(binSize, numSlots); -// assertEquals(AveragingTravelTimeGetter.class, aggregator.getTravelTimeGetter().getClass()); -// doTravelTimeCalculatorTest(scenario, new TravelTimeDataHashMapFactory(scenario.getNetwork()), -// aggregator, binSize, endTime, compareFile, false); -// } -// -// @Test public final void testTravelTimeCalculator_HashMap_Pessimistic_LinearInterpolation() throws IOException { -// String compareFile; -// MutableScenario scenario; -// TravelTimeAggregator aggregator; -// -// int endTime = 12*3600; -// int binSize = 1*60; -// int numSlots = (endTime / binSize) + 1; -// -// // use linear interpolation -// compareFile = getClassInputDirectory() + "link10_ttimes_pessimistic_linearinterpolation.txt"; -// scenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); -// aggregator = new PessimisticTravelTimeAggregator(binSize, numSlots); -// aggregator.connectTravelTimeGetter(new LinearInterpolatingTravelTimeGetter(numSlots, binSize)); -// doTravelTimeCalculatorTest(scenario, new TravelTimeDataHashMapFactory(scenario.getNetwork()), -// aggregator, binSize, endTime, compareFile, false); -// } - - private static void doTravelTimeCalculatorTest( final MutableScenario scenario, final TravelTimeDataFactory ttDataFactory, + private static void doTravelTimeCalculatorTest( final MutableScenario scenario, final TimeSlotComputation aggregator, final int timeBinSize, final int endTime, final String compareFile, final boolean generateNewData, String inputDirectory, TravelTimeGetter travelTimeGetter ) throws IOException { @@ -195,9 +126,8 @@ private static void doTravelTimeCalculatorTest( final MutableScenario scenario, EventsManager events2 = EventsUtils.createEventsManager(); TravelTimeCalculator ttcalc = new TravelTimeCalculator(network, timeBinSize, endTime, scenario.getConfig().travelTimeCalculator()); - ttcalc.travelTimeGetter = travelTimeGetter ; - ttcalc.aggregator = aggregator ; - ttcalc.setTtDataFactory( ttDataFactory ); + ttcalc.travelTimeGetter = travelTimeGetter; + ttcalc.aggregator = aggregator; events2.addHandler(ttcalc); events2.initProcessing(); for (Event e : collector.getEvents()) { diff --git a/matsim/src/test/java/org/matsim/core/utils/io/MatsimFileTypeGuesserTest.java b/matsim/src/test/java/org/matsim/core/utils/io/MatsimFileTypeGuesserTest.java index 8e4b7df8ff7..34b26897bd8 100644 --- a/matsim/src/test/java/org/matsim/core/utils/io/MatsimFileTypeGuesserTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/io/MatsimFileTypeGuesserTest.java @@ -26,6 +26,7 @@ import static org.junit.Assert.fail; import java.io.IOException; +import java.io.UncheckedIOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/matsim/src/test/java/org/matsim/core/utils/io/MatsimXmlParserTest.java b/matsim/src/test/java/org/matsim/core/utils/io/MatsimXmlParserTest.java index 2c7a7025d54..d7006b7ce1d 100644 --- a/matsim/src/test/java/org/matsim/core/utils/io/MatsimXmlParserTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/io/MatsimXmlParserTest.java @@ -32,6 +32,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -207,7 +208,8 @@ public void endTag(String name, String content, Stack context) { }.parse(stream); Assert.fail("expected exception."); } catch (UncheckedIOException e) { - Assert.assertTrue(e.getCause() instanceof SAXParseException); // expected + Assert.assertTrue(e.getCause() instanceof IOException); // expected + Assert.assertTrue(e.getCause().getCause() instanceof SAXParseException); // expected } Assert.assertEquals(3, log.size()); @@ -282,7 +284,8 @@ public void endTag(String name, String content, Stack context) { }.parse(stream); Assert.fail("expected exception."); } catch (UncheckedIOException e) { - Assert.assertTrue(e.getCause() instanceof SAXParseException); // expected + Assert.assertTrue(e.getCause() instanceof IOException); // expected + Assert.assertTrue(e.getCause().getCause() instanceof SAXParseException); // expected } Assert.assertEquals(5, log.size()); diff --git a/matsim/src/test/java/org/matsim/core/utils/misc/ConfigUtilsTest.java b/matsim/src/test/java/org/matsim/core/utils/misc/ConfigUtilsTest.java index 86c61c5f05b..2b0e176d0bb 100644 --- a/matsim/src/test/java/org/matsim/core/utils/misc/ConfigUtilsTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/misc/ConfigUtilsTest.java @@ -91,7 +91,7 @@ public void loadConfigWithTypedArgs(){ final URL url = IOUtils.extendUrl( ExamplesUtils.getTestScenarioURL( "equil" ), "config.xml" ); final String [] typedArgs = {"--config:controler.outputDirectory=abc"} ; Config config = ConfigUtils.loadConfig( url, typedArgs ); - Assert.assertEquals("abc", config.controler().getOutputDirectory()); + Assert.assertEquals("abc", config.controller().getOutputDirectory()); } @Test public void loadConfigWithTypedArgsWithTypo(){ diff --git a/matsim/src/test/java/org/matsim/core/utils/timing/TimeInterpretationTest.java b/matsim/src/test/java/org/matsim/core/utils/timing/TimeInterpretationTest.java index 8f2d3624feb..e8ef70e3ccd 100644 --- a/matsim/src/test/java/org/matsim/core/utils/timing/TimeInterpretationTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/timing/TimeInterpretationTest.java @@ -39,7 +39,7 @@ import org.matsim.api.core.v01.population.PopulationFactory; 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.ScoringConfigGroup.ActivityParams; import org.matsim.core.config.groups.PlansConfigGroup.TripDurationHandling; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -92,13 +92,13 @@ public class TimeInterpretationTest { } private Controler prepareController(Config config) { - config.controler() + config.controller() .setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); ActivityParams genericParams = new ActivityParams("generic"); genericParams.setScoringThisActivityAtAll(false); - config.planCalcScore().addActivityParams(genericParams); + config.scoring().addActivityParams(genericParams); Scenario scenario = ScenarioUtils.createScenario(config); diff --git a/matsim/src/test/java/org/matsim/counts/CountsControlerListenerTest.java b/matsim/src/test/java/org/matsim/counts/CountsControlerListenerTest.java index 314a4483179..45f5d661b93 100644 --- a/matsim/src/test/java/org/matsim/counts/CountsControlerListenerTest.java +++ b/matsim/src/test/java/org/matsim/counts/CountsControlerListenerTest.java @@ -65,7 +65,7 @@ public class CountsControlerListenerTest { public void testUseVolumesOfIteration() { Config config = ConfigUtils.createConfig(); Scenario scenario = ScenarioUtils.createScenario(config); - CountsControlerListener ccl = new CountsControlerListener(config.global(), scenario.getNetwork(), config.controler(), config.counts(), null, null, null); + CountsControlerListener ccl = new CountsControlerListener(config.global(), scenario.getNetwork(), config.controller(), config.counts(), null, null, null); // test defaults Assert.assertEquals(10, config.counts().getWriteCountsInterval()); @@ -265,23 +265,23 @@ public void install() { bind(Mobsim.class).toProvider(DummyMobsimFactory.class); } }); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(7); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(7); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); controler.run(); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.0/0.countscompare.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.1/1.countscompare.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.2/2.countscompare.txt").exists()); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.3/3.countscompare.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.4/4.countscompare.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.5/5.countscompare.txt").exists()); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.6/6.countscompare.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.7/7.countscompare.txt").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.0/0.countscompare.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.1/1.countscompare.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.2/2.countscompare.txt").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.3/3.countscompare.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.4/4.countscompare.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.5/5.countscompare.txt").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.6/6.countscompare.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.7/7.countscompare.txt").exists()); } @Test @@ -303,26 +303,26 @@ public void install() { bind(Mobsim.class).toProvider(DummyMobsimFactory.class); } }); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(7); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(7); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); controler.run(); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.0/0.countscompareAWTV.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.1/1.countscompareAWTV.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.2/2.countscompareAWTV.txt").exists()); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.4/4.countscompareAWTV.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.5/5.countscompareAWTV.txt").exists()); - Assert.assertTrue(new File(config.controler().getOutputDirectory() + "ITERS/it.6/6.countscompareAWTV.txt").exists()); - Assert.assertFalse(new File(config.controler().getOutputDirectory() + "ITERS/it.7/7.countscompareAWTV.txt").exists()); - - Assert.assertEquals(3.5, getVolume(config.controler().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); - Assert.assertEquals(6.5, getVolume(config.controler().getOutputDirectory() + "ITERS/it.6/6.countscompareAWTV.txt"), 1e-8); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.0/0.countscompareAWTV.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.1/1.countscompareAWTV.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.2/2.countscompareAWTV.txt").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.4/4.countscompareAWTV.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.5/5.countscompareAWTV.txt").exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory() + "ITERS/it.6/6.countscompareAWTV.txt").exists()); + Assert.assertFalse(new File(config.controller().getOutputDirectory() + "ITERS/it.7/7.countscompareAWTV.txt").exists()); + + Assert.assertEquals(3.5, getVolume(config.controller().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); + Assert.assertEquals(6.5, getVolume(config.controller().getOutputDirectory() + "ITERS/it.6/6.countscompareAWTV.txt"), 1e-8); } @Test @@ -337,30 +337,30 @@ public void testFilterAnalyzedModes() throws IOException { cConfig.setOutputFormat("txt"); cConfig.setInputFile("counts.xml"); // just any file to activate the counts feature - config.controler().setMobsim("dummy"); - config.controler().setFirstIteration(0); - config.controler().setLastIteration(3); + config.controller().setMobsim("dummy"); + config.controller().setFirstIteration(0); + config.controller().setLastIteration(3); createAndRunControler(config); - Assert.assertEquals(150, getVolume(config.controler().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); + Assert.assertEquals(150, getVolume(config.controller().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); // enable modes filtering and count only car cConfig.setAnalyzedModes(TransportMode.car); cConfig.setFilterModes(true); createAndRunControler(config); - Assert.assertEquals(100, getVolume(config.controler().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); + Assert.assertEquals(100, getVolume(config.controller().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); // enable modes filtering and count only walk cConfig.setAnalyzedModes(TransportMode.walk); cConfig.setFilterModes(true); createAndRunControler(config); - Assert.assertEquals(50, getVolume(config.controler().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); + Assert.assertEquals(50, getVolume(config.controller().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); // enable modes filtering and count only bike cConfig.setAnalyzedModes(TransportMode.bike); cConfig.setFilterModes(true); createAndRunControler(config); - Assert.assertEquals(0, getVolume(config.controler().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); + Assert.assertEquals(0, getVolume(config.controller().getOutputDirectory() + "ITERS/it.3/3.countscompareAWTV.txt"), 1e-8); } @@ -375,11 +375,11 @@ public void install() { bind(EventsManager.class).to(EventsManagerImpl.class).in(Singleton.class); } }); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - controler.getConfig().controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); controler.run(); } diff --git a/matsim/src/test/java/org/matsim/counts/CountsReprojectionIOTest.java b/matsim/src/test/java/org/matsim/counts/CountsReprojectionIOTest.java index 59e0ba11b01..55e42f43d49 100644 --- a/matsim/src/test/java/org/matsim/counts/CountsReprojectionIOTest.java +++ b/matsim/src/test/java/org/matsim/counts/CountsReprojectionIOTest.java @@ -32,7 +32,6 @@ import org.matsim.api.core.v01.network.Link; 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.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; @@ -97,9 +96,9 @@ public void testWithControlerAndConfigParameters() { // TODO: test also with loading from Controler C'tor? final Scenario scenario = ScenarioUtils.loadScenario( config ); - config.controler().setLastIteration( 0 ); + config.controller().setLastIteration( 0 ); final String outputDirectory = utils.getOutputDirectory()+"/output/"; - config.controler().setOutputDirectory( outputDirectory ); + config.controller().setOutputDirectory( outputDirectory ); final Controler controler = new Controler( scenario ); controler.run(); diff --git a/matsim/src/test/java/org/matsim/examples/EquilTest.java b/matsim/src/test/java/org/matsim/examples/EquilTest.java index 13ccb964846..c884bf4b3a5 100644 --- a/matsim/src/test/java/org/matsim/examples/EquilTest.java +++ b/matsim/src/test/java/org/matsim/examples/EquilTest.java @@ -68,7 +68,7 @@ public static Collection parameterObjects () { @Test public void testEquil() { Config config = ConfigUtils.createConfig() ; - config.controler().setOutputDirectory( utils.getOutputDirectory() ); + config.controller().setOutputDirectory( utils.getOutputDirectory() ); config.qsim().setUsingFastCapacityUpdate(this.isUsingFastCapacityUpdate); config.facilities().setFacilitiesSource( FacilitiesConfigGroup.FacilitiesSource.onePerActivityLinkInPlansFile ); diff --git a/matsim/src/test/java/org/matsim/examples/OnePercentBerlin10sIT.java b/matsim/src/test/java/org/matsim/examples/OnePercentBerlin10sIT.java index dafea13f5b0..92e9431f0c5 100644 --- a/matsim/src/test/java/org/matsim/examples/OnePercentBerlin10sIT.java +++ b/matsim/src/test/java/org/matsim/examples/OnePercentBerlin10sIT.java @@ -66,7 +66,7 @@ public class OnePercentBerlin10sIT { config.qsim().setStorageCapFactor(0.04); config.qsim().setRemoveStuckVehicles(false); config.qsim().setStuckTime(10.0); - config.planCalcScore().setLearningRate(1.0); + config.scoring().setLearningRate(1.0); config.plans().setActivityDurationInterpretation(PlansConfigGroup.ActivityDurationInterpretation.minOfDurationAndEndTime); @@ -110,9 +110,9 @@ public class OnePercentBerlin10sIT { config.qsim().setStorageCapFactor(0.04); config.qsim().setRemoveStuckVehicles(false); config.qsim().setStuckTime(10.0); - config.planCalcScore().setLearningRate(1.0); + config.scoring().setLearningRate(1.0); - config.controler().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setOutputDirectory(utils.getOutputDirectory()); Scenario scenario = ScenarioUtils.createScenario(config); diff --git a/matsim/src/test/java/org/matsim/examples/PtTutorialIT.java b/matsim/src/test/java/org/matsim/examples/PtTutorialIT.java index b6636c931a5..43c8378d326 100644 --- a/matsim/src/test/java/org/matsim/examples/PtTutorialIT.java +++ b/matsim/src/test/java/org/matsim/examples/PtTutorialIT.java @@ -51,13 +51,13 @@ public class PtTutorialIT { private final static Logger log = LogManager.getLogger(PtTutorialIT.class); - + public @Rule MatsimTestUtils utils = new MatsimTestUtils(); - + @Test public void ensure_tutorial_runs() throws MalformedURLException { Config config = this.utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("pt-tutorial"), "0.config.xml")); - config.controler().setLastIteration(1); + config.controller().setLastIteration(1); try { Controler controler = new Controler(config); @@ -76,9 +76,9 @@ public void ensure_tutorial_runs() throws MalformedURLException { Assert.fail("There shouldn't be any exception, but there was ... :-("); } final String it1Plans = "ITERS/it.1/1.plans.xml.gz"; - Assert.assertTrue(new File(config.controler().getOutputDirectory(), it1Plans).exists()); - Assert.assertTrue(new File(config.controler().getOutputDirectory(), "output_config.xml").exists()); - + Assert.assertTrue(new File(config.controller().getOutputDirectory(), it1Plans).exists()); + Assert.assertTrue(new File(config.controller().getOutputDirectory(), "output_config.xml").exists()); + log.info( Controler.DIVIDER ) ; log.info( Controler.DIVIDER ) ; // try to restart from output: @@ -87,11 +87,11 @@ public void ensure_tutorial_runs() throws MalformedURLException { config.plans().setInputFile(new File(utils.getOutputDirectory() + "/" + it1Plans).toURI().toURL().toString()); - config.controler().setOverwriteFileSetting( OverwriteFileSetting.overwriteExistingFiles ); + config.controller().setOverwriteFileSetting( OverwriteFileSetting.overwriteExistingFiles ); // note: cannot delete directory since some of the input resides there. kai, sep'15 - - config.controler().setFirstIteration(10); - config.controler().setLastIteration(10); + + config.controller().setFirstIteration(10); + config.controller().setLastIteration(10); try { Controler controler = new Controler(config); @@ -110,7 +110,7 @@ public void ensure_tutorial_runs() throws MalformedURLException { log.error(e.getMessage(), e); Assert.fail("There shouldn't be any exception, but there was ... :-("); } - + } private static final class EnterVehicleEventCounter implements PersonEntersVehicleEventHandler { @@ -154,5 +154,5 @@ private static final class StageActivityDurationChecker implements ActivityStart } } } - + } diff --git a/matsim/src/test/java/org/matsim/examples/simple/PtScoringTest.java b/matsim/src/test/java/org/matsim/examples/simple/PtScoringTest.java index b7a7551dfbd..3789e469a25 100644 --- a/matsim/src/test/java/org/matsim/examples/simple/PtScoringTest.java +++ b/matsim/src/test/java/org/matsim/examples/simple/PtScoringTest.java @@ -17,9 +17,6 @@ * * * *********************************************************************** */ -/** - * - */ package org.matsim.examples.simple; import java.util.List; @@ -36,9 +33,9 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.TypicalDurationScoreComputation; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup.TypicalDurationScoreComputation; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.scoring.functions.ActivityUtilityParameters; @@ -58,31 +55,30 @@ public class PtScoringTest { @Parameter public TypicalDurationScoreComputation typicalDurationScoreComputation; - + @Parameterized.Parameters public static Object[] testParameters() { - return new Object[] {TypicalDurationScoreComputation.relative,TypicalDurationScoreComputation.uniform}; + return new Object[] {TypicalDurationScoreComputation.relative, TypicalDurationScoreComputation.uniform}; } - + @Rule public MatsimTestUtils utils = new MatsimTestUtils(); @Test public void test_PtScoringLineswitch() { Config config = this.utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("pt-simple-lineswitch"), "config.xml")); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); - PlanCalcScoreConfigGroup pcs = config.planCalcScore() ; + ScoringConfigGroup pcs = config.scoring() ; if(this.typicalDurationScoreComputation.equals(TypicalDurationScoreComputation.uniform)){ for(ActivityParams params : pcs.getActivityParams()){ params.setTypicalDurationScoreComputation(typicalDurationScoreComputation); } } - + pcs.setWriteExperiencedPlans(true); Controler controler = new Controler(config); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setCreateGraphs(false); EventsCollector collector = new EventsCollector(); controler.getEvents().addHandler(collector); @@ -99,7 +95,7 @@ public void test_PtScoringLineswitch() { double typicalDuration_s = pcs.getActivityParams("home").getTypicalDuration().seconds(); double priority = 1. ; - + // double zeroUtilityDurationHome_s = CharyparNagelScoringUtils.computeZeroUtilityDuration_s(priority, typicalDuration_s); ActivityUtilityParameters.Builder builder = new ActivityUtilityParameters.Builder( pcs.getActivityParams("home") ) ; ActivityUtilityParameters params = builder.build() ; @@ -130,7 +126,7 @@ public void test_PtScoringLineswitch() { double score = pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (stop1Arr-homeAct1End)/3600. ; System.out.println("score after walk: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt interact: " + score ) ; // yyyy wait is not separately scored!! @@ -141,14 +137,14 @@ public void test_PtScoringLineswitch() { score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * (leaveVeh-enterVeh)/3600. ; System.out.println("score after travel pt: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt interact: " + score ) ; score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (home2Arr-ptIA2ActEnd)/3600. ; System.out.println("score after walk: " + score ) ; final double duration = homeAct2End-home2Arr; - double tmpScore = (pcs.getPerforming_utils_hr()/3600.) * typicalDuration_s + double tmpScore = (pcs.getPerforming_utils_hr()/3600.) * typicalDuration_s * Math.log(duration/zeroUtilityDurationHome_s) ; if ( tmpScore < 0 ) { System.out.println("home2score< 0; replacing ... ") ; @@ -163,7 +159,7 @@ public void test_PtScoringLineswitch() { score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (stop2Arr-homeAct2End)/3600. ; System.out.println("score after walk: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt int act: " + score ) ; score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * (enterVeh2-ptIA3ActEnd)/3600. ; @@ -172,7 +168,7 @@ public void test_PtScoringLineswitch() { score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * (leaveVeh2-enterVeh2)/3600. ; System.out.println("score after travel pt: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt int act: " + score ) ; score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (stop3Arr-ptIA4ActEnd)/3600. ; @@ -183,7 +179,7 @@ public void test_PtScoringLineswitch() { // ------ - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt int act: " + score ) ; score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * (enterVeh3-ptIA5ActEnd)/3600. ; @@ -192,13 +188,13 @@ public void test_PtScoringLineswitch() { score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * (leaveVeh3-enterVeh3)/3600. ; System.out.println("score after travel pt: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt int act: " + score ) ; score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (home3Arr-ptIA6ActEnd)/3600. ; System.out.println("score after walk: " + score ) ; - score += (pcs.getPerforming_utils_hr()/3600.) * typicalDuration_s + score += (pcs.getPerforming_utils_hr()/3600.) * typicalDuration_s * Math.log((homeAct1End-home3Arr+24.*3600)/zeroUtilityDurationHome_s) ; System.out.println("score after home act: " + score ) ; @@ -208,34 +204,33 @@ public void test_PtScoringLineswitch() { // (there is only one person, but we need to get it) System.out.println(" score: " + pp.getSelectedPlan().getScore() ) ; - + if(this.typicalDurationScoreComputation.equals(TypicalDurationScoreComputation.uniform)){ - Assert.assertEquals(-21.28929580072052, pp.getSelectedPlan().getScore(), MatsimTestUtils.EPSILON ) ; + Assert.assertEquals(-21.280962467387187, pp.getSelectedPlan().getScore(), MatsimTestUtils.EPSILON ) ; } else{ - Assert.assertEquals(27.46011565686209, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; + Assert.assertEquals(27.468448990195423, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; } - + } } @Test public void test_PtScoringLineswitchAndPtConstant() { Config config = this.utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("pt-simple-lineswitch"), "config.xml")); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); - PlanCalcScoreConfigGroup pcs = config.planCalcScore() ; + ScoringConfigGroup pcs = config.scoring() ; if(this.typicalDurationScoreComputation.equals(TypicalDurationScoreComputation.uniform)) for(ActivityParams params : pcs.getActivityParams()){ params.setTypicalDurationScoreComputation(typicalDurationScoreComputation); } - + pcs.setWriteExperiencedPlans(true); pcs.getModes().get(TransportMode.pt).setConstant(1.); Controler controler = new Controler(config); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setCreateGraphs(false); EventsCollector collector = new EventsCollector(); controler.getEvents().addHandler(collector); @@ -247,7 +242,7 @@ public void test_PtScoringLineswitchAndPtConstant() { for (Event event : allEvents) { System.out.println(event.toString()); } - + double typicalDuration_s = pcs.getActivityParams("home").getTypicalDuration().seconds(); double priority = 1. ; @@ -280,7 +275,7 @@ public void test_PtScoringLineswitchAndPtConstant() { double score = pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (stop1Arr-homeAct1End)/3600. ; System.out.println("score after walk: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt interact: " + score ) ; score += pcs.getModes().get(TransportMode.pt).getConstant(); @@ -294,13 +289,13 @@ public void test_PtScoringLineswitchAndPtConstant() { score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * (leaveVeh-enterVeh)/3600. ; System.out.println("score after travel pt: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt interact: " + score ) ; score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (home2Arr-ptIA2ActEnd)/3600. ; System.out.println("score after walk: " + score ) ; - double tmpScore = (pcs.getPerforming_utils_hr()/3600.) * typicalDuration_s + double tmpScore = (pcs.getPerforming_utils_hr()/3600.) * typicalDuration_s * Math.log((homeAct2End-home2Arr)/zeroUtilityDurationHome_s) ; if ( tmpScore < 0 ) { System.out.println("home2score< 0; replacing ... ") ; @@ -315,7 +310,7 @@ public void test_PtScoringLineswitchAndPtConstant() { score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (stop2Arr-homeAct2End)/3600. ; System.out.println("score after walk: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt int act: " + score ) ; score += pcs.getModes().get(TransportMode.pt).getConstant(); @@ -327,7 +322,7 @@ public void test_PtScoringLineswitchAndPtConstant() { score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * (leaveVeh2-enterVeh2)/3600. ; System.out.println("score after travel pt: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt int act: " + score ) ; score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (stop3Arr-ptIA4ActEnd)/3600. ; @@ -338,7 +333,7 @@ public void test_PtScoringLineswitchAndPtConstant() { // ------ - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt int act: " + score ) ; score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * (enterVeh3-ptIA5ActEnd)/3600. ; @@ -347,13 +342,13 @@ public void test_PtScoringLineswitchAndPtConstant() { score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * (leaveVeh3-enterVeh3)/3600. ; System.out.println("score after travel pt: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score after pt int act: " + score ) ; score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (home3Arr-ptIA6ActEnd)/3600. ; System.out.println("score after walk: " + score ) ; - score += (pcs.getPerforming_utils_hr()/3600.) * typicalDuration_s + score += (pcs.getPerforming_utils_hr()/3600.) * typicalDuration_s * Math.log((homeAct1End-home3Arr+24.*3600)/zeroUtilityDurationHome_s) ; System.out.println("score after home act: " + score ) ; @@ -363,36 +358,35 @@ public void test_PtScoringLineswitchAndPtConstant() { // (there is only one person, but we need to get it) System.out.println(" score: " + pp.getSelectedPlan().getScore() ) ; - + if(this.typicalDurationScoreComputation.equals(TypicalDurationScoreComputation.uniform)){ // Assert.assertEquals(89.14608279715044, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; - Assert.assertEquals(-19.28929580072052, pp.getSelectedPlan().getScore(), MatsimTestUtils.EPSILON ) ; + Assert.assertEquals(-19.280962467387187, pp.getSelectedPlan().getScore(), MatsimTestUtils.EPSILON ) ; } else{ - Assert.assertEquals(29.46011565686209, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; + Assert.assertEquals(29.468448990195423, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; } - + } } @Test public void test_PtScoring_Wait() { Config config = this.utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("pt-simple"), "config.xml")); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); - PlanCalcScoreConfigGroup pcs = config.planCalcScore() ; - + ScoringConfigGroup pcs = config.scoring(); + if(this.typicalDurationScoreComputation.equals(TypicalDurationScoreComputation.uniform)){ for(ActivityParams params : pcs.getActivityParams()){ params.setTypicalDurationScoreComputation(typicalDurationScoreComputation); } } - + pcs.setWriteExperiencedPlans(true); pcs.setMarginalUtlOfWaitingPt_utils_hr(-18.0) ; - + Controler controler = new Controler(config); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setCreateGraphs(false); EventsCollector collector = new EventsCollector(); controler.getEvents().addHandler(collector); @@ -404,7 +398,7 @@ public void test_PtScoring_Wait() { for (Event event : allEvents) { System.out.println(event.toString()); } - + double typicalDuration_s = pcs.getActivityParams("home").getTypicalDuration().seconds(); double priority = 1. ; @@ -423,7 +417,7 @@ public void test_PtScoring_Wait() { double score = pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (timeTransitWalk/3600.) ; System.out.println("score: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score: " + score ) ; System.out.println("marginalUtlOfWaitPt: " + pcs.getMarginalUtlOfWaitingPt_utils_hr() ) ; @@ -436,7 +430,7 @@ public void test_PtScoring_Wait() { score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * timeTransitInVeh/3600. ; System.out.println("score: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score: " + score ) ; score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * timeTransitWalk2/3600. ; @@ -451,12 +445,12 @@ public void test_PtScoring_Wait() { // (there is only one person, but we need to get it) System.out.println("agent score: " + pp.getSelectedPlan().getScore() ) ; - + if(this.typicalDurationScoreComputation.equals(TypicalDurationScoreComputation.uniform)){ - Assert.assertEquals(89.14608279715044, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; + Assert.assertEquals(89.13108279715044, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; } else{ - Assert.assertEquals(137.14608279715043, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; + Assert.assertEquals(137.1310827971504, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; } } @@ -465,19 +459,18 @@ public void test_PtScoring_Wait() { @Test public void test_PtScoring() { Config config = this.utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("pt-simple"), "config.xml")); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); - PlanCalcScoreConfigGroup pcs = config.planCalcScore() ; + ScoringConfigGroup pcs = config.scoring() ; if(this.typicalDurationScoreComputation.equals(TypicalDurationScoreComputation.uniform)) for(ActivityParams params : pcs.getActivityParams()){ params.setTypicalDurationScoreComputation(typicalDurationScoreComputation); } - + pcs.setWriteExperiencedPlans(true); Controler controler = new Controler(config); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setCreateGraphs(false); EventsCollector collector = new EventsCollector(); controler.getEvents().addHandler(collector); @@ -508,7 +501,7 @@ public void test_PtScoring() { double score = pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * (timeTransitWalk/3600.) ; System.out.println("score: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score: " + score ) ; // score += pcs.getMarginalUtlOfWaitingPt_utils_hr() * timeTransitWait/3600. ; @@ -519,7 +512,7 @@ public void test_PtScoring() { score += pcs.getModes().get(TransportMode.pt).getMarginalUtilityOfTraveling() * timeTransitInVeh/3600. ; System.out.println("score: " + score ) ; - // (pt interaction activity) + // (pt interaction activity) System.out.println("score: " + score ) ; score += pcs.getModes().get(TransportMode.walk).getMarginalUtilityOfTraveling() * timeTransitWalk2/3600. ; @@ -534,15 +527,15 @@ public void test_PtScoring() { // (there is only one person, but we need to get it) System.out.println(" score: " + pp.getSelectedPlan().getScore() ) ; - + if(this.typicalDurationScoreComputation.equals(TypicalDurationScoreComputation.uniform)){ - Assert.assertEquals(89.85608279715044, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; + Assert.assertEquals(89.87441613048377, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; } else{ - Assert.assertEquals(137.85608279715044, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; + Assert.assertEquals(137.87441613048375, pp.getSelectedPlan().getScore(),MatsimTestUtils.EPSILON ) ; } - - + + } } diff --git a/matsim/src/test/java/org/matsim/facilities/ActivityFacilitiesSourceTest.java b/matsim/src/test/java/org/matsim/facilities/ActivityFacilitiesSourceTest.java index e4f5cbc305d..30d0e5a0a6e 100644 --- a/matsim/src/test/java/org/matsim/facilities/ActivityFacilitiesSourceTest.java +++ b/matsim/src/test/java/org/matsim/facilities/ActivityFacilitiesSourceTest.java @@ -52,7 +52,7 @@ @RunWith(Parameterized.class) public class ActivityFacilitiesSourceTest { - + @Rule public MatsimTestUtils utils = new MatsimTestUtils() ; // private static final String outDir = "test/output/"+ActivityFacilitiesSourceTest.class.getCanonicalName().replace('.','/')+"/"; @@ -86,14 +86,14 @@ public void test(){ new File(testOutDir).mkdirs(); Scenario scenario = prepareScenario(); - scenario.getConfig().controler().setOutputDirectory(testOutDir); - scenario.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + scenario.getConfig().controller().setOutputDirectory(testOutDir); + scenario.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); // (overwriteExistingFiles is needed here for the parameterized test since otherwise all output directories except for // the last test will be deleted and thus not available for debugging. kai, sep'19) new Controler(scenario).run(); // checks - ActivityFacilities activityFacilities = getFacilities(scenario.getConfig().controler().getOutputDirectory()); + ActivityFacilities activityFacilities = getFacilities(scenario.getConfig().controller().getOutputDirectory()); switch (this.facilitiesSource) { case none: break; @@ -115,13 +115,13 @@ public void test(){ } break; case onePerActivityLinkInPlansFile: - Assert.assertEquals("wrong number of facilities", 4, getFacilities(scenario.getConfig().controler().getOutputDirectory()).getFacilities().size(), MatsimTestUtils.EPSILON); + Assert.assertEquals("wrong number of facilities", 4, getFacilities(scenario.getConfig().controller().getOutputDirectory()).getFacilities().size(), MatsimTestUtils.EPSILON); for (ActivityFacility af : activityFacilities.getFacilities().values()){ Assert.assertNotNull(af.getLinkId()); } break; case onePerActivityLocationInPlansFile: - Assert.assertEquals("wrong number of facilities", 2, getFacilities(scenario.getConfig().controler().getOutputDirectory()).getFacilities().size(), MatsimTestUtils.EPSILON); + Assert.assertEquals("wrong number of facilities", 2, getFacilities(scenario.getConfig().controller().getOutputDirectory()).getFacilities().size(), MatsimTestUtils.EPSILON); for (ActivityFacility af : activityFacilities.getFacilities().values()){ Assert.assertNotNull(af.getCoord()); Assert.assertNotNull(af.getLinkId()); @@ -136,13 +136,13 @@ private ActivityFacilities getFacilities(String outputDir){ return scenario.getActivityFacilities(); } - + // create basic scenario private Scenario prepareScenario() { Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); config.plans().setInputFile(null); - config.controler().setLastIteration(0); - + config.controller().setLastIteration(0); + switch (facilitiesSource) { case fromFile: break; @@ -158,11 +158,11 @@ private Scenario prepareScenario() { // config.facilities().setAssigningLinksToFacilitiesIfMissing(false); break; } - + config.facilities().setFacilitiesSource(facilitiesSource); - + Scenario scenario = ScenarioUtils.loadScenario(config); - + if (facilitiesSource.equals(FacilitiesConfigGroup.FacilitiesSource.setInScenario)) { ActivityFacilities facilities = scenario.getActivityFacilities(); ActivityFacilitiesFactory factory = facilities.getFactory(); @@ -182,7 +182,7 @@ private Scenario prepareScenario() { Id.createLinkId("20"))); } } - + PopulationFactory populationFactory = scenario.getPopulation().getFactory(); String mode = TransportMode.car; @@ -297,7 +297,7 @@ private Scenario prepareScenario() { } return scenario; } - + private boolean assignFacilityIdToActivity(FacilitiesConfigGroup.FacilitiesSource facilitiesSource) { return facilitiesSource.equals(FacilitiesConfigGroup.FacilitiesSource.setInScenario) || facilitiesSource.equals( FacilitiesConfigGroup.FacilitiesSource.fromFile); diff --git a/matsim/src/test/java/org/matsim/facilities/ActivityWithOnlyFacilityIdTest.java b/matsim/src/test/java/org/matsim/facilities/ActivityWithOnlyFacilityIdTest.java index d23b6e962d4..11666860066 100644 --- a/matsim/src/test/java/org/matsim/facilities/ActivityWithOnlyFacilityIdTest.java +++ b/matsim/src/test/java/org/matsim/facilities/ActivityWithOnlyFacilityIdTest.java @@ -24,8 +24,8 @@ public void testSiouxFallsWithOnlyFacilityIds() { URL scenarioURL = ExamplesUtils.getTestScenarioURL("siouxfalls-2014"); Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(scenarioURL, "config_default.xml")); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setLastIteration(1); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setLastIteration(1); Scenario scenario = ScenarioUtils.loadScenario(config); diff --git a/matsim/src/test/java/org/matsim/facilities/FacilitiesFromPopulationTest.java b/matsim/src/test/java/org/matsim/facilities/FacilitiesFromPopulationTest.java index 5f19f968480..fa503cb96f4 100644 --- a/matsim/src/test/java/org/matsim/facilities/FacilitiesFromPopulationTest.java +++ b/matsim/src/test/java/org/matsim/facilities/FacilitiesFromPopulationTest.java @@ -37,8 +37,8 @@ import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup; -import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.scenario.ScenarioUtils; /** @@ -54,13 +54,13 @@ public void testRun_onePerLink_assignLinks() { generator.setOneFacilityPerLink(true); generator.setAssignLinksToFacilitiesIfMissing( f.scenario.getNetwork() ); generator.run(f.scenario.getPopulation()); - + Assert.assertEquals(3, f.scenario.getActivityFacilities().getFacilities().size()); - + Assert.assertEquals("bc", f.scenario.getActivityFacilities().getFacilities().get(Id.create("bc", ActivityFacility.class)).getLinkId().toString()); Assert.assertEquals("ca", f.scenario.getActivityFacilities().getFacilities().get(Id.create("ca", ActivityFacility.class)).getLinkId().toString()); Assert.assertEquals("ab", f.scenario.getActivityFacilities().getFacilities().get(Id.create("ab", ActivityFacility.class)).getLinkId().toString()); - + assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("1", Person.class)).getSelectedPlan(), "ab", "bc", true); assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("2", Person.class)).getSelectedPlan(), "ab", "bc", true); assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("3", Person.class)).getSelectedPlan(), "ab", "bc", true); @@ -76,12 +76,12 @@ public void testRun_onePerLink_assignLinks() { @Test public void testRun_onePerLink_assignLinks_openingTimes() { Fixture f = new Fixture(); - + FacilitiesFromPopulation generator = new FacilitiesFromPopulation(f.scenario.getActivityFacilities()); generator.setOneFacilityPerLink(true); generator.setAddEmptyActivityOptions(true); generator.setAssignLinksToFacilitiesIfMissing( f.scenario.getNetwork() ); - PlanCalcScoreConfigGroup config = new PlanCalcScoreConfigGroup(); + ScoringConfigGroup config = new ScoringConfigGroup(); ActivityParams homeParams = new ActivityParams("home"); ActivityParams workParams = new ActivityParams("work"); workParams.setOpeningTime(7*3600); @@ -90,13 +90,13 @@ public void testRun_onePerLink_assignLinks_openingTimes() { config.addActivityParams(workParams); generator.assignOpeningTimes( config ); generator.run(f.scenario.getPopulation()); - + Assert.assertEquals(3, f.scenario.getActivityFacilities().getFacilities().size()); - + Map, ? extends ActivityFacility> ffs = f.scenario.getActivityFacilities().getFacilities(); Assert.assertEquals(7*3600, ffs.get(Id.create("ab", ActivityFacility.class)).getActivityOptions().get("work").getOpeningTimes().first().getStartTime(), 1e-7); Assert.assertEquals(19*3600, ffs.get(Id.create("ab", ActivityFacility.class)).getActivityOptions().get("work").getOpeningTimes().first().getEndTime(), 1e-7); - + assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("1", Person.class)).getSelectedPlan(), "ab", "bc", true); assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("2", Person.class)).getSelectedPlan(), "ab", "bc", true); assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("3", Person.class)).getSelectedPlan(), "ab", "bc", true); @@ -112,16 +112,16 @@ public void testRun_onePerLink_assignLinks_openingTimes() { @Test public void testRun_multiple_assignLinks() { Fixture f = new Fixture(); - + FacilitiesFromPopulation generator = new FacilitiesFromPopulation(f.scenario.getActivityFacilities()); generator.setOneFacilityPerLink(false); generator.setAssignLinksToFacilitiesIfMissing( f.scenario.getNetwork() ); generator.run(f.scenario.getPopulation()); - + // for (ActivityFacility af : f.scenario.getActivityFacilities().getFacilities().values()) { // System.out.println(af.getId() + "\t" + af.getLinkId() + "\t" + af.getCoord().getX() + "\t" + af.getCoord().getY()); // } - + Assert.assertEquals(13, f.scenario.getActivityFacilities().getFacilities().size()); Map, ? extends ActivityFacility> ffs = f.scenario.getActivityFacilities().getFacilities(); @@ -138,7 +138,7 @@ public void testRun_multiple_assignLinks() { Assert.assertEquals("ab", ffs.get(Id.create("10", ActivityFacility.class)).getLinkId().toString()); // work of agent 8-10 Assert.assertEquals("ca", ffs.get(Id.create("11", ActivityFacility.class)).getLinkId().toString()); // home of agent 9 Assert.assertEquals("ca", ffs.get(Id.create("12", ActivityFacility.class)).getLinkId().toString()); // home of agent 10 - + assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("1", Person.class)).getSelectedPlan(), "0", "1", true); assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("2", Person.class)).getSelectedPlan(), "2", "1", true); assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("3", Person.class)).getSelectedPlan(), "3", "1", true); @@ -150,16 +150,16 @@ public void testRun_multiple_assignLinks() { assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("9", Person.class)).getSelectedPlan(), "11", "10", true); assertPlan(f.scenario.getPopulation().getPersons().get(Id.create("0", Person.class)).getSelectedPlan(), "12", "10", true); } - + private void assertPlan(Plan plan, String homeFacilityId, String workFacilityId, boolean linkCoordMustBeNull) { Activity home1 = (Activity) plan.getPlanElements().get(0); Activity work = (Activity) plan.getPlanElements().get(2); Activity home2 = (Activity) plan.getPlanElements().get(4); - + Assert.assertEquals(homeFacilityId, home1.getFacilityId().toString()); Assert.assertEquals(workFacilityId, work.getFacilityId().toString()); Assert.assertEquals(homeFacilityId, home2.getFacilityId().toString()); - + if (linkCoordMustBeNull) { Assert.assertNull(home1.getLinkId()); Assert.assertNull(home1.getCoord()); @@ -169,11 +169,11 @@ private void assertPlan(Plan plan, String homeFacilityId, String workFacilityId, Assert.assertNull(home2.getCoord()); } } - + /** * Creates a simple scenario with a network with 3 links and * 10 agents. - * + * *
                 (C)
         	 *               / \
         	 *            8 /   \
        @@ -189,17 +189,17 @@ private void assertPlan(Plan plan, String homeFacilityId, String workFacilityId,
         	 *    (A)-------------------(B)
         	 *                  2
         	 * 
        - * + * * @author mrieser / Senozon AG */ private static class Fixture { Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); - + public Fixture() { createNetwork(); createPopulation(); } - + private void createNetwork() { Network network = this.scenario.getNetwork(); NetworkFactory factory = network.getFactory(); @@ -207,15 +207,15 @@ private void createNetwork() { Node a = factory.createNode(Id.create("A", Node.class), new Coord((double) 0, (double) 0)); Node b = factory.createNode(Id.create("B", Node.class), new Coord((double) 1000, (double) 0)); Node c = factory.createNode(Id.create("C", Node.class), new Coord((double) 500, (double) 600)); - + network.addNode(a); network.addNode(b); network.addNode(c); - + Link ab = factory.createLink(Id.create("ab", Link.class), a, b); Link bc = factory.createLink(Id.create("bc", Link.class), b, c); Link ca = factory.createLink(Id.create("ca", Link.class), c, a); - + Set modes = new HashSet<>(); modes.add("car"); for (Link l : new Link[] {ab, bc, ca}) { @@ -224,15 +224,15 @@ private void createNetwork() { l.setNumberOfLanes(1); l.setFreespeed(10.0); l.setAllowedModes(modes); - + network.addLink(l); } } - + private void createPopulation() { Population pop = scenario.getPopulation(); PopulationFactory factory = pop.getFactory(); - + pop.addPerson(createPersonWithPlan(factory, "1", 200, 10, 800, 300)); pop.addPerson(createPersonWithPlan(factory, "2", 500, -10, 800, 300)); pop.addPerson(createPersonWithPlan(factory, "3", 600, 20, 800, 300)); @@ -244,7 +244,7 @@ private void createPopulation() { pop.addPerson(createPersonWithPlan(factory, "9", 250, 250, 300, 100)); pop.addPerson(createPersonWithPlan(factory, "0", 0, 100, 300, 100)); } - + private Person createPersonWithPlan(PopulationFactory factory, String id, double homeX, double homeY, double workX, double workY) { Person person = factory.createPerson(Id.create(id, Person.class)); Plan plan = factory.createPlan(); @@ -254,15 +254,15 @@ private Person createPersonWithPlan(PopulationFactory factory, String id, double Activity work = factory.createActivityFromCoord("work", new Coord(workX, workY)); work.setEndTime(17*3600); Activity home2 = factory.createActivityFromCoord("home", new Coord(homeX, homeY)); - + plan.addActivity(home1); plan.addLeg(factory.createLeg("car")); plan.addActivity(work); plan.addLeg(factory.createLeg("car")); plan.addActivity(home2); - + return person; } - + } } diff --git a/matsim/src/test/java/org/matsim/facilities/FacilitiesReprojectionIOTest.java b/matsim/src/test/java/org/matsim/facilities/FacilitiesReprojectionIOTest.java index 63bc92a1f39..e3ad1e04478 100644 --- a/matsim/src/test/java/org/matsim/facilities/FacilitiesReprojectionIOTest.java +++ b/matsim/src/test/java/org/matsim/facilities/FacilitiesReprojectionIOTest.java @@ -114,9 +114,9 @@ public void testWithControlerAndObjectAttributes() { TARGET_CRS, ProjectionUtils.getCRS(scenario.getActivityFacilities())); - config.controler().setLastIteration( -1 ); + config.controller().setLastIteration( -1 ); final String outputDirectory = utils.getOutputDirectory()+"/output/"; - config.controler().setOutputDirectory( outputDirectory ); + config.controller().setOutputDirectory( outputDirectory ); final Controler controler = new Controler( scenario ); controler.run(); @@ -179,9 +179,9 @@ public void testWithControlerAndConfigParameters() { epsilon ); } - config.controler().setLastIteration( -1 ); + config.controller().setLastIteration( -1 ); final String outputDirectory = utils.getOutputDirectory()+"/output/"; - config.controler().setOutputDirectory( outputDirectory ); + config.controller().setOutputDirectory( outputDirectory ); final Controler controler = new Controler( scenario ); controler.run(); diff --git a/matsim/src/test/java/org/matsim/integration/EquilTwoAgentsTest.java b/matsim/src/test/java/org/matsim/integration/EquilTwoAgentsTest.java index c8b707958e0..3d2df7affd6 100644 --- a/matsim/src/test/java/org/matsim/integration/EquilTwoAgentsTest.java +++ b/matsim/src/test/java/org/matsim/integration/EquilTwoAgentsTest.java @@ -37,8 +37,8 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.PlanCalcScoreConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -93,16 +93,16 @@ public void testSingleIterationPlansV4() { ConfigUtils.loadConfig(config, IOUtils.extendUrl(utils.classInputResourcePath(), "config.xml")); config.plans().setInputFile(IOUtils.extendUrl(utils.classInputResourcePath(), "plans2.xml").toString()); - PlanCalcScoreConfigGroup pcsConfig = config.planCalcScore() ; + ScoringConfigGroup pcsConfig = config.scoring() ; ActivityParams params = new ActivityParams("h") ; params.setTypicalDuration(123456789.0) ; // probably dummy params.setScoringThisActivityAtAll(false); pcsConfig.addActivityParams(params) ; final Controler controler = new Controler(config); - controler.getConfig().controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setWriteEventsInterval(0); + controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setWriteEventsInterval(0); controler.addOverridingModule(new AbstractModule() { @Override public void install() { diff --git a/matsim/src/test/java/org/matsim/integration/SimulateAndScoreTest.java b/matsim/src/test/java/org/matsim/integration/SimulateAndScoreTest.java index e9ce57fff72..9d70490fc42 100644 --- a/matsim/src/test/java/org/matsim/integration/SimulateAndScoreTest.java +++ b/matsim/src/test/java/org/matsim/integration/SimulateAndScoreTest.java @@ -43,7 +43,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.AbstractModule; import org.matsim.core.controler.Injector; import org.matsim.core.controler.PrepareForSimUtils; @@ -90,22 +90,22 @@ public class SimulateAndScoreTest { final Config config = ConfigUtils.createConfig(); config.transit().setUseTransit(true); - PlanCalcScoreConfigGroup.ActivityParams h = new PlanCalcScoreConfigGroup.ActivityParams("h"); + ScoringConfigGroup.ActivityParams h = new ScoringConfigGroup.ActivityParams("h"); h.setTypicalDuration(16 * 3600); - PlanCalcScoreConfigGroup.ActivityParams w = new PlanCalcScoreConfigGroup.ActivityParams("w"); + ScoringConfigGroup.ActivityParams w = new ScoringConfigGroup.ActivityParams("w"); w.setTypicalDuration(8 * 3600); - PlanCalcScoreConfigGroup.ActivityParams transitActivityParams = new PlanCalcScoreConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); + ScoringConfigGroup.ActivityParams transitActivityParams = new ScoringConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); transitActivityParams.setTypicalDuration(120.0); - config.planCalcScore().setPerforming_utils_hr(0); - config.planCalcScore().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling((double) 0); - config.planCalcScore().getModes().get(TransportMode.pt).setMarginalUtilityOfTraveling((double) 0); - config.planCalcScore().getModes().get(TransportMode.walk).setMarginalUtilityOfTraveling((double) 0); - config.planCalcScore().getModes().get(TransportMode.car).setMonetaryDistanceRate((double) 10); - config.planCalcScore().getModes().get(TransportMode.pt).setMonetaryDistanceRate((double) 0); - config.planCalcScore().addActivityParams(h); - config.planCalcScore().addActivityParams(w); - config.planCalcScore().addActivityParams(transitActivityParams); + config.scoring().setPerforming_utils_hr(0); + config.scoring().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling((double) 0); + config.scoring().getModes().get(TransportMode.pt).setMarginalUtilityOfTraveling((double) 0); + config.scoring().getModes().get(TransportMode.walk).setMarginalUtilityOfTraveling((double) 0); + config.scoring().getModes().get(TransportMode.car).setMonetaryDistanceRate((double) 10); + config.scoring().getModes().get(TransportMode.pt).setMonetaryDistanceRate((double) 0); + config.scoring().addActivityParams(h); + config.scoring().addActivityParams(w); + config.scoring().addActivityParams(transitActivityParams); // --- @@ -278,17 +278,17 @@ public void install() { Netsim sim = new QSimBuilder(scenario.getConfig()) // .useDefaults() // .build(scenario, events); - PlanCalcScoreConfigGroup.ActivityParams h = new PlanCalcScoreConfigGroup.ActivityParams("h"); + ScoringConfigGroup.ActivityParams h = new ScoringConfigGroup.ActivityParams("h"); h.setTypicalDuration(16 * 3600); - PlanCalcScoreConfigGroup.ActivityParams w = new PlanCalcScoreConfigGroup.ActivityParams("w"); + ScoringConfigGroup.ActivityParams w = new ScoringConfigGroup.ActivityParams("w"); w.setTypicalDuration(8 * 3600); - scenario.getConfig().planCalcScore().setPerforming_utils_hr(0); + scenario.getConfig().scoring().setPerforming_utils_hr(0); final double travelingPt = -1.00; - scenario.getConfig().planCalcScore().getModes().get(TransportMode.pt).setMarginalUtilityOfTraveling(travelingPt); + scenario.getConfig().scoring().getModes().get(TransportMode.pt).setMarginalUtilityOfTraveling(travelingPt); double monetaryDistanceRatePt = -0.001; - scenario.getConfig().planCalcScore().getModes().get(TransportMode.pt).setMonetaryDistanceRate(monetaryDistanceRatePt); - scenario.getConfig().planCalcScore().addActivityParams(h); - scenario.getConfig().planCalcScore().addActivityParams(w); + scenario.getConfig().scoring().getModes().get(TransportMode.pt).setMonetaryDistanceRate(monetaryDistanceRatePt); + scenario.getConfig().scoring().addActivityParams(h); + scenario.getConfig().scoring().addActivityParams(w); EventsToScore scorer = EventsToScore.createWithScoreUpdating(scenario, new CharyparNagelScoringFunctionFactory(scenario), events); EventsCollector handler = new EventsCollector(); events.addHandler(handler); diff --git a/matsim/src/test/java/org/matsim/integration/events/PersonScoreEventTest.java b/matsim/src/test/java/org/matsim/integration/events/PersonScoreEventTest.java index a5fc87a32ab..501d668165c 100644 --- a/matsim/src/test/java/org/matsim/integration/events/PersonScoreEventTest.java +++ b/matsim/src/test/java/org/matsim/integration/events/PersonScoreEventTest.java @@ -29,7 +29,7 @@ import org.matsim.api.core.v01.events.PersonScoreEvent; import org.matsim.api.core.v01.population.Person; import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.config.groups.ControlerConfigGroup.EventsFileFormat; +import org.matsim.core.config.groups.ControllerConfigGroup.EventsFileFormat; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; import org.matsim.core.events.algorithms.EventWriterJson; diff --git a/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingIT.java b/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingIT.java index 0ae37563728..7373f84c106 100644 --- a/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingIT.java +++ b/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingIT.java @@ -36,11 +36,11 @@ public class InvertedNetworkRoutingIT { @Test public final void testLanesInvertedNetworkRouting() { InvertedNetworkRoutingTestFixture f = new InvertedNetworkRoutingTestFixture(false, true, false); - f.scenario.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory()); + f.scenario.getConfig().controller().setOutputDirectory(testUtils.getOutputDirectory()); f.scenario.getConfig().travelTimeCalculator().setSeparateModes( false ); Controler c = new Controler(f.scenario); - c.getConfig().controler().setDumpDataAtEnd(false); - c.getConfig().controler().setCreateGraphs(false); + c.getConfig().controller().setDumpDataAtEnd(false); + c.getConfig().controller().setCreateGraphs(false); final InvertedNetworkRoutingTestEventHandler testHandler = new InvertedNetworkRoutingTestEventHandler(); c.addControlerListener(new StartupListener(){ @Override @@ -56,11 +56,11 @@ public void notifyStartup(StartupEvent event) { @Test public final void testModesInvertedNetworkRouting() { InvertedNetworkRoutingTestFixture f = new InvertedNetworkRoutingTestFixture(true, false, false); - f.scenario.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory()); + f.scenario.getConfig().controller().setOutputDirectory(testUtils.getOutputDirectory()); f.scenario.getConfig().travelTimeCalculator().setSeparateModes( false ); Controler c = new Controler(f.scenario); - c.getConfig().controler().setDumpDataAtEnd(false); - c.getConfig().controler().setCreateGraphs(false); + c.getConfig().controller().setDumpDataAtEnd(false); + c.getConfig().controller().setCreateGraphs(false); final InvertedNetworkRoutingTestEventHandler testHandler = new InvertedNetworkRoutingTestEventHandler(); c.addControlerListener(new StartupListener(){ @Override @@ -75,13 +75,13 @@ public void notifyStartup(StartupEvent event) { @Test public final void testModesNotInvertedNetworkRouting() { InvertedNetworkRoutingTestFixture f = new InvertedNetworkRoutingTestFixture(true, false, false); - f.scenario.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory()); - f.scenario.getConfig().controler().setLinkToLinkRoutingEnabled(false); + f.scenario.getConfig().controller().setOutputDirectory(testUtils.getOutputDirectory()); + f.scenario.getConfig().controller().setLinkToLinkRoutingEnabled(false); f.scenario.getConfig().travelTimeCalculator().setCalculateLinkToLinkTravelTimes(false); Controler c = new Controler(f.scenario); //c.addOverridingModule(new InvertedNetworkRoutingGuiceModule()); - c.getConfig().controler().setDumpDataAtEnd(false); - c.getConfig().controler().setCreateGraphs(false); + c.getConfig().controller().setDumpDataAtEnd(false); + c.getConfig().controller().setCreateGraphs(false); final InvertedNetworkRoutingTestEventHandler testHandler = new InvertedNetworkRoutingTestEventHandler(); c.addControlerListener(new StartupListener(){ @Override diff --git a/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingTestFixture.java b/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingTestFixture.java index 153a5b95ebd..039fb91947f 100644 --- a/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingTestFixture.java +++ b/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingTestFixture.java @@ -38,8 +38,8 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.QSimConfigGroup; -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.replanning.strategies.DefaultPlanStrategiesModule; import org.matsim.core.scenario.MutableScenario; import org.matsim.core.scenario.ScenarioUtils; @@ -78,10 +78,10 @@ public class InvertedNetworkRoutingTestFixture { public InvertedNetworkRoutingTestFixture(boolean doCreateModes, boolean doCreateLanes, boolean doCreateSignals) { Config config = ConfigUtils.createConfig(); - config.controler().setLastIteration(0); - config.controler().setLinkToLinkRoutingEnabled(true); + config.controller().setLastIteration(0); + config.controller().setLinkToLinkRoutingEnabled(true); config.travelTimeCalculator().setCalculateLinkToLinkTravelTimes(true); - config.controler().setMobsim("qsim"); + config.controller().setMobsim("qsim"); config.global().setNumberOfThreads(1); config.qsim().setRemoveStuckVehicles(false); config.qsim().setStuckTime(10000.0); @@ -90,12 +90,12 @@ public InvertedNetworkRoutingTestFixture(boolean doCreateModes, boolean doCreate StrategySettings stratSets = new StrategySettings(Id.create(1, StrategySettings.class)); stratSets.setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.ReRoute.toString()); stratSets.setWeight(1.0); - config.strategy().addStrategySettings(stratSets); + config.replanning().addStrategySettings(stratSets); final double traveling = -1200.0; - config.planCalcScore().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(traveling); + config.scoring().getModes().get(TransportMode.car).setMarginalUtilityOfTraveling(traveling); ActivityParams params = new ActivityParams("home"); params.setTypicalDuration(24.0 * 3600.0); - config.planCalcScore().addActivityParams(params); + config.scoring().addActivityParams(params); config.qsim().setUseLanes(doCreateLanes); this.scenario = (MutableScenario) ScenarioUtils.createScenario(config); @@ -196,7 +196,7 @@ private void createNetwork() { l.setCapacity(3600.0); network.addLink(l); } - + private void createPopulation() { Population pop = this.scenario.getPopulation(); PopulationFactory f = pop.getFactory(); diff --git a/matsim/src/test/java/org/matsim/integration/invertednetworks/LanesIT.java b/matsim/src/test/java/org/matsim/integration/invertednetworks/LanesIT.java index 5e5f2285367..f31ec3a810e 100644 --- a/matsim/src/test/java/org/matsim/integration/invertednetworks/LanesIT.java +++ b/matsim/src/test/java/org/matsim/integration/invertednetworks/LanesIT.java @@ -33,7 +33,7 @@ import org.matsim.core.api.experimental.events.EventsManager; 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.events.IterationEndsEvent; @@ -66,11 +66,11 @@ public void testLanes(){ config.network().setInputFile("network.xml"); config.network().setLaneDefinitionsFile("testLaneDefinitions_v2.0.xml"); config.plans().setInputFile("population.xml"); - config.controler().setRoutingAlgorithmType(ControlerConfigGroup.RoutingAlgorithmType.Dijkstra); - config.controler().setOutputDirectory(testUtils.getOutputDirectory() + "output"); + config.controller().setRoutingAlgorithmType(ControllerConfigGroup.RoutingAlgorithmType.Dijkstra); + config.controller().setOutputDirectory(testUtils.getOutputDirectory() + "output"); final int lastIteration = 50; - config.controler().setLastIteration(lastIteration); - config.controler().setCreateGraphs(false); + config.controller().setLastIteration(lastIteration); + config.controller().setCreateGraphs(false); config.vspExperimental().setWritingOutputEvents(false); config.travelTimeCalculator().setSeparateModes( false ); // --- diff --git a/matsim/src/test/java/org/matsim/integration/population/NonAlternatingPlanElementsIT.java b/matsim/src/test/java/org/matsim/integration/population/NonAlternatingPlanElementsIT.java index a06e6aebf07..5c317f24862 100644 --- a/matsim/src/test/java/org/matsim/integration/population/NonAlternatingPlanElementsIT.java +++ b/matsim/src/test/java/org/matsim/integration/population/NonAlternatingPlanElementsIT.java @@ -55,7 +55,7 @@ /** * Tests that a simple simulation can be run with plans where * activities and legs are not always alternating. - * + * * @author mrieser / senozon */ public class NonAlternatingPlanElementsIT { @@ -65,11 +65,11 @@ public class NonAlternatingPlanElementsIT { @Test public void test_Controler_QSim_Routechoice_acts() { Config config = this.utils.loadConfig("test/scenarios/equil/config.xml"); - config.controler().setMobsim("qsim"); - config.controler().setLastIteration(10); + config.controller().setMobsim("qsim"); + config.controller().setLastIteration(10); config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); - config.strategy().addParam("Module_2", "ReRoute"); - config.strategy().addParam("ModuleProbability_2", "1.0"); + config.replanning().addParam("Module_2", "ReRoute"); + config.replanning().addParam("ModuleProbability_2", "1.0"); config.transit().setUseTransit(true); // a scenario is created to take only network from config file; rest inputs are ignored; @@ -87,8 +87,8 @@ public void test_Controler_QSim_Routechoice_acts() { scenario.getPopulation().addPerson(person); Controler controler = new Controler(scenario); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); controler.run(); Assert.assertTrue(person.getPlans().size() > 1); // ensure there was some replanning @@ -97,11 +97,11 @@ public void test_Controler_QSim_Routechoice_acts() { @Test public void test_Controler_QSim_Routechoice_legs() { Config config = this.utils.loadConfig("test/scenarios/equil/config.xml"); - config.controler().setMobsim("qsim"); - config.controler().setLastIteration(10); + config.controller().setMobsim("qsim"); + config.controller().setLastIteration(10); config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); - config.strategy().addParam("Module_2", "ReRoute"); - config.strategy().addParam("ModuleProbability_2", "1.0"); + config.replanning().addParam("Module_2", "ReRoute"); + config.replanning().addParam("ModuleProbability_2", "1.0"); config.transit().setUseTransit(true); // a scenario is created to take only network from config file; rest inputs are ignored; @@ -119,8 +119,8 @@ public void test_Controler_QSim_Routechoice_legs() { scenario.getPopulation().addPerson(person); Controler controler = new Controler(scenario); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); controler.run(); Assert.assertTrue(person.getPlans().size() > 1); // ensure there was some replanning @@ -129,9 +129,9 @@ public void test_Controler_QSim_Routechoice_legs() { // TODO: make more complicated plans when testing subtour mode choice private static Plan createPlanWithConsecutiveLegsForEquilNet(final Scenario scenario) { PopulationFactory pf = scenario.getPopulation().getFactory(); - + Plan plan = pf.createPlan(); - + Activity home1 = pf.createActivityFromLinkId("h", Id.create(1, Link.class)); final double x1 = -17000; ((Activity) home1).setCoord(new Coord(x1, (double) 500)); @@ -161,7 +161,7 @@ private static Plan createPlanWithConsecutiveLegsForEquilNet(final Scenario scen Activity home2 = pf.createActivityFromLinkId("h", Id.create(1, Link.class)); final double x = -17000; ((Activity) home2).setCoord(new Coord(x, (double) 500)); - + plan.addActivity(home1); plan.addLeg(leg1); plan.addLeg(leg2); @@ -169,15 +169,15 @@ private static Plan createPlanWithConsecutiveLegsForEquilNet(final Scenario scen plan.addActivity(work); plan.addLeg(leg4); plan.addActivity(home2); - + return plan; } private static Plan createPlanWithConsecutiveActivitiesForEquilNet(final Scenario scenario) { PopulationFactory pf = scenario.getPopulation().getFactory(); - + Plan plan = pf.createPlan(); - + Activity home1 = pf.createActivityFromLinkId("h", Id.create(1, Link.class)); final double x3 = -17000; ((Activity) home1).setCoord(new Coord(x3, (double) 500)); @@ -214,7 +214,7 @@ private static Plan createPlanWithConsecutiveActivitiesForEquilNet(final Scenari Activity home4 = pf.createActivityFromLinkId("h", Id.create(1, Link.class)); final double x = -17000; ((Activity) home2).setCoord(new Coord(x, (double) 500)); - + plan.addActivity(home1); plan.addLeg(leg1); plan.addActivity(work); @@ -223,12 +223,12 @@ private static Plan createPlanWithConsecutiveActivitiesForEquilNet(final Scenari plan.addActivity(home2); plan.addActivity(home3); plan.addActivity(home4); - + return plan; } private void addSimpleTransitServices(Scenario scenario) { - + TransitSchedule schedule = scenario.getTransitSchedule(); TransitScheduleFactory f = schedule.getFactory(); final double x = -6000; @@ -239,7 +239,7 @@ private void addSimpleTransitServices(Scenario scenario) { stopFacility2.setLinkId(Id.create(21, Link.class)); schedule.addStopFacility(stopFacility1); schedule.addStopFacility(stopFacility2); - + TransitLine line1 = f.createTransitLine(Id.create(1, TransitLine.class)); NetworkRoute netRoute = RouteUtils.createLinkNetworkRouteImpl(Id.create("14", Link.class), new Id[] { Id.create("20", Link.class) }, Id.create("21", Link.class)); List stops = new ArrayList(); @@ -248,11 +248,11 @@ private void addSimpleTransitServices(Scenario scenario) { TransitRoute route1 = f.createTransitRoute(Id.create(1, TransitRoute.class), netRoute, stops, "bus"); line1.addRoute(route1); schedule.addTransitLine(line1); - + for (int i = 0; i < 20; i++) { route1.addDeparture(f.createDeparture(Id.create(i, Departure.class), 6.0 * 3600 + i * 600)); } - + new CreateVehiclesForSchedule(schedule, scenario.getTransitVehicles()).run(); } diff --git a/matsim/src/test/java/org/matsim/integration/pt/TransitIntegrationTest.java b/matsim/src/test/java/org/matsim/integration/pt/TransitIntegrationTest.java index 2936b6a464d..b6caa9f2372 100644 --- a/matsim/src/test/java/org/matsim/integration/pt/TransitIntegrationTest.java +++ b/matsim/src/test/java/org/matsim/integration/pt/TransitIntegrationTest.java @@ -23,8 +23,8 @@ import org.junit.Test; 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.PlanCalcScoreConfigGroup.ScoringParameterSet; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ScoringParameterSet; import org.matsim.core.controler.Controler; import org.matsim.pt.PtConstants; import org.matsim.testcases.MatsimTestUtils; @@ -36,34 +36,34 @@ public class TransitIntegrationTest { @Test(expected = RuntimeException.class) public void testPtInteractionParams() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - PlanCalcScoreConfigGroup.ActivityParams params = new PlanCalcScoreConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + ScoringConfigGroup.ActivityParams params = new ScoringConfigGroup.ActivityParams(PtConstants.TRANSIT_ACTIVITY_TYPE); params.setScoringThisActivityAtAll(true); params.setTypicalDuration(60.0); - config.planCalcScore().addActivityParams(params); + config.scoring().addActivityParams(params); // --- - config.controler().setLastIteration(0); // in case the exception is _not_ thrown, we don't need 100 iterations to find that out ... + config.controller().setLastIteration(0); // in case the exception is _not_ thrown, we don't need 100 iterations to find that out ... // --- Controler controler = new Controler(config); controler.run(); } - - + + @Test(expected = RuntimeException.class) public void testSubpopulationParams() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(utils.getOutputDirectory()); - PlanCalcScoreConfigGroup.ActivityParams params = new PlanCalcScoreConfigGroup.ActivityParams("home"); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + ScoringConfigGroup.ActivityParams params = new ScoringConfigGroup.ActivityParams("home"); params.setScoringThisActivityAtAll(true); params.setTypicalDuration(60.0); - ScoringParameterSet sps = config.planCalcScore().getOrCreateScoringParameters("one"); + ScoringParameterSet sps = config.scoring().getOrCreateScoringParameters("one"); sps.addActivityParams(params); - ScoringParameterSet sps2 = config.planCalcScore().getOrCreateScoringParameters("two"); + ScoringParameterSet sps2 = config.scoring().getOrCreateScoringParameters("two"); sps2.addActivityParams(params); // --- - config.controler().setLastIteration(0); // in case the exception is _not_ thrown, we don't need 100 iterations to find that out ... + config.controller().setLastIteration(0); // in case the exception is _not_ thrown, we don't need 100 iterations to find that out ... config.checkConsistency(); - + Controler controler = new Controler(config); controler.run(); } diff --git a/matsim/src/test/java/org/matsim/integration/replanning/ChangeTripModeIntegrationTest.java b/matsim/src/test/java/org/matsim/integration/replanning/ChangeTripModeIntegrationTest.java index f7576dc5d95..7672fd7769b 100644 --- a/matsim/src/test/java/org/matsim/integration/replanning/ChangeTripModeIntegrationTest.java +++ b/matsim/src/test/java/org/matsim/integration/replanning/ChangeTripModeIntegrationTest.java @@ -37,7 +37,7 @@ import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; 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.AbstractModule; import org.matsim.core.controler.Injector; import org.matsim.core.controler.NewControlerModule; @@ -81,7 +81,7 @@ public class ChangeTripModeIntegrationTest { final StrategySettings strategySettings = new StrategySettings(Id.create("1", StrategySettings.class)); strategySettings.setStrategyName("ChangeTripMode"); strategySettings.setWeight(1.0); - config.strategy().addStrategySettings(strategySettings); + config.replanning().addStrategySettings(strategySettings); // config.setParam("changeMode", "modes", "car,walk"); String[] str = {"car","walk"} ; config.changeMode().setModes(str); diff --git a/matsim/src/test/java/org/matsim/integration/replanning/ReRoutingIT.java b/matsim/src/test/java/org/matsim/integration/replanning/ReRoutingIT.java index d338fb590d2..19a67fdd437 100644 --- a/matsim/src/test/java/org/matsim/integration/replanning/ReRoutingIT.java +++ b/matsim/src/test/java/org/matsim/integration/replanning/ReRoutingIT.java @@ -32,8 +32,8 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup.EventsFileFormat; -import org.matsim.core.config.groups.ControlerConfigGroup.RoutingAlgorithmType; +import org.matsim.core.config.groups.ControllerConfigGroup.EventsFileFormat; +import org.matsim.core.config.groups.ControllerConfigGroup.RoutingAlgorithmType; import org.matsim.core.controler.Controler; import org.matsim.core.gbl.Gbl; import org.matsim.core.population.PopulationUtils; @@ -54,21 +54,21 @@ private Scenario loadScenario() { config.qsim().setTimeStepSize(10.0); config.qsim().setStuckTime(100.0); config.qsim().setRemoveStuckVehicles(true); - config.controler().setEventsFileFormats(EnumSet.of(EventsFileFormat.xml)); - config.controler().setLastIteration(1); - /* linear interpolate the into time bins aggregated travel time data to avoid artifacts at the boundaries of time bins: + config.controller().setEventsFileFormats(EnumSet.of(EventsFileFormat.xml)); + config.controller().setLastIteration(1); + /* linear interpolate the into time bins aggregated travel time data to avoid artifacts at the boundaries of time bins: * e.g. a first time bin with aggregated travel time of 90 seconds and a second time bin with 45 seconds; time bin size 60; - * i.e. consolidateData-method in TravelTimeCalculator will accept this difference; imagine an requested route starting 2 + * i.e. consolidateData-method in TravelTimeCalculator will accept this difference; imagine an requested route starting 2 * seconds before the end of the first time bin, another route starts 2 seconds after the start of the second time bin; then - * the second one will arrive 41 seconds earlier than the first. Depending on the algorithm, some routers will detect this, - * some not (see MATSim-730), which is why we decided to test the linear interpolated travel time data here (which does not + * the second one will arrive 41 seconds earlier than the first. Depending on the algorithm, some routers will detect this, + * some not (see MATSim-730), which is why we decided to test the linear interpolated travel time data here (which does not * contain this artifacts). theresa, sep'17 * */ config.travelTimeCalculator().setTravelTimeGetterType("linearinterpolation"); /* * The input plans file is not sorted. After switching from TreeMap to LinkedHashMap - * to store the persons in the population, we have to sort the population manually. + * to store the persons in the population, we have to sort the population manually. * cdobler, oct'11 */ Scenario scenario = ScenarioUtils.loadScenario(config); @@ -79,21 +79,10 @@ private Scenario loadScenario() { @Test public void testReRoutingDijkstra() throws MalformedURLException { Scenario scenario = this.loadScenario(); - scenario.getConfig().controler().setRoutingAlgorithmType(RoutingAlgorithmType.Dijkstra); + scenario.getConfig().controller().setRoutingAlgorithmType(RoutingAlgorithmType.Dijkstra); Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.run(); - this.evaluate(); - } - - @Test - public void testReRoutingFastDijkstra() throws MalformedURLException { - Scenario scenario = this.loadScenario(); - scenario.getConfig().controler().setRoutingAlgorithmType(RoutingAlgorithmType.FastDijkstra); - Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); this.evaluate(); } @@ -101,21 +90,10 @@ public void testReRoutingFastDijkstra() throws MalformedURLException { @Test public void testReRoutingAStarLandmarks() throws MalformedURLException { Scenario scenario = this.loadScenario(); - scenario.getConfig().controler().setRoutingAlgorithmType(RoutingAlgorithmType.AStarLandmarks); + scenario.getConfig().controller().setRoutingAlgorithmType(RoutingAlgorithmType.AStarLandmarks); Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.run(); - this.evaluate(); - } - - @Test - public void testReRoutingFastAStarLandmarks() throws MalformedURLException { - Scenario scenario = this.loadScenario(); - scenario.getConfig().controler().setRoutingAlgorithmType(RoutingAlgorithmType.FastAStarLandmarks); - Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); this.evaluate(); } @@ -123,10 +101,10 @@ public void testReRoutingFastAStarLandmarks() throws MalformedURLException { @Test public void testReRoutingSpeedyALT() throws MalformedURLException { Scenario scenario = this.loadScenario(); - scenario.getConfig().controler().setRoutingAlgorithmType(RoutingAlgorithmType.SpeedyALT); + scenario.getConfig().controller().setRoutingAlgorithmType(RoutingAlgorithmType.SpeedyALT); Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); controler.run(); this.evaluate("plans_speedyALT.xml.gz"); } @@ -154,5 +132,5 @@ private void evaluate(String plansFilename) throws MalformedURLException { } Assert.assertTrue("different plans files.", isEqual); } - -} \ No newline at end of file + +} diff --git a/matsim/src/test/java/org/matsim/integration/replanning/ResumableRunsIT.java b/matsim/src/test/java/org/matsim/integration/replanning/ResumableRunsIT.java index 67583d66662..ee859ca7b41 100644 --- a/matsim/src/test/java/org/matsim/integration/replanning/ResumableRunsIT.java +++ b/matsim/src/test/java/org/matsim/integration/replanning/ResumableRunsIT.java @@ -58,32 +58,32 @@ public class ResumableRunsIT { @Test public void testResumableRuns() throws MalformedURLException { Config config = utils.loadConfig(IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "config.xml")); - config.controler().setLastIteration(11); - config.controler().setWriteEventsInterval(1); + config.controller().setLastIteration(11); + config.controller().setWriteEventsInterval(1); config.global().setNumberOfThreads(1); // only use one thread to rule out other disturbances for the test - config.controler().setWritePlansInterval(10); + config.controller().setWritePlansInterval(10); // run1 - config.controler().setOutputDirectory(utils.getOutputDirectory() + "/run1/"); + config.controller().setOutputDirectory(utils.getOutputDirectory() + "/run1/"); /* * The input plans file is not sorted. After switching from TreeMap to LinkedHashMap - * to store the persons in the population, we have to sort the population manually. + * to store the persons in the population, we have to sort the population manually. * cdobler, oct'11 */ Scenario scenario1 = ScenarioUtils.loadScenario(config); PopulationUtils.sortPersons(scenario1.getPopulation()); Controler controler1 = new Controler(scenario1); - controler1.getConfig().controler().setCreateGraphs(false); - controler1.getConfig().controler().setDumpDataAtEnd(false); + controler1.getConfig().controller().setCreateGraphs(false); + controler1.getConfig().controller().setDumpDataAtEnd(false); controler1.run(); // run2 - config.controler().setOutputDirectory(utils.getOutputDirectory() + "/run2/"); - config.controler().setFirstIteration(10); + config.controller().setOutputDirectory(utils.getOutputDirectory() + "/run2/"); + config.controller().setFirstIteration(10); config.plans().setInputFile(new File(utils.getOutputDirectory() + "/run1/ITERS/it.10/10.plans.xml.gz").toURI().toURL().toString()); Controler controler2 = new Controler(config); - controler2.getConfig().controler().setCreateGraphs(false); - controler2.getConfig().controler().setDumpDataAtEnd(false); + controler2.getConfig().controller().setCreateGraphs(false); + controler2.getConfig().controller().setDumpDataAtEnd(false); controler2.run(); // comparison diff --git a/matsim/src/test/java/org/matsim/modules/ScoreStatsModuleTest.java b/matsim/src/test/java/org/matsim/modules/ScoreStatsModuleTest.java index 97d7c60b958..4951ffdf3c7 100644 --- a/matsim/src/test/java/org/matsim/modules/ScoreStatsModuleTest.java +++ b/matsim/src/test/java/org/matsim/modules/ScoreStatsModuleTest.java @@ -37,7 +37,7 @@ import org.matsim.analysis.ScoreStats; import org.matsim.analysis.ScoreStatsControlerListener.ScoreItem; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.events.ShutdownEvent; @@ -75,9 +75,9 @@ public void testScoreStats() { Config config = utils.loadConfig("test/scenarios/equil/config.xml"); config.qsim().setUsingFastCapacityUpdate(this.isUsingFastCapacityUpdate); - config.plansCalcRoute().setAccessEgressType(this.isInsertingAccessEgressWalk? AccessEgressType.accessEgressModeToLink : AccessEgressType.none); + config.routing().setAccessEgressType(this.isInsertingAccessEgressWalk? AccessEgressType.accessEgressModeToLink : AccessEgressType.none); - config.controler().setLastIteration(1); + config.controller().setLastIteration(1); Controler controler = new Controler(config); controler.addOverridingModule(new AbstractModule() { @Override @@ -107,7 +107,7 @@ public void notifyShutdown(ShutdownEvent event) { // } // yy the following is retrofitted from an older double[][] data structure and thus messy. Please improve it. kai, nov'16 - if ( config.plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + if ( config.routing().getAccessEgressType().equals(AccessEgressType.none) ) { { Double[] array = result.get(ScoreItem.worst).values().toArray(new Double[0]) ; Assert.assertEquals(64.75686659291274, array[0], DELTA); diff --git a/matsim/src/test/java/org/matsim/population/algorithms/TripPlanMutateTimeAllocationTest.java b/matsim/src/test/java/org/matsim/population/algorithms/TripPlanMutateTimeAllocationTest.java deleted file mode 100644 index 4961b6887c0..00000000000 --- a/matsim/src/test/java/org/matsim/population/algorithms/TripPlanMutateTimeAllocationTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * 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.population.algorithms; - -import java.util.Random; - -import org.junit.Assert; -import org.junit.Test; -import org.matsim.api.core.v01.Coord; -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.Person; -import org.matsim.api.core.v01.population.Plan; -import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.core.population.PersonUtils; -import org.matsim.core.population.PopulationUtils; -import org.matsim.core.population.algorithms.TripPlanMutateTimeAllocation; -import org.matsim.pt.PtConstants; - -/** - * @author mrieser - */ -public class TripPlanMutateTimeAllocationTest { - - @Test - public void testRun() { - // setup population with one person - Person person = (Person) PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); - Plan plan = PersonUtils.createAndAddPlan(person, true); - Activity act = PopulationUtils.createAndAddActivityFromCoord(plan, "home", new Coord((double) 0, (double) 0)); - act.setEndTime(8.0 * 3600); - PopulationUtils.createAndAddLeg( plan, TransportMode.transit_walk ); - Activity ptAct1 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, new Coord((double) 0, (double) 100)); - ptAct1.setMaximumDuration(0); - PopulationUtils.createAndAddLeg( plan, TransportMode.pt ); - Activity ptAct2 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, new Coord((double) 0, (double) 100)); - ptAct2.setMaximumDuration(0); - PopulationUtils.createAndAddLeg( plan, TransportMode.transit_walk ); - act = PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord((double) 0, (double) 500)); - act.setEndTime(16*3600); - PopulationUtils.createAndAddLeg( plan, TransportMode.transit_walk ); - Activity ptAct3 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, new Coord((double) 0, (double) 100)); - ptAct3.setMaximumDuration(0); - PopulationUtils.createAndAddLeg( plan, TransportMode.pt ); - Activity ptAct4 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, new Coord((double) 0, (double) 100)); - ptAct4.setMaximumDuration(0); - PopulationUtils.createAndAddLeg( plan, TransportMode.transit_walk ); - PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord((double) 0, (double) 500)); - boolean affectingDuration = true ; - - TripPlanMutateTimeAllocation mutator = - new TripPlanMutateTimeAllocation( - 3600., - affectingDuration, new Random(2011)); - mutator.run(plan); - - Assert.assertEquals(0.0, ptAct1.getMaximumDuration().seconds(), 1e-8); - Assert.assertEquals(0.0, ptAct2.getMaximumDuration().seconds(), 1e-8); - Assert.assertEquals(0.0, ptAct3.getMaximumDuration().seconds(), 1e-8); - Assert.assertEquals(0.0, ptAct4.getMaximumDuration().seconds(), 1e-8); - } - - @Test - public void testRunLatestEndTime() { - // setup population with one person - Person person = (Person) PopulationUtils.getFactory().createPerson(Id.create(1, Person.class)); - Plan plan = PersonUtils.createAndAddPlan(person, true); - Activity act = PopulationUtils.createAndAddActivityFromCoord(plan, "home", new Coord((double) 0, (double) 0)); - act.setEndTime(8.0 * 3600); - PopulationUtils.createAndAddLeg(plan, TransportMode.transit_walk); - Activity ptAct1 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, - new Coord((double) 0, (double) 100)); - ptAct1.setMaximumDuration(0); - PopulationUtils.createAndAddLeg(plan, TransportMode.pt); - Activity ptAct2 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, - new Coord((double) 0, (double) 100)); - ptAct2.setMaximumDuration(0); - PopulationUtils.createAndAddLeg(plan, TransportMode.transit_walk); - act = PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord((double) 0, (double) 500)); - act.setEndTime(38 * 3600); - PopulationUtils.createAndAddLeg(plan, TransportMode.transit_walk); - Activity ptAct3 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, - new Coord((double) 0, (double) 100)); - ptAct3.setMaximumDuration(0); - PopulationUtils.createAndAddLeg(plan, TransportMode.pt); - Activity ptAct4 = PopulationUtils.createAndAddActivityFromCoord(plan, PtConstants.TRANSIT_ACTIVITY_TYPE, - new Coord((double) 0, (double) 100)); - ptAct4.setMaximumDuration(0); - PopulationUtils.createAndAddLeg(plan, TransportMode.transit_walk); - PopulationUtils.createAndAddActivityFromCoord(plan, "work", new Coord((double) 0, (double) 500)); - - boolean affectingDuration = true; - final double latestEndTime = 30. * 3600; - - TripPlanMutateTimeAllocation mutator = new TripPlanMutateTimeAllocation(3600., affectingDuration, - new Random(2011), null, null, latestEndTime); - mutator.run(plan); - - Assert.assertEquals(0.0, ptAct1.getMaximumDuration().seconds(), 1e-8); - Assert.assertEquals(0.0, ptAct2.getMaximumDuration().seconds(), 1e-8); - Assert.assertEquals(0.0, ptAct3.getMaximumDuration().seconds(), 1e-8); - Assert.assertEquals(0.0, ptAct4.getMaximumDuration().seconds(), 1e-8); - - // check whether activity times are equal or less than latestEndTime - for (PlanElement pe : plan.getPlanElements()) { - if (pe instanceof Activity activity) { - if (activity.getStartTime().isDefined()) { - Assert.assertTrue(activity.getStartTime().seconds() <= latestEndTime); - } - if (activity.getEndTime().isDefined()) { - Assert.assertTrue(activity.getEndTime().seconds() <= latestEndTime); - } - } - } - } -} diff --git a/matsim/src/test/java/org/matsim/pt/analysis/TransitLoadIntegrationTest.java b/matsim/src/test/java/org/matsim/pt/analysis/TransitLoadIntegrationTest.java index 69dd39711d0..298664f0f7f 100644 --- a/matsim/src/test/java/org/matsim/pt/analysis/TransitLoadIntegrationTest.java +++ b/matsim/src/test/java/org/matsim/pt/analysis/TransitLoadIntegrationTest.java @@ -46,7 +46,7 @@ public class TransitLoadIntegrationTest { @Test public void testIntegration() { final Config cfg = this.util.loadConfig("test/scenarios/pt-tutorial/0.config.xml"); - cfg.controler().setLastIteration(0); + cfg.controller().setLastIteration(0); cfg.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier); final Scenario s = ScenarioUtils.loadScenario(cfg); final Controler c = new Controler(s); @@ -59,10 +59,10 @@ public void notifyStartup(StartupEvent event) { } }); - cfg.controler().setWritePlansInterval(0); - c.getConfig().controler().setCreateGraphs(false); - c.getConfig().controler().setWriteEventsInterval(0); - c.getConfig().controler().setDumpDataAtEnd(false); + cfg.controller().setWritePlansInterval(0); + c.getConfig().controller().setCreateGraphs(false); + c.getConfig().controller().setWriteEventsInterval(0); + c.getConfig().controller().setDumpDataAtEnd(false); c.run(); TransitLine line = s.getTransitSchedule().getTransitLines().get(Id.create("Blue Line", TransitLine.class)); diff --git a/matsim/src/test/java/org/matsim/pt/counts/OccupancyAnalyzerTest.java b/matsim/src/test/java/org/matsim/pt/counts/OccupancyAnalyzerTest.java deleted file mode 100644 index 85fdcd5b79d..00000000000 --- a/matsim/src/test/java/org/matsim/pt/counts/OccupancyAnalyzerTest.java +++ /dev/null @@ -1,214 +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.pt.counts; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Set; -import javax.xml.parsers.ParserConfigurationException; -import org.junit.Assert; -import org.junit.Test; -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.network.Network; -import org.matsim.api.core.v01.network.Node; -import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.config.Config; -import org.matsim.core.config.ConfigUtils; -import org.matsim.core.controler.PrepareForSimUtils; -import org.matsim.core.events.EventsUtils; -import org.matsim.core.mobsim.qsim.QSimBuilder; -import org.matsim.core.population.io.PopulationReader; -import org.matsim.core.scenario.MutableScenario; -import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.pt.transitSchedule.TransitScheduleReaderV1; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.vehicles.MatsimVehicleReader; -import org.xml.sax.SAXException; - -/** - * @author mrieser / senozon - */ -public class OccupancyAnalyzerTest { - - @Test - public void test_SinglePersonOccupancy() throws SAXException, ParserConfigurationException, IOException { - Fixture f = new Fixture(); - String scheduleXml = "" + - "" + - "" + - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " train" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - ""; - new TransitScheduleReaderV1(f.scenario).parse(new ByteArrayInputStream(scheduleXml.getBytes())); - - String plansXml = "" + - "" + - "" + - "" + - " " + - " " + - " " + - " PT1===2===A===Aa===4" + - " " + - " " + - " " + - "" + - "" + - " " + - " " + - " " + - " " + - " " + - " " + - "" + - ""; - new PopulationReader(f.scenario).parse(new ByteArrayInputStream(plansXml.getBytes())); - - EventsManager eventsManager = EventsUtils.createEventsManager(); - OccupancyAnalyzer oa = new OccupancyAnalyzer(3600, 12*3600); - eventsManager.addHandler(oa); - - PrepareForSimUtils.createDefaultPrepareForSim(f.scenario).run(); - new QSimBuilder(f.scenario.getConfig()) // - .useDefaults() // - .build(f.scenario, eventsManager) // - .run(); - - Set> enterStops = oa.getBoardStopIds(); - Assert.assertEquals(1, enterStops.size()); - Assert.assertTrue(enterStops.contains(Id.create(2, TransitStopFacility.class))); - - Set> exitStops = oa.getAlightStopIds(); - Assert.assertEquals(1, exitStops.size()); - Assert.assertTrue(exitStops.contains(Id.create(4, TransitStopFacility.class))); - - int[] occupancy = oa.getOccupancyVolumesForStop(Id.create(1, TransitStopFacility.class)); - Assert.assertEquals(0, occupancy[6]); - occupancy = oa.getOccupancyVolumesForStop(Id.create(2, TransitStopFacility.class)); - Assert.assertEquals(1, occupancy[6]); - occupancy = oa.getOccupancyVolumesForStop(Id.create(3, TransitStopFacility.class)); - Assert.assertEquals(1, occupancy[6]); - occupancy = oa.getOccupancyVolumesForStop(Id.create(4, TransitStopFacility.class)); - Assert.assertEquals(0, occupancy[6]); - - Assert.assertEquals(0, oa.getBoardVolumesForStop(Id.create(1, TransitStopFacility.class))[6]); - Assert.assertEquals(1, oa.getBoardVolumesForStop(Id.create(2, TransitStopFacility.class))[6]); - Assert.assertEquals(0, oa.getBoardVolumesForStop(Id.create(3, TransitStopFacility.class))[6]); - Assert.assertEquals(0, oa.getBoardVolumesForStop(Id.create(4, TransitStopFacility.class))[6]); - - Assert.assertEquals(0, oa.getAlightVolumesForStop(Id.create(1, TransitStopFacility.class))[6]); - Assert.assertEquals(0, oa.getAlightVolumesForStop(Id.create(2, TransitStopFacility.class))[6]); - Assert.assertEquals(0, oa.getAlightVolumesForStop(Id.create(3, TransitStopFacility.class))[6]); - Assert.assertEquals(1, oa.getAlightVolumesForStop(Id.create(4, TransitStopFacility.class))[6]); - } - - private static class Fixture { - public final MutableScenario scenario; - public Fixture() throws SAXException, ParserConfigurationException, IOException { - // setup: config - final Config config = ConfigUtils.createConfig(); - config.transit().setUseTransit(true); - config.qsim().setEndTime(8.0*3600); - - this.scenario = (MutableScenario) ScenarioUtils.createScenario(config); - - // setup: network - Network network = this.scenario.getNetwork(); - Node node1 = network.getFactory().createNode(Id.create("1", Node.class), new Coord(0, 0)); - Node node2 = network.getFactory().createNode(Id.create("2", Node.class), new Coord(1000, 0)); - Node node3 = network.getFactory().createNode(Id.create("3", Node.class), new Coord(2000, 0)); - Node node4 = network.getFactory().createNode(Id.create("4", Node.class), new Coord(3000, 0)); - Node node5 = network.getFactory().createNode(Id.create("5", Node.class), new Coord(4000, 0)); - Node node6 = network.getFactory().createNode(Id.create("6", Node.class), new Coord(5000, 0)); - network.addNode(node1); - network.addNode(node2); - network.addNode(node3); - network.addNode(node4); - network.addNode(node5); - network.addNode(node6); - Link link1 = network.getFactory().createLink(Id.create("1", Link.class), node1, node2); - Link link2 = network.getFactory().createLink(Id.create("2", Link.class), node2, node3); - Link link3 = network.getFactory().createLink(Id.create("3", Link.class), node3, node4); - Link link4 = network.getFactory().createLink(Id.create("4", Link.class), node4, node5); - Link link5 = network.getFactory().createLink(Id.create("5", Link.class), node5, node6); - setDefaultLinkAttributes(link1); - setDefaultLinkAttributes(link2); - setDefaultLinkAttributes(link3); - setDefaultLinkAttributes(link4); - setDefaultLinkAttributes(link5); - network.addLink(link1); - network.addLink(link2); - network.addLink(link3); - network.addLink(link4); - network.addLink(link5); - - // setup: vehicles - String vehiclesXml = "" + - "" + - " " + - " Small Train" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - ""; - new MatsimVehicleReader(this.scenario.getTransitVehicles()).readStream(new ByteArrayInputStream(vehiclesXml.getBytes()) ); - } - - private void setDefaultLinkAttributes(final Link link) { - link.setLength(1000.0); - link.setFreespeed(10.0); - link.setCapacity(3600.0); - link.setNumberOfLanes(1); - } - } -} diff --git a/matsim/src/test/java/org/matsim/pt/counts/PtAlightCountsComparisonAlgorithmTest.java b/matsim/src/test/java/org/matsim/pt/counts/PtAlightCountsComparisonAlgorithmTest.java deleted file mode 100644 index 4bcc4780526..00000000000 --- a/matsim/src/test/java/org/matsim/pt/counts/PtAlightCountsComparisonAlgorithmTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtBoardCountsComparisonAlgorithmTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007 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.pt.counts; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.junit.Rule; -import org.junit.Test; -import org.matsim.counts.CountSimComparison; -import org.matsim.counts.algorithms.CountsComparisonAlgorithm; -import org.matsim.testcases.MatsimTestUtils; - - -public class PtAlightCountsComparisonAlgorithmTest { - - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); - - - - @Test public void testCompare() { - PtCountsFixture fixture = new PtAlightCountsFixture(); - fixture.setUp(); - - CountsComparisonAlgorithm cca = fixture.getCCA(); - cca.run(); - - List csc_list = cca.getComparison(); - - int cnt = 0; - for (CountSimComparison csc : csc_list) { - if (cnt != 8 && cnt!=32) { - assertEquals("Wrong sim value set", 0d, csc.getSimulationValue(), 0d); - } else if(cnt==8) { - assertEquals("Wrong sim value set", 500d, csc.getSimulationValue(), 0d); - }else{ - assertEquals("Wrong sim value set", 150d, csc.getSimulationValue(), 0d); - } - cnt++; - } - } - - - @Test public void testDistanceFilter() { - final PtCountsFixture fixture = new PtAlightCountsFixture(); - fixture.setUp(); - CountsComparisonAlgorithm cca = fixture.getCCA(); - - cca.setCountCoordUsingDistanceFilter(4000.0, "11"); - cca.run(); - - List csc_list = cca.getComparison(); - assertEquals("Distance filter not working", 24, csc_list.size()); - } -} diff --git a/matsim/src/test/java/org/matsim/pt/counts/PtAlightCountsFixture.java b/matsim/src/test/java/org/matsim/pt/counts/PtAlightCountsFixture.java deleted file mode 100644 index 45073f883cc..00000000000 --- a/matsim/src/test/java/org/matsim/pt/counts/PtAlightCountsFixture.java +++ /dev/null @@ -1,68 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtBoardCountsFixture.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2010 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.pt.counts; - -import java.util.HashMap; -import java.util.Map; - -import org.matsim.api.core.v01.Id; -import org.matsim.counts.algorithms.CountsComparisonAlgorithm; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -public class PtAlightCountsFixture extends PtCountsFixture { - - public PtAlightCountsFixture() { - super("inputAlightCountsFile"); - } - - @Override - public CountsComparisonAlgorithm getCCA() { - Map, int[]> alights = new HashMap<>(); - - int[] alightArrayStop3 = new int[24]; - alightArrayStop3[8] = 50; - alights.put(Id.create("stop3", TransitStopFacility.class), alightArrayStop3); - - int[] alightArrayStop4 = new int[24]; - alightArrayStop4[8] = 15; - alights.put(Id.create("stop4", TransitStopFacility.class), alightArrayStop4); - - this.oa.setAlights(alights); - CountsComparisonAlgorithm cca = new CountsComparisonAlgorithm(new CountsComparisonAlgorithm.VolumesForId() { - - @Override - public double[] getVolumesForStop(Id locationId) { - return copyFromIntArray(oa.getAlightVolumesForStop(locationId)); - } - - }, counts, network, Double.parseDouble(config.findParam(MODULE_NAME, "countsScaleFactor"))); - cca.setCountCoordUsingDistanceFilter(Double.valueOf(config.findParam(MODULE_NAME,"distanceFilter")), config.findParam(MODULE_NAME, "distanceFilterCenterNode")); - return cca; - } - - private static double[] copyFromIntArray(int[] source) { - double[] dest = new double[source.length]; - for(int i=0; i csc_list = cca.getComparison(); - - int cnt = 0; - for (CountSimComparison csc : csc_list) { - if (cnt != 8) { - assertEquals("Wrong sim value set", 0d, csc.getSimulationValue(), 0d); - } else { - assertEquals("Wrong sim value set", 650d, csc.getSimulationValue(), 0d); - } - cnt++; - } - } - - - @Test public void testDistanceFilter() { - PtCountsFixture fixture = new PtBoardCountsFixture(); - fixture.setUp(); - - CountsComparisonAlgorithm cca = fixture.getCCA(); - cca.setCountCoordUsingDistanceFilter(Double.valueOf(5000), "11"); - cca.run(); - - List csc_list = cca.getComparison(); - assertEquals("Distance filter not working", 24, csc_list.size()); - } -} diff --git a/matsim/src/test/java/org/matsim/pt/counts/PtBoardCountsFixture.java b/matsim/src/test/java/org/matsim/pt/counts/PtBoardCountsFixture.java deleted file mode 100644 index 80b65cf8139..00000000000 --- a/matsim/src/test/java/org/matsim/pt/counts/PtBoardCountsFixture.java +++ /dev/null @@ -1,63 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtBoardCountsFixture.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2010 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.pt.counts; - -import java.util.HashMap; -import java.util.Map; - -import org.matsim.api.core.v01.Id; -import org.matsim.counts.algorithms.CountsComparisonAlgorithm; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -public class PtBoardCountsFixture extends PtCountsFixture { - - public PtBoardCountsFixture() { - super("inputBoardCountsFile"); - } - - @Override - public CountsComparisonAlgorithm getCCA() { - Map, int[]> boards = new HashMap<>(); - int[] boardArray = new int[24]; - boardArray[8] = 65; - boards.put(Id.create("stop1", TransitStopFacility.class), boardArray); - this.oa.setBoards(boards); - CountsComparisonAlgorithm cca = new CountsComparisonAlgorithm(new CountsComparisonAlgorithm.VolumesForId() { - - @Override - public double[] getVolumesForStop(Id locationId) { - return copyFromIntArray(oa.getBoardVolumesForStop(locationId)); - } - - }, counts, network, Double.parseDouble(config.findParam(MODULE_NAME, "countsScaleFactor"))); - cca.setDistanceFilter(Double.valueOf(config.findParam(MODULE_NAME,"distanceFilter")), config.findParam(MODULE_NAME,"distanceFilterCenterNode")); - return cca; - } - - - private static double[] copyFromIntArray(int[] source) { - double[] dest = new double[source.length]; - for(int i=0; i ceateCountSimCompList() { - List csc_l = new Vector(24); - for (int i = 0; i < 24; i++) { - csc_l.add(new CountSimComparisonImpl(Id.create(100, Link.class), "", i + 1, 1.0,1.0)); - } - return csc_l; - } -} diff --git a/matsim/src/test/java/org/matsim/pt/counts/PtCountsLoadCurveGraphTest.java b/matsim/src/test/java/org/matsim/pt/counts/PtCountsLoadCurveGraphTest.java deleted file mode 100644 index 6c888007de3..00000000000 --- a/matsim/src/test/java/org/matsim/pt/counts/PtCountsLoadCurveGraphTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtCountsLoadCurveGraphTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007 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.pt.counts; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Rule; -import org.junit.Test; -import org.matsim.counts.algorithms.graphs.CountsLoadCurveGraph; -import org.matsim.testcases.MatsimTestUtils; - -public class PtCountsLoadCurveGraphTest { - - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); - - - @Test public void testCreateBoardChart() { - PtCountsFixture fixture = new PtBoardCountsFixture(); - fixture.setUp(); - - CountsLoadCurveGraph eg = new CountsLoadCurveGraph(fixture - .ceateCountSimCompList(), 1, "testCreateChart"); - assertNotNull("No graph is created", eg.createChart(0)); - } - - - @Test public void testCreateAlightChart() { - PtCountsFixture fixture = new PtAlightCountsFixture(); - fixture.setUp(); - - CountsLoadCurveGraph eg = new CountsLoadCurveGraph(fixture - .ceateCountSimCompList(), 1, "testCreateChart"); - assertNotNull("No graph is created", eg.createChart(0)); - } - - - @Test public void testCreateOccupancyChart() { - PtCountsFixture fixture = new PtOccupancyCountsFixture(); - fixture.setUp(); - - CountsLoadCurveGraph eg = new CountsLoadCurveGraph(fixture - .ceateCountSimCompList(), 1, "testCreateChart"); - assertNotNull("No graph is created", eg.createChart(0)); - } -} diff --git a/matsim/src/test/java/org/matsim/pt/counts/PtCountsSimRealPerHourGraphTest.java b/matsim/src/test/java/org/matsim/pt/counts/PtCountsSimRealPerHourGraphTest.java deleted file mode 100644 index 147c430b567..00000000000 --- a/matsim/src/test/java/org/matsim/pt/counts/PtCountsSimRealPerHourGraphTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtCountsSimRealPerHourGraphTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007 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.pt.counts; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Rule; -import org.junit.Test; -import org.matsim.pt.counts.obsolete.PtCountSimComparisonWriter.PtCountsType; -import org.matsim.pt.counts.obsolete.PtCountsSimRealPerHourGraph; -import org.matsim.testcases.MatsimTestUtils; - -public class PtCountsSimRealPerHourGraphTest { - - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); - - - - @Test public void testCreatBoardChart() { - PtCountsFixture fixture = new PtBoardCountsFixture(); - fixture.setUp(); - - PtCountsSimRealPerHourGraph eg = new PtCountsSimRealPerHourGraph(fixture.ceateCountSimCompList(), 1, "testCreateChart", PtCountsType.Boarding); - assertNotNull("No graph is created", eg.createChart(0)); - } - - - @Test public void testCreatAlightChart() { - PtCountsFixture fixture = new PtAlightCountsFixture(); - fixture.setUp(); - - PtCountsSimRealPerHourGraph eg = new PtCountsSimRealPerHourGraph(fixture.ceateCountSimCompList(), 1, "testCreateChart", PtCountsType.Alighting); - assertNotNull("No graph is created", eg.createChart(0)); - } - - - @Test public void testCreatOccupancyChart() { - PtCountsFixture fixture = new PtOccupancyCountsFixture(); - fixture.setUp(); - - PtCountsSimRealPerHourGraph eg = new PtCountsSimRealPerHourGraph(fixture.ceateCountSimCompList(), 1, "testCreateChart", PtCountsType.Occupancy); - assertNotNull("No graph is created", eg.createChart(0)); - } -} diff --git a/matsim/src/test/java/org/matsim/pt/counts/PtOccupancyCountsComparisonAlgorithmTest.java b/matsim/src/test/java/org/matsim/pt/counts/PtOccupancyCountsComparisonAlgorithmTest.java deleted file mode 100644 index ba4f59d8e0d..00000000000 --- a/matsim/src/test/java/org/matsim/pt/counts/PtOccupancyCountsComparisonAlgorithmTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtBoardCountsComparisonAlgorithmTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2007 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.pt.counts; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.junit.Rule; -import org.junit.Test; -import org.matsim.counts.CountSimComparison; -import org.matsim.counts.algorithms.CountsComparisonAlgorithm; -import org.matsim.testcases.MatsimTestUtils; - -public class PtOccupancyCountsComparisonAlgorithmTest { - - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); - - - - @Test public void testCompare() { - PtCountsFixture fixture = new PtOccupancyCountsFixture(); - fixture.setUp(); - - CountsComparisonAlgorithm cca = fixture.getCCA(); - cca.run(); - - List csc_list = cca.getComparison(); - - int cnt = 0; - for (CountSimComparison csc : csc_list) { - if (cnt != 8 && cnt != 32 && cnt != 56) { - assertEquals("Wrong sim value set", 0d, csc.getSimulationValue(), 0d); - } else if (cnt == 8 || cnt == 32) { - assertEquals("Wrong sim value set", 650d, csc.getSimulationValue(), 0d); - }else{ - assertEquals("Wrong sim value set", 150d, csc.getSimulationValue(), 0d); - } - cnt++; - } - } - - - @Test public void testDistanceFilter() { - PtCountsFixture fixture = new PtOccupancyCountsFixture(); - fixture.setUp(); - - CountsComparisonAlgorithm cca = fixture.getCCA(); - cca.setCountCoordUsingDistanceFilter(3000.0, "11"); - cca.run(); - - List csc_list = cca.getComparison(); - assertEquals("Distance filter not working", 72, csc_list.size()); - } -} diff --git a/matsim/src/test/java/org/matsim/pt/counts/PtOccupancyCountsFixture.java b/matsim/src/test/java/org/matsim/pt/counts/PtOccupancyCountsFixture.java deleted file mode 100644 index fbf17c7a35f..00000000000 --- a/matsim/src/test/java/org/matsim/pt/counts/PtOccupancyCountsFixture.java +++ /dev/null @@ -1,75 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * PtBoardCountsFixture.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2010 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.pt.counts; - -import java.util.HashMap; -import java.util.Map; - -import org.matsim.api.core.v01.Id; -import org.matsim.counts.algorithms.CountsComparisonAlgorithm; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -public class PtOccupancyCountsFixture extends PtCountsFixture { - - public PtOccupancyCountsFixture() { - super("inputOccupancyCountsFile"); - } - - @Override - public CountsComparisonAlgorithm getCCA() { - Map, int[]> occupancies = new HashMap<>(); - - int[] occupancyArrayStop1 = new int[24]; - occupancyArrayStop1[8] = 65; - occupancies.put(Id.create("stop1", TransitStopFacility.class), occupancyArrayStop1); - - int[] occupancyArrayStop2 = new int[24]; - occupancyArrayStop2[8] = 65; - occupancies.put(Id.create("stop2", TransitStopFacility.class), occupancyArrayStop2); - - int[] occupancyArrayStop3 = new int[24]; - occupancyArrayStop3[8] = 15; - occupancies.put(Id.create("stop3", TransitStopFacility.class), occupancyArrayStop3); - - int[] occupancyArrayStop4 = new int[24]; - occupancies.put(Id.create("stop4", TransitStopFacility.class), occupancyArrayStop4); - - this.oa.setOccupancies(occupancies); - CountsComparisonAlgorithm cca = new CountsComparisonAlgorithm(new CountsComparisonAlgorithm.VolumesForId() { - - @Override - public double[] getVolumesForStop(Id locationId) { - return copyFromIntArray(oa.getOccupancyVolumesForStop(locationId)); - } - - }, counts, network, Double.parseDouble(config.findParam(MODULE_NAME, "countsScaleFactor"))); - cca.setDistanceFilter(Double.valueOf(config.findParam(MODULE_NAME,"distanceFilter")), config.findParam(MODULE_NAME,"distanceFilterCenterNode")); - return cca; - } - - private static double[] copyFromIntArray(int[] source) { - double[] dest = new double[source.length]; - for(int i=0; i

        - * Comments:
          - *
        • As far as I can tell, it is not tested if other utility values for the out-of-vehicle wait times influences the results. - * This should/could be done in org.matsim.examples.simple.PtScoringTest . - * - * @author manuel after mrieser - */ - -public class AdaptedTransitRouterNetworkTravelTimeCostTest { - - @Test public void testTravelTime() { - //create the scenario test - Fixture f = new Fixture(); - f.init(); - - //create the adapted router - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule) ; - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - - // find the link connecting C and G on the red line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == f.redLine) && - (link.fromNode.stop.getStopFacility().getName().equals("C")) && - (link.toNode.stop.getStopFacility().getName().equals("G"))) { - testLink = link; - } - } - //at 6:00 the link travel time = 540 - assertEquals(9.0*60, tc.getLinkTravelTime(testLink, 6.0*3600, null, null), MatsimTestUtils.EPSILON); - } - - @Test public void testVehArrivalTime() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule) ; - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - - // find the link connecting C and D on the blue line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == f.blueLine) && (link.fromNode.stop.getStopFacility().getName().equals("C")) - && (link.toNode.stop.getStopFacility().getName().equals("D"))) { - testLink = link; - } - } - - //original MATSim. same as before - assertEquals(9.0*60 , tc.getLinkTravelTime(testLink, 6.0*3600, null, null) , MatsimTestUtils.EPSILON); - assertEquals(9.0*60+1 , tc.getLinkTravelTime(testLink, 6.0*3600-1, null, null) , MatsimTestUtils.EPSILON); - - /* - //if the agents arrives to stop (in or outside the veh) before 06:02, his/her "arrrival veh time" is 05:58 - //veh arrival time to stop= 05:58 - //veh departure from stop = 06:02 - //System.out.println("veh arr: " + timecost.getVehArrivalTime(testLink , (6.0*3600) + (1*60))); - //System.out.println("next departure: " + timecost.getNextDepartureTime(testLink.getRoute(), testLink.getFromNode().getStop(), (6.0*3600) + 60)); - */ - - //this arrival would be for waiting outside the vehicle at the stop - assertEquals((5.0*3600) + (58*60) , tc.getVehArrivalTime(testLink, (5.0*3600) + (56*60)), MatsimTestUtils.EPSILON); - assertEquals((5.0*3600) + (58*60) , tc.getVehArrivalTime(testLink, (5.0*3600) + (57*60)), MatsimTestUtils.EPSILON); - - //this arrival would be for waiting inside the vehicle - assertEquals((5.0*3600) + (58*60) , tc.getVehArrivalTime(testLink, (5.0*3600) + (58*60)), MatsimTestUtils.EPSILON); - assertEquals((5.0*3600) + (58*60) , tc.getVehArrivalTime(testLink, (5.0*3600) + (59*60)), MatsimTestUtils.EPSILON); - assertEquals((5.0*3600) + (58*60) , tc.getVehArrivalTime(testLink, (6.0*3600) + (1*60)), MatsimTestUtils.EPSILON); - assertEquals((5.0*3600) + (58*60) , tc.getVehArrivalTime(testLink, (6.0*3600) + (2*60)), MatsimTestUtils.EPSILON); - - //if the agents arrives after to stop after 06:02, his/her "arrrival veh time" is displaced to 06:18 - assertEquals((6.0*3600) + (18*60) , tc.getVehArrivalTime(testLink, (6.0*3600) + (3*60)), MatsimTestUtils.EPSILON); - } - - @Test public void testTravelTimeAfterMidnight() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule) ; - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - // find the link connecting C and D on the blue line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == f.blueLine) && - (link.fromNode.stop.getStopFacility().getName().equals("C")) && - (link.toNode.stop.getStopFacility().getName().equals("D"))) { - testLink = link; - } - } - - //original - // planned departure at 25:00, has to wait until 05:22 = 29:22 - assertEquals(22.0*60 + 4.0*3600 + 7.0*60, tc.getLinkTravelTime(testLink, 25.0*3600, null, null ), MatsimTestUtils.EPSILON); - //after adaption : next veh arrival is in 29:18 - assertEquals((29.0*3600) + (18*60.0) , tc.getVehArrivalTime(testLink, 25.0*3600), MatsimTestUtils.EPSILON); - - //original - // planned departure at 47:00, has to wait until 05:22 = 53:22 - assertEquals(22.0*60 + 6.0*3600 + 7.0*60, tc.getLinkTravelTime(testLink, 47.0*3600, null, null), MatsimTestUtils.EPSILON); - //after adaption : next veh arrival is in 53:18 - assertEquals((53.0*3600) + (18*60.0), tc.getVehArrivalTime(testLink, 47.0*3600), MatsimTestUtils.EPSILON); - - //original - // planned departure at 49:00, has to wait until 05:22 = 53:22, tests explicitly > 2*MIDNIGHT - assertEquals(22.0*60 + 4.0*3600 + 7.0*60, tc.getLinkTravelTime(testLink, 49.0*3600, null, null), MatsimTestUtils.EPSILON); - //after adaption : next veh arrival is in 53:18 - assertEquals((53.0*3600) + (18*60.0), tc.getVehArrivalTime(testLink, 49.0*3600), MatsimTestUtils.EPSILON); - } - - @Test public void testTravelCostLineSwitch() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule) ; - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - - // find the link connecting C and D on the blue line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == null) && - (link.fromNode.stop.getStopFacility().getName().equals("C")) && - (link.toNode.stop.getStopFacility().getName().equals("C"))) { - testLink = link; - } - } - - double oldCost = - conf.getUtilityOfLineSwitch_utl(); - double cost1 = tc.getLinkTravelDisutility(testLink, 7.0*3600, null, null, null); - conf.setUtilityOfLineSwitch_utl(0.0); - double cost2 = tc.getLinkTravelDisutility(testLink, 6.0*3600, null, null, null); // use different time because of internal caching effects - assertEquals(oldCost, cost1 - cost2, MatsimTestUtils.EPSILON); - conf.setUtilityOfLineSwitch_utl(-40.125); - double cost3 = tc.getLinkTravelDisutility(testLink, 5.0*3600, null, null, null); - assertEquals(40.125, cost3 - cost2, MatsimTestUtils.EPSILON); - } - - - @Test public void testTravelCostLineSwitch_AdditionalTransferTime() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule) ; - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - - // find the link connecting C and D on the blue line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == null) && - (link.fromNode.stop.getStopFacility().getName().equals("C")) && - (link.toNode.stop.getStopFacility().getName().equals("C"))) { - testLink = link; - } - } - - double oldCost = - conf.getUtilityOfLineSwitch_utl(); - double cost1 = tc.getLinkTravelDisutility(testLink, 7.0*3600, null, null, null); - conf.setUtilityOfLineSwitch_utl(0.0); - double cost2 = tc.getLinkTravelDisutility(testLink, 6.0*3600, null, null, null); // use different time because of internal caching effects - assertEquals(oldCost, cost1 - cost2, MatsimTestUtils.EPSILON); - conf.setAdditionalTransferTime(120.0); - double cost3 = tc.getLinkTravelDisutility(testLink, 5.0*3600, null, null, null); - assertEquals(-120.0 * conf.getMarginalUtilityOfWaitingPt_utl_s(), cost3 - cost2, MatsimTestUtils.EPSILON); - // test with custom value for utility of waiting, just in case too many of the default marginal utilities are 0.0 - conf.setMarginalUtilityOfWaitingPt_utl_s(-12.0 / 3600.0); - double cost4 = tc.getLinkTravelDisutility(testLink, 7.0*3600, null, null, null); - assertEquals(120.0 * 12.0 / 3600.0, cost4 - cost2, MatsimTestUtils.EPSILON); - } - - -} diff --git a/matsim/src/test/java/org/matsim/pt/router/MultiNodeDijkstraTest.java b/matsim/src/test/java/org/matsim/pt/router/MultiNodeDijkstraTest.java deleted file mode 100644 index 4136ce038ae..00000000000 --- a/matsim/src/test/java/org/matsim/pt/router/MultiNodeDijkstraTest.java +++ /dev/null @@ -1,493 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TransitDijkstraTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 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.pt.router; - -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -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.network.Network; -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.network.NetworkUtils; -import org.matsim.core.router.InitialNode; -import org.matsim.core.router.util.LeastCostPathCalculator.Path; -import org.matsim.core.router.util.TravelTime; -import org.matsim.vehicles.Vehicle; - -/** - * @author mrieser - */ -public class MultiNodeDijkstraTest { - - @Test public void testMultipleStarts() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 2.0, 2.0); - tc.setData(Id.create(5, Link.class), 1.0, 1.0); - tc.setData(Id.create(6, Link.class), 3.0, 3.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(1, Node.class)), new InitialNode(1.0, 1.0)); - fromNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(3.0, 3.0)); - fromNodes.put(f.network.getNodes().get(Id.create(3, Node.class)), new InitialNode(2.0, 2.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(5, Node.class)), new InitialNode(0.0, 0.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("1", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("5", p.links.get(2).getId().toString()); - - // change costs - tc.setData(Id.create(1, Link.class), 2.0, 5.0); - - p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("5", p.links.get(2).getId().toString()); - - // change costs again - tc.setData(Id.create(1, Link.class), 2.0, 1.0); - - p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("1", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("5", p.links.get(2).getId().toString()); - } - - @Test public void testMultipleEnds() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 4.0, 4.0); - tc.setData(Id.create(5, Link.class), 3.0, 3.0); - tc.setData(Id.create(6, Link.class), 7.0, 7.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(0.0, 0.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(4, Node.class)), new InitialNode(5.0, 5.0)); - toNodes.put(f.network.getNodes().get(Id.create(5, Node.class)), new InitialNode(4.0, 4.0)); - toNodes.put(f.network.getNodes().get(Id.create(6, Node.class)), new InitialNode(1.0, 1.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("5", p.links.get(2).getId().toString()); - - // change costs - tc.setData(Id.create(4, Link.class), 3.0, 1.0); - - p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("4", p.links.get(2).getId().toString()); - - // change costs again - tc.setData(Id.create(6, Link.class), 7.0, 3.0); - - p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("6", p.links.get(2).getId().toString()); - } - - @Test public void testMultipleStartsAndEnds() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 4.0, 4.0); - tc.setData(Id.create(5, Link.class), 3.0, 3.0); - tc.setData(Id.create(6, Link.class), 7.0, 7.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(4.0, 4.0)); - fromNodes.put(f.network.getNodes().get(Id.create(3, Node.class)), new InitialNode(3.0, 3.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(4, Node.class)), new InitialNode(5.0, 5.0)); - toNodes.put(f.network.getNodes().get(Id.create(5, Node.class)), new InitialNode(4.0, 4.0)); - toNodes.put(f.network.getNodes().get(Id.create(6, Node.class)), new InitialNode(1.0, 1.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("5", p.links.get(2).getId().toString()); - - // change costs - tc.setData(Id.create(3, Link.class), 3.0, 1.0); - tc.setData(Id.create(4, Link.class), 3.0, 1.0); - - p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("3", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("4", p.links.get(2).getId().toString()); - - // change costs again - tc.setData(Id.create(3, Link.class), 3.0, 4.0); - tc.setData(Id.create(6, Link.class), 7.0, 3.0); - - p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("6", p.links.get(2).getId().toString()); - } - - /** - * Both nodes 1 and 4 are part of the start set. Even if the path from 1 to the - * target leads over node 4, it may be faster, due to the intial cost values. - * Test that the route does not cut at node 4 as the first node backwards from - * the start set. - */ - @Test public void testStartViaFaster() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 2.0, 2.0); - tc.setData(Id.create(5, Link.class), 1.0, 1.0); - tc.setData(Id.create(6, Link.class), 3.0, 3.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(1, Node.class)), new InitialNode(1.0, 1.0)); - fromNodes.put(f.network.getNodes().get(Id.create(4, Node.class)), new InitialNode(4.0, 4.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(5, Node.class)), new InitialNode(0.0, 0.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("1", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("5", p.links.get(2).getId().toString()); - } - - @Test public void testEndViaFaster() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 2.0, 2.0); - tc.setData(Id.create(5, Link.class), 1.0, 1.0); - tc.setData(Id.create(6, Link.class), 3.0, 3.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(1.0, 1.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(8, Node.class)), new InitialNode(3.0, 3.0)); - toNodes.put(f.network.getNodes().get(Id.create(5, Node.class)), new InitialNode(1.0, 1.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("5", p.links.get(2).getId().toString()); - } - - @Test public void testOnlyFromToSameNode() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 2.0, 2.0); - tc.setData(Id.create(5, Link.class), 1.0, 1.0); - tc.setData(Id.create(6, Link.class), 3.0, 3.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(1.0, 1.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(3.0, 3.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(0, p.links.size()); - assertEquals(1, p.nodes.size()); - assertEquals("2", p.nodes.get(0).getId().toString()); - } - - /** - * Tests that a path is found if some links are in the set of start - * as well as in the set of end nodes and the path only containing - * of this node is the cheapest. - */ - @Test public void testSameNodeInFromToSetCheapest() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 2.0, 2.0); - tc.setData(Id.create(5, Link.class), 1.0, 1.0); - tc.setData(Id.create(6, Link.class), 3.0, 3.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(2.0, 2.0)); - fromNodes.put(f.network.getNodes().get(Id.create(4, Node.class)), new InitialNode(1.0, 1.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(4, Node.class)), new InitialNode(1.0, 1.0)); - toNodes.put(f.network.getNodes().get(Id.create(6, Node.class)), new InitialNode(3.0, 3.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(0, p.links.size()); - assertEquals(1, p.nodes.size()); - assertEquals("4", p.nodes.get(0).getId().toString()); - } - - /** - * Tests that a path is found if some links are in the set of start - * as well as in the set of end nodes, but the path only containing - * of this node is the not the cheapest. - */ - @Test public void testSameNodeInFromToSetNotCheapest() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 2.0, 2.0); - tc.setData(Id.create(5, Link.class), 1.0, 1.0); - tc.setData(Id.create(6, Link.class), 3.0, 3.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(2.0, 2.0)); - fromNodes.put(f.network.getNodes().get(Id.create(4, Node.class)), new InitialNode(10.0, 10.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(4, Node.class)), new InitialNode(8.0, 8.0)); - toNodes.put(f.network.getNodes().get(Id.create(6, Node.class)), new InitialNode(3.0, 3.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("6", p.links.get(2).getId().toString()); - } - - /** - * Tests that a route is found even if not all given end nodes are reachable - */ - @Test public void testSomeEndNodesNotReachable() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 2.0, 2.0); - tc.setData(Id.create(5, Link.class), 1.0, 1.0); - tc.setData(Id.create(6, Link.class), 3.0, 3.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(2.0, 2.0)); - fromNodes.put(f.network.getNodes().get(Id.create(1, Node.class)), new InitialNode(3.0, 3.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(5, Node.class)), new InitialNode(1.0, 1.0)); - toNodes.put(f.network.getNodes().get(Id.create(3, Node.class)), new InitialNode(3.0, 3.0)); // cannot be reached! - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("5", p.links.get(2).getId().toString()); - } - - /** - * Tests that a route is found even if not all given start nodes lead to an end node - */ - @Test public void testSomeStartNodesNotUseable() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 2.0, 2.0); - tc.setData(Id.create(5, Link.class), 1.0, 1.0); - tc.setData(Id.create(6, Link.class), 3.0, 3.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(2.0, 2.0)); - fromNodes.put(f.network.getNodes().get(Id.create(4, Node.class)), new InitialNode(3.0, 3.0)); // cannot lead to 5 or 6 - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(5, Node.class)), new InitialNode(1.0, 1.0)); - toNodes.put(f.network.getNodes().get(Id.create(6, Node.class)), new InitialNode(3.0, 3.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNotNull("no path found!", p); - assertEquals(3, p.links.size()); - assertEquals("2", p.links.get(0).getId().toString()); - assertEquals("7", p.links.get(1).getId().toString()); - assertEquals("5", p.links.get(2).getId().toString()); - } - - @Test public void testImpossibleRoute() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - tc.setData(Id.create(1, Link.class), 2.0, 2.0); - tc.setData(Id.create(2, Link.class), 1.0, 1.0); - tc.setData(Id.create(3, Link.class), 3.0, 3.0); - tc.setData(Id.create(4, Link.class), 2.0, 2.0); - tc.setData(Id.create(5, Link.class), 1.0, 1.0); - tc.setData(Id.create(6, Link.class), 3.0, 3.0); - tc.setData(Id.create(7, Link.class), 4.0, 4.0); - MultiNodeDijkstra dijkstra = new MultiNodeDijkstra(f.network, tc, tc); - Map fromNodes = new HashMap(); - fromNodes.put(f.network.getNodes().get(Id.create(1, Node.class)), new InitialNode(1.0, 1.0)); - Map toNodes = new HashMap(); - toNodes.put(f.network.getNodes().get(Id.create(2, Node.class)), new InitialNode(3.0, 3.0)); - - Path p = dijkstra.calcLeastCostPath(fromNodes, toNodes, null); - assertNull("wow, impossible path found!", p); - } - - /** - * Creates a simple network to be used in tests. - * - *
          -	 *   (1)                       (4)
          -	 *      \                     /
          -	 *       \_1               4_/
          -	 *        \                 /
          -	 *   (2)-2-(7)-----7-----(8)-5-(5)
          -	 *        /                 \
          -	 *       /_3               6_\
          -	 *      /                     \
          -	 *   (3)                       (6)
          -	 * 
          - * - * @author mrieser - */ - /*package*/ static class Fixture { - /*package*/ Network network; - - public Fixture() { - this.network = NetworkUtils.createNetwork(); - Node node1 = NetworkUtils.createAndAddNode(this.network, Id.create(1, Node.class), new Coord((double) 1000, (double) 0)); - Node node2 = NetworkUtils.createAndAddNode(this.network, Id.create(2, Node.class), new Coord((double) 500, (double) 0)); - Node node3 = NetworkUtils.createAndAddNode(this.network, Id.create(3, Node.class), new Coord((double) 0, (double) 0)); - Node node4 = NetworkUtils.createAndAddNode(this.network, Id.create(4, Node.class), new Coord((double) 1000, (double) 2000)); - Node node5 = NetworkUtils.createAndAddNode(this.network, Id.create(5, Node.class), new Coord((double) 500, (double) 2000)); - Node node6 = NetworkUtils.createAndAddNode(this.network, Id.create(6, Node.class), new Coord((double) 0, (double) 2000)); - Node node7 = NetworkUtils.createAndAddNode(this.network, Id.create(7, Node.class), new Coord((double) 500, (double) 500)); - Node node8 = NetworkUtils.createAndAddNode(this.network, Id.create(8, Node.class), new Coord((double) 500, (double) 1500)); - final Node fromNode = node1; - final Node toNode = node7; - NetworkUtils.createAndAddLink(this.network,Id.create(1, Link.class), fromNode, toNode, 1000.0, 10.0, 2000.0, (double) 1 ); - final Node fromNode1 = node2; - final Node toNode1 = node7; - NetworkUtils.createAndAddLink(this.network,Id.create(2, Link.class), fromNode1, toNode1, 1000.0, 10.0, 2000.0, (double) 1 ); - final Node fromNode2 = node3; - final Node toNode2 = node7; - NetworkUtils.createAndAddLink(this.network,Id.create(3, Link.class), fromNode2, toNode2, 1000.0, 10.0, 2000.0, (double) 1 ); - final Node fromNode3 = node8; - final Node toNode3 = node4; - NetworkUtils.createAndAddLink(this.network,Id.create(4, Link.class), fromNode3, toNode3, 1000.0, 10.0, 2000.0, (double) 1 ); - final Node fromNode4 = node8; - final Node toNode4 = node5; - NetworkUtils.createAndAddLink(this.network,Id.create(5, Link.class), fromNode4, toNode4, 1000.0, 10.0, 2000.0, (double) 1 ); - final Node fromNode5 = node8; - final Node toNode5 = node6; - NetworkUtils.createAndAddLink(this.network,Id.create(6, Link.class), fromNode5, toNode5, 1000.0, 10.0, 2000.0, (double) 1 ); - final Node fromNode6 = node7; - final Node toNode6 = node8; - NetworkUtils.createAndAddLink(this.network,Id.create(7, Link.class), fromNode6, toNode6, 1000.0, 10.0, 2000.0, (double) 1 ); - } - } - - /*package*/ static class TestTimeCost implements TravelTime, TransitTravelDisutility { - - private final Map, Double> travelTimes = new HashMap<>(); - private final Map, Double> travelCosts = new HashMap<>(); - - public void setData(final Id id, final double travelTime, final double travelCost) { - this.travelTimes.put(id, Double.valueOf(travelTime)); - this.travelCosts.put(id, Double.valueOf(travelCost)); - } - - @Override - public double getLinkTravelTime(final Link link, final double time, Person person, Vehicle vehicle) { - return this.travelTimes.get(link.getId()).doubleValue(); - } - - @Override - public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle, final CustomDataManager dataManager) { - return this.travelCosts.get(link.getId()).doubleValue(); - } - - @Override - public double getWalkTravelTime(Person person, Coord coord, Coord toCoord) { - return 0; - } - - @Override - public double getWalkTravelDisutility(Person person, Coord coord, Coord toCoord) { - return 0; - } - - - - } - -} diff --git a/matsim/src/test/java/org/matsim/pt/router/TransitLeastCostPathTreeTest.java b/matsim/src/test/java/org/matsim/pt/router/TransitLeastCostPathTreeTest.java deleted file mode 100644 index b168007ee70..00000000000 --- a/matsim/src/test/java/org/matsim/pt/router/TransitLeastCostPathTreeTest.java +++ /dev/null @@ -1,239 +0,0 @@ - -/* *********************************************************************** * - * project: org.matsim.* - * TransitLeastCostPathTreeTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2019 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - - package org.matsim.pt.router; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.assertj.core.api.Assertions; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Scenario; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Person; -import org.matsim.core.config.Config; -import org.matsim.core.config.ConfigUtils; -import org.matsim.core.network.NetworkUtils; -import org.matsim.core.router.InitialNode; -import org.matsim.core.router.util.LeastCostPathCalculator.Path; -import org.matsim.core.router.util.TravelTime; -import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitScheduleReader; -import org.matsim.testcases.MatsimTestUtils; -import org.matsim.vehicles.Vehicle; - -/** - * Junit Test for the TransitLeastCostPathTree. - * - * @author gabriel.thunig on 23.05.2016. - */ -public class TransitLeastCostPathTreeTest { - - private TransitRouterNetwork network; - private TransitRouterNetworkTravelTimeAndDisutility travelDisutility; - - /** - * Instantiates a new TransitLeastCostPathTree object with a sample transitSchedule and default configuration. - */ - public void instantiateNetworkAndTravelDisutility() { - String transitScheduleFile = "test/scenarios/pt-tutorial/transitschedule.xml"; - - Config config = ConfigUtils.createConfig(); - Scenario scenario = ScenarioUtils.loadScenario(config); - scenario.getConfig().transit().setUseTransit(true); - TransitScheduleReader reader = new TransitScheduleReader(scenario); - TransitRouterConfig transitRouterConfig = new TransitRouterConfig(scenario.getConfig()); - reader.readFile(transitScheduleFile); - TransitSchedule transitSchedule = scenario.getTransitSchedule(); - network = TransitRouterNetwork.createFromSchedule(transitSchedule, transitRouterConfig.getBeelineWalkConnectionDistance()); - - PreparedTransitSchedule preparedTransitSchedule = new PreparedTransitSchedule(transitSchedule); - travelDisutility = new TransitRouterNetworkTravelTimeAndDisutility(transitRouterConfig, preparedTransitSchedule); - } - - /** - * Check whether the @Before-instantiation is instantiating a network and a travelDisutility. - */ - @Test - public void TestNetworkAndTravelDisutilityInstantiated() { - instantiateNetworkAndTravelDisutility(); - Assert.assertNotNull(network); - Assert.assertNotNull(travelDisutility); - } - - /** - * Get the very next transitNode. - * @param person Which person we are routing for. For default leave null. - * @param coord The origin of the tree. - * @param departureTime The time the person departures at the origin. - * @return the next transitNode. - */ - private Map locateWrappedNearestTransitNode(Person person, Coord coord, double departureTime) { - TransitRouterNetwork.TransitRouterNetworkNode nearestNode = network.getNearestNode(coord); - Map wrappedNearestNodes = new LinkedHashMap<>(); - Coord toCoord = nearestNode.stop.getStopFacility().getCoord(); - double initialTime = travelDisutility.getWalkTravelTime(person, coord, toCoord); - double initialCost = travelDisutility.getWalkTravelDisutility(person, coord, toCoord); - wrappedNearestNodes.put(nearestNode, new InitialNode(initialCost, initialTime + departureTime)); - return wrappedNearestNodes; - } - - /** - * Try to route a standard connection. - */ - @Test - public void TestValidRouting() { - instantiateNetworkAndTravelDisutility(); - Coord fromCoord = new Coord(1050d, 1050d); - Map wrappedFromNodes = this.locateWrappedNearestTransitNode(null, fromCoord, 28800); - TransitLeastCostPathTree tree = new TransitLeastCostPathTree(network, travelDisutility, travelDisutility, wrappedFromNodes, null); - Coord toCoord = new Coord(3950d, 1050d); - Map wrappedToNodes = this.locateWrappedNearestTransitNode(null, toCoord, 28800); - Path path = tree.getPath(wrappedToNodes); - Assert.assertNotNull(path); - double pathCost = path.travelCost; - Assert.assertEquals(1.8d, pathCost, MatsimTestUtils.EPSILON); - double pathTime = path.travelTime; - Assert.assertEquals(540d, pathTime, MatsimTestUtils.EPSILON); - } - - /** - * Try to route a connection with interchange. - */ - @Test - public void TestValidRoutingWithInterchange() { - instantiateNetworkAndTravelDisutility(); - Coord fromCoord = new Coord(1050d, 1050d); - Map wrappedFromNodes = this.locateWrappedNearestTransitNode(null, fromCoord, 28800); - TransitLeastCostPathTree tree = new TransitLeastCostPathTree(network, travelDisutility, travelDisutility, wrappedFromNodes, null); - Coord toCoord = new Coord(2050d, 2960d); - Map wrappedToNodes = this.locateWrappedNearestTransitNode(null, toCoord, 28800); - Path path = tree.getPath(wrappedToNodes); - Assert.assertNotNull(path); - double pathCost = path.travelCost; - Assert.assertEquals(1.7706666666666668d, pathCost, MatsimTestUtils.EPSILON); - double pathTime = path.travelTime; - Assert.assertEquals(231.20000000000073d, pathTime, MatsimTestUtils.EPSILON); - } - - @Ignore - @Test - public void TestSpeedImprovementOnStopCriterion() { - Fixture f = new Fixture(); - TestTimeCost tc = new TestTimeCost(); - for (int i = 0; i < f.count-1; i++) { - tc.setData(Id.create(i, Link.class), 1.0, 1.0); - } - Map fromNodes = new HashMap<>(); - fromNodes.put(f.network.getNodes().get(Id.create(0, Node.class)), new InitialNode(0.0, 0.0)); - Map toNodes = new HashMap<>(); - toNodes.put(f.network.getNodes().get(Id.create(1, Node.class)), new InitialNode(0.0, 0.0)); - for (Node node : fromNodes.keySet()) { - System.out.println("From Node = " + node.getCoord()); - } - for (Node node : toNodes.keySet()) { - System.out.println("To Node = " + node.getCoord()); - } - long startTime = System.currentTimeMillis(); - new TransitLeastCostPathTree(f.network, tc, tc, fromNodes, null); - long endTime = System.currentTimeMillis(); - long elapsedTimeWithoutStopCreterion = (endTime - startTime); - startTime = System.currentTimeMillis(); - new TransitLeastCostPathTree(f.network, tc, tc, fromNodes, toNodes, null); - endTime = System.currentTimeMillis(); - long elapsedTimeWithStopCreterion = (endTime - startTime); - Double bareRatio = (double)elapsedTimeWithoutStopCreterion / (double)elapsedTimeWithStopCreterion; - System.out.println("bareRatio = " + bareRatio); - int ratio = (int) ((bareRatio) * 10); - System.out.println("Time without stop criterion = " + elapsedTimeWithoutStopCreterion); - System.out.println("Time with stop criterion = " + elapsedTimeWithStopCreterion); - System.out.println("ratio = " + ratio); - Assertions.assertThat(ratio).isGreaterThan(15); - } - - /** - * Creates a simple network to be used in TestSpeedImprovementOnStopCriterion. - * - *
          -     *   (0)--(1)--(2)--...--(9997)--(9998)--(9999)
          -     * 
          - * - * @author gthunig - */ - /*package*/ static class Fixture { - /*package*/ Network network; - - int count = 10000; - - public Fixture() { - this.network = NetworkUtils.createNetwork(); - Node linkStartNode = NetworkUtils.createAndAddNode(this.network, Id.create(0, Node.class), new Coord((double) 0, (double) 0)); - for (int i = 1; i < count; i++) { - Node linkEndNode = NetworkUtils.createAndAddNode(this.network, Id.create(i, Node.class), new Coord((double) i, (double) 0)); - final Node fromNode = linkStartNode; - final Node toNode = linkEndNode; - NetworkUtils.createAndAddLink(this.network,Id.create(i-1, Link.class), fromNode, toNode, 1000.0, 10.0, 2000.0, (double) 1 ); - linkStartNode = linkEndNode; - } - - } - } - - /*package*/ static class TestTimeCost implements TravelTime, TransitTravelDisutility { - - private final Map, Double> travelTimes = new HashMap<>(); - private final Map, Double> travelCosts = new HashMap<>(); - - public void setData(final Id id, final double travelTime, final double travelCost) { - this.travelTimes.put(id, travelTime); - this.travelCosts.put(id, travelCost); - } - - @Override - public double getLinkTravelTime(final Link link, final double time, Person person, Vehicle vehicle) { - return this.travelTimes.get(link.getId()); - } - - @Override - public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle, final CustomDataManager dataManager) { - return this.travelCosts.get(link.getId()); - } - - @Override - public double getWalkTravelTime(Person person, Coord coord, Coord toCoord) { - return 0; - } - - @Override - public double getWalkTravelDisutility(Person person, Coord coord, Coord toCoord) { - return 0; - } - - } -} diff --git a/matsim/src/test/java/org/matsim/pt/router/TransitRouterConfigTest.java b/matsim/src/test/java/org/matsim/pt/router/TransitRouterConfigTest.java index b77f034999d..a7a3f3cad17 100644 --- a/matsim/src/test/java/org/matsim/pt/router/TransitRouterConfigTest.java +++ b/matsim/src/test/java/org/matsim/pt/router/TransitRouterConfigTest.java @@ -23,8 +23,8 @@ import org.junit.Test; import org.matsim.api.core.v01.TransportMode; -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.config.groups.VspExperimentalConfigGroup; import org.matsim.pt.config.TransitRouterConfigGroup; @@ -32,11 +32,11 @@ * @author mrieser */ public class TransitRouterConfigTest { - + @Test public void testConstructor() { - PlanCalcScoreConfigGroup planScoring = new PlanCalcScoreConfigGroup(); - PlansCalcRouteConfigGroup planRouting = new PlansCalcRouteConfigGroup(); + ScoringConfigGroup planScoring = new ScoringConfigGroup(); + RoutingConfigGroup planRouting = new RoutingConfigGroup(); TransitRouterConfigGroup transitRouting = new TransitRouterConfigGroup(); VspExperimentalConfigGroup vspConfig = new VspExperimentalConfigGroup() ; @@ -50,26 +50,26 @@ public void testConstructor() { // naturally, this failed after the functionality was moved to a separate planCalcScore parameter. kai, oct'12 planScoring.setPerforming_utils_hr(+6.0); - + planScoring.setUtilityOfLineSwitch(-2.34); - + planRouting.setTeleportedModeSpeed(TransportMode.walk, 1.37 ); // (this will clear all defaults!) planRouting.setBeelineDistanceFactor(1.2); - + transitRouting.setAdditionalTransferTime(128.0); transitRouting.setSearchRadius(987.6); transitRouting.setExtensionRadius(123.4); transitRouting.setMaxBeelineWalkConnectionDistance(23.4); - + // test without marginal utl of time: { TransitRouterConfig config = new TransitRouterConfig(planScoring, planRouting, transitRouting, vspConfig ); - + // Assert.assertEquals(-9.0/3600, config.getMarginalUtilityOfTravelTimePt_utl_s(), 1e-8); // Assert.assertEquals(-11.0/3600, config.getMarginalUtilityOfTravelTimeWalk_utl_s(), 1e-8); // Assert.assertEquals(-13.0/3600, config.getMarginalUtiltityOfWaiting_utl_s(), 1e-8); - // a number of changes related to the fact that the opportunity cost of time is now + // a number of changes related to the fact that the opportunity cost of time is now // included in the pt routing. Either the test here or some scoring // test needs to be adapted; this seems the better place. kai/benjamin, oct'12 Assert.assertEquals(-15.0/3600, config.getMarginalUtilityOfTravelTimePt_utl_s(), 1e-8); @@ -78,23 +78,23 @@ public void testConstructor() { Assert.assertEquals(-2.34, config.getUtilityOfLineSwitch_utl(), 1e-8); Assert.assertEquals(1.37 / 1.2, config.getBeelineWalkSpeed(), 1e-8); - + Assert.assertEquals(128.0, config.getAdditionalTransferTime(), 1e-8); Assert.assertEquals(987.6, config.getSearchRadius(), 1e-8); Assert.assertEquals(123.4, config.getExtensionRadius(), 1e-8); Assert.assertEquals(23.4, config.getBeelineWalkConnectionDistance(), 1e-8); } - + // test with marginal utl of time: { TransitRouterConfig config = new TransitRouterConfig(planScoring, planRouting, transitRouting, vspConfig ); - + Assert.assertEquals(-15.0/3600, config.getMarginalUtilityOfTravelTimePt_utl_s(), 1e-8); Assert.assertEquals(-17.0/3600, config.getMarginalUtilityOfTravelTimeWalk_utl_s(), 1e-8); Assert.assertEquals(-19.0/3600, config.getMarginalUtilityOfWaitingPt_utl_s(), 1e-8); Assert.assertEquals(-2.34, config.getUtilityOfLineSwitch_utl(), 1e-8); Assert.assertEquals(1.37 / 1.2, config.getBeelineWalkSpeed(), 1e-8); - + Assert.assertEquals(128.0, config.getAdditionalTransferTime(), 1e-8); Assert.assertEquals(987.6, config.getSearchRadius(), 1e-8); Assert.assertEquals(123.4, config.getExtensionRadius(), 1e-8); diff --git a/matsim/src/test/java/org/matsim/pt/router/TransitRouterCustomDataTest.java b/matsim/src/test/java/org/matsim/pt/router/TransitRouterCustomDataTest.java deleted file mode 100644 index ecd8b62af48..00000000000 --- a/matsim/src/test/java/org/matsim/pt/router/TransitRouterCustomDataTest.java +++ /dev/null @@ -1,209 +0,0 @@ - -/* *********************************************************************** * - * project: org.matsim.* - * TransitRouterCustomDataTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2019 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - - package org.matsim.pt.router; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Scenario; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Person; -import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.core.config.ConfigUtils; -import org.matsim.core.router.DefaultRoutingRequest; -import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.pt.router.TransitRouterNetwork.TransitRouterNetworkNode; -import org.matsim.pt.transitSchedule.api.Departure; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitRouteStop; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitScheduleFactory; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.vehicles.Vehicle; - -/** - * @author mrieser / senozon - */ -public class TransitRouterCustomDataTest { - @Test - public void testCustomDataIntegration() { - Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); - scenario.getConfig().transit().setUseTransit(true); - createTestSchedule(scenario); - - TransitRouterConfig trConfig = new TransitRouterConfig(scenario.getConfig().planCalcScore(), - scenario.getConfig().plansCalcRoute(), scenario.getConfig().transitRouter(), - scenario.getConfig().vspExperimental()); - trConfig.setBeelineWalkSpeed(0.1); // something very slow, so the agent does not walk over night - trConfig.setSearchRadius(200); - - TransitRouterNetworkTravelTimeAndDisutility transitRouterNetworkTravelTimeAndDisutility = new TransitRouterNetworkTravelTimeAndDisutility(trConfig); - - MockingTransitTravelDisutility disutility = new MockingTransitTravelDisutility(transitRouterNetworkTravelTimeAndDisutility); - - TransitRouterNetwork transitNetwork = TransitRouterNetwork.createFromSchedule(scenario.getTransitSchedule(), trConfig.getBeelineWalkConnectionDistance()); - - TransitRouterImpl router = new TransitRouterImpl(trConfig, new PreparedTransitSchedule(scenario.getTransitSchedule()), transitNetwork, transitRouterNetworkTravelTimeAndDisutility, disutility); - - double x = -100; - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility( new Coord(x, (double) 0)), new FakeFacility( new Coord((double) 3100, (double) 0)), 5.9*3600, null)); - Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - - /* the following is not really nice as a test, but I had to somehow - * keep track of the internal state and have to replay this now - * to ensure everything works as expected... - */ - Assert.assertEquals(8, disutility.states.size()); - Assert.assertEquals("[[1>2 @ 22240.0]]", disutility.states.get(0)); // first link to be expanded: from stop 1 to stop 2, line 1 - Assert.assertEquals("[[1>3 @ 22240.0]]", disutility.states.get(1)); // now from stop 1 to stop 3, line 2 - Assert.assertEquals("[[1>2 @ 22240.0], [2>3 @ 108300.0]]", disutility.states.get(2)); // from stop 2 to stop 3, coming from stop 1 before, line 1 - Assert.assertEquals("[[1>2 @ 22240.0], [2>3 @ 108300.0], [3>4 @ 108600.0]]", disutility.states.get(3)); // continuing on line 1 - Assert.assertEquals("[[1>2 @ 22240.0], [2>3 @ 108300.0], [3>3 @ 108600.0]]", disutility.states.get(4)); // transfer at stop 3, coming from line 1, to line 2 - Assert.assertEquals("[[1>3 @ 22240.0], [3>5 @ 108690.0]]", disutility.states.get(5)); // continue on line 2 - Assert.assertEquals("[[1>3 @ 22240.0], [3>3 @ 108690.0]]", disutility.states.get(6)); // transfer at stop 3, coming from line 2, should be a dead end - Assert.assertEquals("[[1>2 @ 22240.0], [2>3 @ 108300.0], [3>4 @ 108600.0], [4>5 @ 108900.0]]", disutility.states.get(7)); // continue on line 1 - - /* important to notice: - * state[4] should be ignored, as it is a worse result than previously found solutions. - * The ignoring of the state can be seen e.g. in state[5] which continues on line 2 state[4] switched to, - * but using the original travel sequence. - */ - } - - private static class MockingTransitTravelDisutility implements TransitTravelDisutility { - - private final TransitRouterNetworkTravelTimeAndDisutility routerDisutility; - private ArrayList states = new ArrayList<>(); - - public MockingTransitTravelDisutility(final TransitRouterNetworkTravelTimeAndDisutility routerDisutility) { - this.routerDisutility = routerDisutility; - } - - @Override - public double getLinkTravelDisutility(Link link, double time, - Person person, Vehicle vehicle, CustomDataManager dataManager) { - double val = this.routerDisutility.getLinkTravelDisutility(link, time, person, vehicle, dataManager); - - System.out.print("handling link " + ((TransitRouterNetworkNode) link.getFromNode()).getStop().getStopFacility().getId() - + ">" + ((TransitRouterNetworkNode) link.getToNode()).getStop().getStopFacility().getId()); - ArrayList links = new ArrayList<>(); - Object o = dataManager.getFromNodeCustomData(); - if (o instanceof ArrayList) { - links.addAll((Collection) o); - } - links.add(new LoggerData(link, time)); - String newState = Arrays.toString(links.toArray(new LoggerData[links.size()])); - System.out.println(" : " + newState); - this.states.add(newState); - dataManager.setToNodeCustomData(links); - - return val; - } - - @Override - public double getWalkTravelDisutility(Person person, Coord coord, Coord toCoord) { - return routerDisutility.getWalkTravelDisutility(person, coord, toCoord); - } - - @Override - public double getWalkTravelTime(Person person, Coord coord, Coord toCoord) { - return routerDisutility.getWalkTravelTime(person, coord, toCoord); - } - - } - - private static class LoggerData { - private final Link link; - private final double time; - public LoggerData(final Link link, final double time) { - this.link = link; - this.time = time; - } - @Override - public String toString() { - return "[" + ((TransitRouterNetworkNode) link.getFromNode()).getStop().getStopFacility().getId() - + ">" + ((TransitRouterNetworkNode) link.getToNode()).getStop().getStopFacility().getId() - + " @ " + time + "]"; - } - } - - /** - * Creates the following test schedule: - * - * - * (2) (4) - * / \ / \ - * / \ / \ - * / \ / \ - * (1)-------(3)-------(5) - * - * line 1 traveling from 1 to 2 to 3 to 4 to 5 - * line 2 traveling from 1 to 3 to 5, slower from 1 to 3 than line 1, faster from 3 to 5 and from 5 to 7 - * - */ - private final void createTestSchedule(final Scenario scenario) { - TransitSchedule schedule = scenario.getTransitSchedule(); - TransitScheduleFactory f = schedule.getFactory(); - - TransitStopFacility f1 = f.createTransitStopFacility(Id.create("1", TransitStopFacility.class), new Coord((double) 0, (double) 0), false); - TransitStopFacility f2 = f.createTransitStopFacility(Id.create("2", TransitStopFacility.class), new Coord((double) 500, (double) 500), false); - TransitStopFacility f3 = f.createTransitStopFacility(Id.create("3", TransitStopFacility.class), new Coord((double) 1000, (double) 0), false); - TransitStopFacility f4 = f.createTransitStopFacility(Id.create("4", TransitStopFacility.class), new Coord((double) 1500, (double) 500), false); - TransitStopFacility f5 = f.createTransitStopFacility(Id.create("5", TransitStopFacility.class), new Coord((double) 2000, (double) 0), false); - - schedule.addStopFacility(f1); - schedule.addStopFacility(f2); - schedule.addStopFacility(f3); - schedule.addStopFacility(f4); - schedule.addStopFacility(f5); - - TransitLine line1 = f.createTransitLine(Id.create("1", TransitLine.class)); - List stops = new ArrayList<>(); - stops.add(f.createTransitRouteStopBuilder(f1).departureOffset(0.0).build()); - stops.add(f.createTransitRouteStopBuilder(f2).departureOffset(300.0).build()); - stops.add(f.createTransitRouteStopBuilder(f3).departureOffset(600.0).build()); - stops.add(f.createTransitRouteStopBuilder(f4).departureOffset(900.0).build()); - stops.add(f.createTransitRouteStopBuilder(f5).arrivalOffset(1200.0).build()); - TransitRoute route1 = f.createTransitRoute(Id.create("1", TransitRoute.class), null, stops, "pt"); - line1.addRoute(route1); - schedule.addTransitLine(line1); - route1.addDeparture(f.createDeparture(Id.create("1", Departure.class), 6.0*3600)); - - TransitLine line2 = f.createTransitLine(Id.create("2", TransitLine.class)); - List stops2 = new ArrayList<>(); - stops2.add(f.createTransitRouteStopBuilder(f1).departureOffset(0.0).build()); - stops2.add(f.createTransitRouteStopBuilder(f3).departureOffset(750.0).build()); - stops2.add(f.createTransitRouteStopBuilder(f5).arrivalOffset(1100.0).build()); - TransitRoute route2 = f.createTransitRoute(Id.create("2", TransitRoute.class), null, stops2, "pt"); - line2.addRoute(route2); - schedule.addTransitLine(line2); - route2.addDeparture(f.createDeparture(Id.create("2", Departure.class), 6.0*3600 - 60)); - } -} diff --git a/matsim/src/test/java/org/matsim/pt/router/TransitRouterImplTest.java b/matsim/src/test/java/org/matsim/pt/router/TransitRouterImplTest.java deleted file mode 100644 index 3e9ca095fef..00000000000 --- a/matsim/src/test/java/org/matsim/pt/router/TransitRouterImplTest.java +++ /dev/null @@ -1,869 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * NewTransitRouteTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 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.pt.router; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.matsim.api.core.v01.Coord; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Scenario; -import org.matsim.api.core.v01.TransportMode; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Activity; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.core.config.Config; -import org.matsim.core.config.ConfigUtils; -import org.matsim.core.population.routes.NetworkRoute; -import org.matsim.core.population.routes.RouteUtils; -import org.matsim.core.router.DefaultRoutingModules; -import org.matsim.core.router.DefaultRoutingRequest; -import org.matsim.core.router.RoutingModule; -import org.matsim.core.router.TransitRouterWrapper; -import org.matsim.core.scenario.MutableScenario; -import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.core.utils.geometry.CoordUtils; -import org.matsim.facilities.ActivityFacilities; -import org.matsim.facilities.ActivityFacility; -import org.matsim.pt.routes.TransitPassengerRoute; -import org.matsim.pt.transitSchedule.api.Departure; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitRouteStop; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitScheduleFactory; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import org.matsim.testcases.MatsimTestUtils; - -/** - * @author mrieser - */ -@RunWith(Parameterized.class) -public class TransitRouterImplTest { - private static final Logger log = LogManager.getLogger(TransitRouterImplTest.class) ; - - private String routerType ; - - @Parameters(name = "{index}: TransitRouter == {0}") - public static Collection createRouterTypes() { - Object[] router = new Object [] { - "standard" -// ,TransitRouterType.raptor - }; - return Arrays.asList(router); - } - - public TransitRouterImplTest( String routerType ) { - log.warn( "using router=" + routerType ) ; - this.routerType = routerType; - } - - @Test - public void testSingleLine() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig()); - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - Coord fromCoord = new Coord(3800, 5100); - Coord toCoord = new Coord(16100, 5050); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 5.0*3600, null)); - assertEquals(3, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); - assertTrue("expected TransitRoute in leg.", ((Leg)legs.get(1)).getRoute() instanceof TransitPassengerRoute); - TransitPassengerRoute ptRoute = (TransitPassengerRoute) ((Leg)legs.get(1)).getRoute(); - assertEquals(Id.create("0", TransitStopFacility.class), ptRoute.getAccessStopId()); - assertEquals(Id.create("6", TransitStopFacility.class), ptRoute.getEgressStopId()); - assertEquals(f.blueLine.getId(), ptRoute.getLineId()); - assertEquals(Id.create("blue A > I", TransitRoute.class), ptRoute.getRouteId()); - double actualTravelTime = 0.0; - for (PlanElement leg : legs) { - actualTravelTime += ((Leg)leg).getTravelTime().seconds(); - } - double expectedTravelTime = 29.0 * 60 + // agent takes the *:06 course, arriving in D at *:29 - CoordUtils.calcEuclideanDistance(f.schedule.getFacilities().get(Id.create("6", TransitStopFacility.class)).getCoord(), toCoord) / trConfig.getBeelineWalkSpeed(); - assertEquals(expectedTravelTime, actualTravelTime, MatsimTestUtils.EPSILON); - } - - protected TransitRouter createTransitRouter(TransitSchedule schedule, TransitRouterConfig trConfig, String routerType) { - TransitRouter router = null ; - switch( routerType ) { -// case raptor: -// double costPerMeterTraveled = 0. ; -// double costPerBoarding = 0. ; -// RaptorDisutility raptorDisutility = new RaptorDisutility(trConfig, costPerBoarding, costPerMeterTraveled); -// TransitRouterQuadTree transitRouterQuadTree = new TransitRouterQuadTree(raptorDisutility); -// transitRouterQuadTree.initializeFromSchedule(schedule, trConfig.getBeelineWalkConnectionDistance()); -// router = new Raptor(transitRouterQuadTree, raptorDisutility, trConfig) ; -// break; - case "standard": - router = new TransitRouterImpl(trConfig, schedule); - break; - default: - break; - } - return router; - } - - @Test - public void testFromToSameStop() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig()); - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - Coord fromCoord = new Coord((double) 3800, (double) 5100); - Coord toCoord = new Coord((double) 4100, (double) 5050); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 5.0*3600, null)); - Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - } - - @Test - public void testDirectWalkCheaper() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - Coord fromCoord = new Coord((double) 4000, (double) 3000); - Coord toCoord = new Coord((double) 8000, (double) 3000); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 5.0*3600, null)); - Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - } - - @Test - public void testSingleLine_DifferentWaitingTime() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - Coord fromCoord = new Coord((double) 4000, (double) 5002); - Coord toCoord = new Coord((double) 8000, (double) 5002); - - double inVehicleTime = 7.0*60; // travel time from A to B - for (int min = 0; min < 30; min += 3) { - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 5.0*3600 + min*60, null)); - assertEquals(3, legs.size()); // walk-pt-walk - double actualTravelTime = 0.0; - for (PlanElement leg : legs) { - actualTravelTime += ((Leg)leg).getTravelTime().seconds(); - } - double waitingTime = ((46 - min) % 20) * 60; // departures at *:06 and *:26 and *:46 - assertEquals("expected different waiting time at 05:"+min, waitingTime, actualTravelTime - inVehicleTime, MatsimTestUtils.EPSILON); - } - } - - @Test - public void testLineChange() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - Coord toCoord = new Coord((double) 16100, (double) 10050); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord((double) 3800, (double) 5100)), new FakeFacility(toCoord), 6.0*3600, null)); - assertEquals(5, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(3)).getMode()); - assertEquals(TransportMode.walk, ((Leg)legs.get(4)).getMode()); - assertTrue("expected TransitRoute in leg.", ((Leg)legs.get(1)).getRoute() instanceof TransitPassengerRoute); - TransitPassengerRoute ptRoute = (TransitPassengerRoute) ((Leg)legs.get(1)).getRoute(); - assertEquals(Id.create("0", TransitStopFacility.class), ptRoute.getAccessStopId()); - assertEquals(Id.create("4", TransitStopFacility.class), ptRoute.getEgressStopId()); - assertEquals(f.blueLine.getId(), ptRoute.getLineId()); - assertEquals(Id.create("blue A > I", TransitRoute.class), ptRoute.getRouteId()); - assertTrue("expected TransitRoute in leg.", ((Leg)legs.get(3)).getRoute() instanceof TransitPassengerRoute); - ptRoute = (TransitPassengerRoute) ((Leg)legs.get(3)).getRoute(); - assertEquals(Id.create("18", TransitStopFacility.class), ptRoute.getAccessStopId()); - assertEquals(Id.create("19", TransitStopFacility.class), ptRoute.getEgressStopId()); - assertEquals(f.greenLine.getId(), ptRoute.getLineId()); - assertEquals(Id.create("green clockwise", TransitRoute.class), ptRoute.getRouteId()); - double actualTravelTime = 0.0; - for (PlanElement leg : legs) { - actualTravelTime += ((Leg)leg).getTravelTime().seconds(); - } - double expectedTravelTime = 31.0 * 60 + // agent takes the *:06 course, arriving in C at *:18, departing at *:21, arriving in K at*:31 - CoordUtils.calcEuclideanDistance(f.schedule.getFacilities().get(Id.create("19", TransitStopFacility.class)).getCoord(), toCoord) / trConfig.getBeelineWalkSpeed(); - assertEquals(expectedTravelTime, actualTravelTime, MatsimTestUtils.EPSILON); - } - - @Test - public void testTransferWalkDistance(){ - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig config = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouter router = createTransitRouter(f.schedule, config, routerType); - Coord fromCoord = new Coord((double) 3800, (double) 5100); - Coord toCoord = new Coord((double) 16100, (double) 10050); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 6.0*3600, null)); - Leg leg1 = (Leg) legs.get(1); - TransitPassengerRoute route1 = (TransitPassengerRoute) leg1.getRoute(); - Coord coord1 = f.schedule.getFacilities().get(route1.getEgressStopId()).getCoord(); - Leg leg3 = (Leg) legs.get(3); - TransitPassengerRoute route3 = (TransitPassengerRoute) leg3.getRoute(); - Coord coord3 = f.schedule.getFacilities().get(route3.getAccessStopId()).getCoord(); - double beelineFactor = f.scenario.getConfig().plansCalcRoute().getModeRoutingParams().get(TransportMode.walk).getBeelineDistanceFactor(); - assertEquals(CoordUtils.calcEuclideanDistance(coord1, coord3) * beelineFactor, - ((Leg)legs.get(2)).getRoute().getDistance(), MatsimTestUtils.EPSILON); - } - - @Test - public void testFasterAlternative() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - Coord toCoord = new Coord((double) 28100, (double) 4950); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility( new Coord((double) 3800, (double) 5100)), new FakeFacility(toCoord), 5.0*3600 + 40.0*60, null)); - assertEquals(4, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(2)).getMode()); - assertEquals(TransportMode.walk, ((Leg)legs.get(3)).getMode()); - assertTrue("expected TransitRoute in leg.", ((Leg)legs.get(1)).getRoute() instanceof TransitPassengerRoute); - TransitPassengerRoute ptRoute = (TransitPassengerRoute) ((Leg)legs.get(1)).getRoute(); - assertEquals(Id.create("0", TransitStopFacility.class), ptRoute.getAccessStopId()); - assertEquals(Id.create("4", TransitStopFacility.class), ptRoute.getEgressStopId()); - assertEquals(f.blueLine.getId(), ptRoute.getLineId()); - assertEquals(Id.create("blue A > I", TransitRoute.class), ptRoute.getRouteId()); - assertTrue("expected TransitRoute in leg.", ((Leg)legs.get(2)).getRoute() instanceof TransitPassengerRoute); - ptRoute = (TransitPassengerRoute) ((Leg)legs.get(2)).getRoute(); - assertEquals(Id.create("4", TransitStopFacility.class), ptRoute.getAccessStopId()); - assertEquals(Id.create("12", TransitStopFacility.class), ptRoute.getEgressStopId()); - assertEquals(f.redLine.getId(), ptRoute.getLineId()); - assertEquals(Id.create("red C > G", TransitRoute.class), ptRoute.getRouteId()); - double actualTravelTime = 0.0; - for (PlanElement leg : legs) { - actualTravelTime += ((Leg)leg).getTravelTime().seconds(); - } - double expectedTravelTime = 29.0 * 60 + // agent takes the *:46 course, arriving in C at *:58, departing at *:00, arriving in G at*:09 - CoordUtils.calcEuclideanDistance(f.schedule.getFacilities().get(Id.create("12", TransitStopFacility.class)).getCoord(), toCoord) / trConfig.getBeelineWalkSpeed(); - assertEquals(expectedTravelTime, actualTravelTime, MatsimTestUtils.EPSILON); - } - - @Test - public void testTransferWeights() { - /* idea: travel from C to F - * If starting at the right time, one could take the red line to G and travel back with blue to F. - * If one doesn't want to switch lines, one could take the blue line from C to F directly. - * Using the red line (dep *:00, change at G *:09/*:12) results in an arrival time of *:19, - * using the blue line only (dep *:02) results in an arrival time of *:23. So the line switch - * cost must be larger than 4 minutes to have an effect. - */ - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - trConfig.setUtilityOfLineSwitch_utl(0); - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord((double) 11900, (double) 5100)), new FakeFacility(new Coord((double) 24100, (double) 4950)), 6.0*3600 - 5.0*60, null)); - assertEquals(5, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(f.redLine.getId(), ((TransitPassengerRoute) ((Leg)legs.get(1)).getRoute()).getLineId()); - assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(3)).getMode()); - assertEquals(f.blueLine.getId(), ((TransitPassengerRoute) ((Leg)legs.get(3)).getRoute()).getLineId()); - assertEquals(TransportMode.walk, ((Leg)legs.get(4)).getMode()); - - trConfig.setUtilityOfLineSwitch_utl(300.0 * trConfig.getMarginalUtilityOfTravelTimePt_utl_s()); // corresponds to 5 minutes transit travel time - legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord((double) 11900, (double) 5100)), new FakeFacility(new Coord((double) 24100, (double) 4950)), 6.0*3600 - 5.0*60, null)); - assertEquals(3, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(f.blueLine.getId(), ((TransitPassengerRoute) ((Leg)legs.get(1)).getRoute()).getLineId()); - assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); - } - - @Test - public void testTransferTime() { - /* idea: travel from C to F - * If starting at the right time, one could take the red line to G and travel back with blue to F. - * If one doesn't want to switch lines, one could take the blue line from C to F directly. - * Using the red line (dep *:00, change at G *:09/*:12) results in an arrival time of *:19, - * using the blue line only (dep *:02) results in an arrival time of *:23. - * For the line switch at G, 3 minutes are available. If the additional "savety" time is larger than - * that, the direct connection should be taken. - */ - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - trConfig.setUtilityOfLineSwitch_utl(0); - assertEquals(0, trConfig.getAdditionalTransferTime(), 1e-8); - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord((double) 11900, (double) 5100)), new FakeFacility(new Coord((double) 24100, (double) 4950)), 6.0*3600 - 5.0*60, null)); - assertEquals(5, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(f.redLine.getId(), ((TransitPassengerRoute) ((Leg)legs.get(1)).getRoute()).getLineId()); - assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(3)).getMode()); - assertEquals(f.blueLine.getId(), ((TransitPassengerRoute) ((Leg)legs.get(3)).getRoute()).getLineId()); - assertEquals(TransportMode.walk, ((Leg)legs.get(4)).getMode()); - - trConfig.setAdditionalTransferTime(3.0*60); // 3 mins already enough, as there is a small distance to walk anyway which adds some time - router = createTransitRouter(f.schedule, trConfig, routerType); // this is necessary to update the router for any change in config. At least raptor transit router fails without this. Amit Sep'17. - legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord((double) 11900, (double) 5100)), new FakeFacility(new Coord((double) 24100, (double) 4950)), 6.0*3600 - 5.0*60, null)); - assertEquals(3, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(f.blueLine.getId(), ((TransitPassengerRoute) ((Leg)legs.get(1)).getRoute()).getLineId()); - assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); - } - - @Test - public void testAfterMidnight() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - trConfig.setBeelineWalkSpeed(0.1); // something very slow, so the agent does not walk over night - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - Coord toCoord = new Coord((double) 16100, (double) 5050); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord((double) 3800, (double) 5100)), new FakeFacility(toCoord), 25.0*3600, null)); - assertEquals(3, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); - assertTrue("expected TransitRoute in leg.", ((Leg)legs.get(1)).getRoute() instanceof TransitPassengerRoute); - TransitPassengerRoute ptRoute = (TransitPassengerRoute) ((Leg)legs.get(1)).getRoute(); - assertEquals(Id.create("0", TransitStopFacility.class), ptRoute.getAccessStopId()); - assertEquals(Id.create("6", TransitStopFacility.class), ptRoute.getEgressStopId()); - assertEquals(f.blueLine.getId(), ptRoute.getLineId()); - assertEquals(Id.create("blue A > I", TransitRoute.class), ptRoute.getRouteId()); - double actualTravelTime = 0.0; - for (PlanElement leg : legs) { - actualTravelTime += ((Leg)leg).getTravelTime().seconds(); - } - double expectedTravelTime = 4*3600 + 29.0 * 60 + // arrival at 05:29 at D - CoordUtils.calcEuclideanDistance(f.schedule.getFacilities().get(Id.create("6", TransitStopFacility.class)).getCoord(), toCoord) / trConfig.getBeelineWalkSpeed(); - assertEquals(expectedTravelTime, actualTravelTime, MatsimTestUtils.EPSILON); - } - - @Test - public void testCoordFarAway() { - Fixture f = new Fixture(); - f.init(); - final TransitRouterConfig trConfig = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental() ); - TransitRouter router = createTransitRouter(f.schedule, trConfig, routerType); - double x = +42000; - double x1 = -2000; - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord(x1, (double) 0)), new FakeFacility(new Coord(x, (double) 0)), 5.5*3600, null)); // should map to stops A and I - assertEquals(3, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); - assertTrue("expected TransitRoute in leg.", ((Leg)legs.get(1)).getRoute() instanceof TransitPassengerRoute); - TransitPassengerRoute ptRoute = (TransitPassengerRoute) ((Leg)legs.get(1)).getRoute(); - assertEquals(Id.create("0", TransitStopFacility.class), ptRoute.getAccessStopId()); - assertEquals(Id.create("16", TransitStopFacility.class), ptRoute.getEgressStopId()); - assertEquals(f.blueLine.getId(), ptRoute.getLineId()); - assertEquals(Id.create("blue A > I", TransitRoute.class), ptRoute.getRouteId()); - } - - /** - * In rare cases, Dijkstra may choose to go along two walk links to get from one location to another. - * Test, that still only one walk leg with the correct start and end points/links is returned. - */ - @Test - public void testDoubleWalk() { - WalkFixture f = new WalkFixture(); - f.routerConfig.setMarginalUtilityOfTravelTimePt_utl_s(-1.0 / 3600.0 - 6.0/3600.0); - f.routerConfig.setUtilityOfLineSwitch_utl(0.2); // must be relatively low in this example, otherwise it's cheaper to walk the whole distance... - TransitRouter router = createTransitRouter(f.schedule, f.routerConfig, routerType); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(f.coord1), new FakeFacility(f.coord7), 990, null)); - assertEquals(5, legs.size()); - assertEquals(TransportMode.walk, ((Leg)legs.get(0)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(1)).getMode()); - assertEquals(f.stop1.getId(), ((TransitPassengerRoute) ((Leg)legs.get(1)).getRoute()).getAccessStopId()); - assertEquals(f.stop2.getId(), ((TransitPassengerRoute) ((Leg)legs.get(1)).getRoute()).getEgressStopId()); - assertEquals(f.stop1.getLinkId(), ((Leg)legs.get(1)).getRoute().getStartLinkId()); - assertEquals(f.stop2.getLinkId(), ((Leg)legs.get(1)).getRoute().getEndLinkId()); - assertEquals(TransportMode.walk, ((Leg)legs.get(2)).getMode()); - assertEquals(TransportMode.pt, ((Leg)legs.get(3)).getMode()); - assertEquals(f.stop2.getLinkId(), ((Leg)legs.get(2)).getRoute().getStartLinkId()); - assertEquals(f.stop6.getLinkId(), ((Leg)legs.get(2)).getRoute().getEndLinkId()); - assertEquals(f.stop6.getId(), ((TransitPassengerRoute) ((Leg)legs.get(3)).getRoute()).getAccessStopId()); - assertEquals(f.stop7.getId(), ((TransitPassengerRoute) ((Leg)legs.get(3)).getRoute()).getEgressStopId()); - assertEquals(f.stop6.getLinkId(), ((Leg)legs.get(3)).getRoute().getStartLinkId()); - assertEquals(f.stop7.getLinkId(), ((Leg)legs.get(3)).getRoute().getEndLinkId()); - assertEquals(TransportMode.walk, ((Leg)legs.get(4)).getMode()); - } - - /** - * Tests that if only a single transfer-/walk-link is found, the router correctly only returns - * on walk leg from start to end. - */ - @Test - public void testSingleWalkOnly() { - WalkFixture f = new WalkFixture(); - f.routerConfig.setSearchRadius(0.8 * CoordUtils.calcEuclideanDistance(f.coord2, f.coord4)); - f.routerConfig.setExtensionRadius(0.0); - - TransitRouter router = createTransitRouter(f.schedule, f.routerConfig, routerType); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(f.coord2), new FakeFacility(f.coord4), 990, null)); - Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - } - - /** - * Tests that if only exactly two transfer-/walk-link are found, the router correctly only returns - * on walk leg from start to end. Differs from {@link #testSingleWalkOnly()} in that it tests for - * the correct internal working when more than one walk links are returned. - */ - @Test - public void testDoubleWalkOnly() { - WalkFixture f = new WalkFixture(); - f.routerConfig.setSearchRadius(0.8 * CoordUtils.calcEuclideanDistance(f.coord2, f.coord4)); - f.routerConfig.setExtensionRadius(0.0); - - TransitRouter router = createTransitRouter(f.schedule, f.routerConfig, routerType); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(f.coord2), new FakeFacility(f.coord6), 990, null)); - Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - } - - @SuppressWarnings("unchecked") - @Test - public void testLongTransferTime() { - // 5 minutes additional transfer time - { - TransferFixture f = new TransferFixture(5 * 60.0); - TransitRouter router = createTransitRouter(f.schedule, f.routerConfig, routerType); - Coord fromCoord = f.fromFacility.getCoord(); - Coord toCoord = f.toFacility.getCoord(); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 7.0*3600 + 50*60, null)); - double legDuration = calcTripDuration(new ArrayList<>(legs)); - Assert.assertEquals(5, legs.size()); - Assert.assertEquals(100, ((Leg)legs.get(0)).getTravelTime().seconds(), 0.0); // 0.1km with 1m/s walk speed -> 100s; arrival at 07:51:40 - Assert.assertEquals(800, ((Leg)legs.get(1)).getTravelTime().seconds(), 0.0); // 8m 20s waiting for pt departure and 5m pt travel time -> 500s + 300s = 800s; arrival at 08:05:00 - Assert.assertEquals(304, ((Leg)legs.get(2)).getTravelTime().seconds(), 0.0); // 0.004km with 1m/s walk speed and additional waiting time -> 4s + 300s = 304s; arrival at 08:10:04 - Assert.assertEquals(596, ((Leg)legs.get(3)).getTravelTime().seconds(), 0.0); // 4m 56s waiting for pt departure and 5m pt travel time -> 296s + 300s = 596s; arrival at 08:15:00 - Assert.assertEquals(100, ((Leg)legs.get(4)).getTravelTime().seconds(), 0.0); // 0.1km with 1m/s walk speed -> 100s - Assert.assertEquals(1900.0, legDuration, 0.0); - - RoutingModule walkRoutingModule = DefaultRoutingModules.createTeleportationRouter(TransportMode.walk, f.scenario, - f.config.plansCalcRoute().getModeRoutingParams().get(TransportMode.walk)); - - TransitRouterWrapper wrapper = new TransitRouterWrapper( - router, - f.schedule, - f.scenario.getNetwork(), // use a walk router in case no PT path is found - walkRoutingModule); - - List planElements = (List) wrapper.calcRoute(DefaultRoutingRequest.withoutAttributes(f.fromFacility, f.toFacility, 7.0*3600 + 50*60, null)); - double tripDuration = calcTripDuration(planElements); - Assert.assertEquals(9, planElements.size()); - Assert.assertEquals(100, ((Leg)planElements.get(0)).getTravelTime().seconds(), 0.0); // 0.1km with 1m/s walk speed -> 100s; arrival at 07:51:40 - Assert.assertEquals(800, ((Leg)planElements.get(2)).getTravelTime().seconds(), 0.0); // 8m 20s waiting for pt departure and 5m pt travel time -> 500s + 300s = 800s; arrival at 08:05:00 - Assert.assertEquals(304, ((Leg)planElements.get(4)).getTravelTime().seconds(), 0.0); // 0.004km with 1m/s walk speed and additional waiting time -> 4s + 300s = 304s; arrival at 08:10:04 - Assert.assertEquals(596, ((Leg)planElements.get(6)).getTravelTime().seconds(), 0.0); // 4m 56s waiting for pt departure and 5m pt travel time -> 296s + 300s = 596s; arrival at 08:15:00 - Assert.assertEquals(100, ((Leg)planElements.get(8)).getTravelTime().seconds(), 0.0); // 0.1km with 1m/s walk speed -> 100s - Assert.assertEquals(1900.0, tripDuration, 0.0); - } - - // 65 minutes additional transfer time - miss one departure - { - TransferFixture f = new TransferFixture(65 * 60.0); - TransitRouter router = createTransitRouter(f.schedule, f.routerConfig, routerType); - Coord fromCoord = f.fromFacility.getCoord(); - Coord toCoord = f.toFacility.getCoord(); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 7.0*3600 + 50*60, null)); - double legDuration = calcTripDuration(new ArrayList<>(legs)); - Assert.assertEquals(5, legs.size()); - Assert.assertEquals(100, ((Leg)legs.get(0)).getTravelTime().seconds(), 0.0); // 0.1km with 1m/s walk speed -> 100s; arrival at 07:51:40 - Assert.assertEquals(800, ((Leg)legs.get(1)).getTravelTime().seconds(), 0.0); // 8m 20s waiting for pt departure and 5m pt travel time -> 500s + 300s = 800s; arrival at 08:05:00 - Assert.assertEquals(3904, ((Leg)legs.get(2)).getTravelTime().seconds(), 0.0); // 0.004km with 1m/s walk speed and additional waiting time -> 4s + 3900s = 3904s; arrival at 09:10:04 - Assert.assertEquals(596, ((Leg)legs.get(3)).getTravelTime().seconds(), 0.0); // 4m 56s waiting for pt departure and 5m pt travel time -> 296s + 300s = 596s; arrival at 09:15:00 - Assert.assertEquals(100, ((Leg)legs.get(4)).getTravelTime().seconds(), 0.0); // 0.1km with 1m/s walk speed -> 100s - Assert.assertEquals(5500.0, legDuration, 0.0); - - RoutingModule walkRoutingModule = DefaultRoutingModules.createTeleportationRouter(TransportMode.walk, f.scenario, - f.config.plansCalcRoute().getModeRoutingParams().get(TransportMode.walk)); - - TransitRouterWrapper wrapper = new TransitRouterWrapper( - router, - f.schedule, - f.scenario.getNetwork(), // use a walk router in case no PT path is found - walkRoutingModule); - - List planElements = (List) wrapper.calcRoute(DefaultRoutingRequest.withoutAttributes(f.fromFacility, f.toFacility, 7.0*3600 + 50*60, null)); - double tripDuration = calcTripDuration(planElements); - Assert.assertEquals(9, planElements.size()); - Assert.assertEquals(100, ((Leg)planElements.get(0)).getTravelTime().seconds(), 0.0); // 0.1km with 1m/s walk speed -> 100s; arrival at 07:51:40 - Assert.assertEquals(800, ((Leg)planElements.get(2)).getTravelTime().seconds(), 0.0); // 8m 20s waiting for pt departure and 5m pt travel time -> 500s + 300s = 800s; arrival at 08:05:00 - Assert.assertEquals(3904, ((Leg)planElements.get(4)).getTravelTime().seconds(), 0.0); // 0.004km with 1m/s walk speed and additional waiting time -> 4s + 3900s = 3904s; arrival at 09:10:04 - Assert.assertEquals(596, ((Leg)planElements.get(6)).getTravelTime().seconds(), 0.0); // 4m 56s waiting for pt departure and 5m pt travel time -> 296s + 300s = 596s; arrival at 09:15:00 - Assert.assertEquals(100, ((Leg)planElements.get(8)).getTravelTime().seconds(), 0.0); // 0.1km with 1m/s walk speed -> 100s - Assert.assertEquals(5500.0, tripDuration, 0.0); - } - - // 600 minutes additional transfer time - miss all departures - { - TransferFixture f = new TransferFixture(600 * 60.0); - TransitRouter router = createTransitRouter(f.schedule, f.routerConfig, routerType); - Coord fromCoord = f.fromFacility.getCoord(); - Coord toCoord = f.toFacility.getCoord(); - List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 7.0*3600 + 50*60, null)); - Assert.assertNull("The router should not find a route and return null, but did return something else.", legs); - - RoutingModule walkRoutingModule = DefaultRoutingModules.createTeleportationRouter(TransportMode.walk, f.scenario, - f.config.plansCalcRoute().getModeRoutingParams().get(TransportMode.walk)); - - TransitRouterWrapper wrapper = new TransitRouterWrapper( - router, - f.schedule, - f.scenario.getNetwork(), // use a walk router in case no PT path is found - walkRoutingModule); - - List planElements = (List) wrapper.calcRoute(DefaultRoutingRequest.withoutAttributes(f.fromFacility, f.toFacility, 7.0*3600 + 50*60, null)); - Assert.assertNull("The router should not find a route and return null, but did return something else.", planElements); - } - } - - private static double calcTripDuration(List planElements) { - double duration = 0.0; - for (PlanElement pe : planElements) { - if (pe instanceof Activity) { - Activity act = (Activity) pe; - if (act.getStartTime().isDefined() && act.getEndTime().isDefined()) { - double startTime = act.getStartTime().seconds(); - double endTime = act.getEndTime().seconds(); - duration += (endTime - startTime); - } - } else if (pe instanceof Leg) { - Leg leg = (Leg) pe; - duration += leg.getTravelTime().seconds(); - } - } - return duration; - } - - /** - * Generates the following network for testing: - *
          -	 *                (5)
          -	 *                 |
          -	 *                 3
          -	 *                 |
          -	 * (1)---1---(2)  (4)  (6)---4---(7)
          -	 *                 |
          -	 *                 2
          -	 *                 |
          -	 *                (3)
          -	 * 
          - * Each link represents a transit line. Between the stops (2) and (4) and also - * between (4) and (6) agents must walk. - * - * @author mrieser - */ - private static class WalkFixture { - - /*package*/ final MutableScenario scenario; - /*package*/ final TransitSchedule schedule; - /*package*/ final TransitRouterConfig routerConfig; - - final Coord coord1; - final Coord coord2; - final Coord coord3; - final Coord coord4; - final Coord coord5; - final Coord coord6; - final Coord coord7; - - final TransitStopFacility stop1; - final TransitStopFacility stop2; - final TransitStopFacility stop3; - final TransitStopFacility stop4; - final TransitStopFacility stop5; - final TransitStopFacility stop6; - final TransitStopFacility stop7; - - /*package*/ WalkFixture() { - this.scenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); - this.scenario.getConfig().transit().setUseTransit(true); - this.routerConfig = new TransitRouterConfig(this.scenario.getConfig().planCalcScore(), - this.scenario.getConfig().plansCalcRoute(), this.scenario.getConfig().transitRouter(), - this.scenario.getConfig().vspExperimental()); - this.routerConfig.setSearchRadius(500.0); - this.routerConfig.setBeelineWalkConnectionDistance(100.0); - this.routerConfig.setBeelineWalkSpeed(10.0); // so the agents can walk the distance in 10 seconds - - double x = 0; - this.coord1 = new Coord(x, (double) 0); - x += 1000; - this.coord2 = new Coord(x, (double) 0); - x += (this.routerConfig.getBeelineWalkConnectionDistance() * 0.75); - double y = -1000; - this.coord3 = new Coord(x, y); - this.coord4 = new Coord(x, (double) 0); - this.coord5 = new Coord(x, (double) 1000); - x += (this.routerConfig.getBeelineWalkConnectionDistance() * 0.75); - this.coord6 = new Coord(x, (double) 0); - x += 1000; - this.coord7 = new Coord(x, (double) 0); - - // network - Network network = this.scenario.getNetwork(); - Node node1 = network.getFactory().createNode(Id.create("1", Node.class), this.coord1); - Node node2 = network.getFactory().createNode(Id.create("2", Node.class), this.coord2); - Node node3 = network.getFactory().createNode(Id.create("3", Node.class), this.coord3); - Node node4 = network.getFactory().createNode(Id.create("4", Node.class), this.coord4); - Node node5 = network.getFactory().createNode(Id.create("5", Node.class), this.coord5); - Node node6 = network.getFactory().createNode(Id.create("6", Node.class), this.coord6); - Node node7 = network.getFactory().createNode(Id.create("7", Node.class), this.coord7); - network.addNode(node1); - network.addNode(node2); - network.addNode(node3); - network.addNode(node4); - network.addNode(node5); - network.addNode(node6); - network.addNode(node7); - Link link1 = network.getFactory().createLink(Id.create("1", Link.class), node1, node2); - Link link2 = network.getFactory().createLink(Id.create("2", Link.class), node3, node4); - Link link3 = network.getFactory().createLink(Id.create("3", Link.class), node4, node5); - Link link4 = network.getFactory().createLink(Id.create("4", Link.class), node6, node7); - network.addLink(link1); - network.addLink(link2); - network.addLink(link3); - network.addLink(link4); - - // schedule - this.schedule = this.scenario.getTransitSchedule(); - TransitScheduleFactory sb = this.schedule.getFactory(); - - this.stop1 = sb.createTransitStopFacility(Id.create("1", TransitStopFacility.class), this.coord1, false); - this.stop2 = sb.createTransitStopFacility(Id.create("2", TransitStopFacility.class), this.coord2, false); - this.stop3 = sb.createTransitStopFacility(Id.create("3", TransitStopFacility.class), this.coord3, false); - this.stop4 = sb.createTransitStopFacility(Id.create("4", TransitStopFacility.class), this.coord4, false); - this.stop5 = sb.createTransitStopFacility(Id.create("5", TransitStopFacility.class), this.coord5, false); - this.stop6 = sb.createTransitStopFacility(Id.create("6", TransitStopFacility.class), this.coord6, false); - this.stop7 = sb.createTransitStopFacility(Id.create("7", TransitStopFacility.class), this.coord7, false); - this.stop1.setLinkId(link1.getId()); - this.stop2.setLinkId(link1.getId()); - this.stop3.setLinkId(link2.getId()); - this.stop4.setLinkId(link2.getId()); - this.stop5.setLinkId(link3.getId()); - this.stop6.setLinkId(link4.getId()); - this.stop7.setLinkId(link4.getId()); - - { // line 1 - TransitLine tLine = sb.createTransitLine(Id.create("1", TransitLine.class)); - { - NetworkRoute netRoute = RouteUtils.createLinkNetworkRouteImpl(link1.getId(), link1.getId()); - List stops = new ArrayList<>(2); - stops.add(sb.createTransitRouteStop(this.stop1, 0, 0)); - stops.add(sb.createTransitRouteStop(this.stop2, 50, 50)); - TransitRoute tRoute = sb.createTransitRoute(Id.create("1a", TransitRoute.class), netRoute, stops, "bus"); - tRoute.addDeparture(sb.createDeparture(Id.create("1a1", Departure.class), 1000)); - tLine.addRoute(tRoute); - } - this.schedule.addTransitLine(tLine); - } - - { // line 2 - TransitLine tLine = sb.createTransitLine(Id.create("2", TransitLine.class)); - { - NetworkRoute netRoute = RouteUtils.createLinkNetworkRouteImpl(link2.getId(), link3.getId()); - List stops = new ArrayList<>(3); - stops.add(sb.createTransitRouteStop(this.stop3, 0, 0)); - stops.add(sb.createTransitRouteStop(this.stop4, 50, 50)); - stops.add(sb.createTransitRouteStop(this.stop5, 100, 100)); - TransitRoute tRoute = sb.createTransitRoute(Id.create("2a", TransitRoute.class), netRoute, stops, "bus"); - tRoute.addDeparture(sb.createDeparture(Id.create("2a1", Departure.class), 1000)); - tLine.addRoute(tRoute); - } - this.schedule.addTransitLine(tLine); - } - - { // line 3 - TransitLine tLine = sb.createTransitLine(Id.create("3", TransitLine.class)); - { - NetworkRoute netRoute = RouteUtils.createLinkNetworkRouteImpl(link4.getId(), link4.getId()); - List stops = new ArrayList<>(2); - stops.add(sb.createTransitRouteStop(this.stop6, 0, 0)); - stops.add(sb.createTransitRouteStop(this.stop7, 50, 50)); - TransitRoute tRoute = sb.createTransitRoute(Id.create("3a", TransitRoute.class), netRoute, stops, "train"); - tRoute.addDeparture(sb.createDeparture(Id.create("3a1", Departure.class), 1070)); - tLine.addRoute(tRoute); - } - this.schedule.addTransitLine(tLine); - } - } - - } - - /** - * Generates the following network for testing: - *
          -	 *  (n) node
          -	 *  [s] stop facilities
          -	 *   l  link
          -	 *
          -	 *  [0]       [1]
          -	 *  (0)---0---(1)---1---(2)
          -	 *            [2]       [3]
          -	 *
          -	 * 
          - * - * Simple setup with one line from 0 to 1 and one from 2 to 3. - * - * Departures are every 5 minutes. PT travel time from (1) to (2) and from (2) to (1) is one hour. - * A short cut is realized via an entry in the transfer matrix (5 minutes). - * - * @author cdobler - */ - private static class TransferFixture { - - /*package*/ final Config config; - /*package*/ final Scenario scenario; - /*package*/ final TransitSchedule schedule; - /*package*/ final TransitRouterConfig routerConfig; - - final TransitStopFacility stop0; - final TransitStopFacility stop1; - final TransitStopFacility stop2; - final TransitStopFacility stop3; - - final ActivityFacility fromFacility; - final ActivityFacility toFacility; - - /*package*/ TransferFixture(double additionalTransferTime) { - this.config = ConfigUtils.createConfig(); - this.config.transitRouter().setAdditionalTransferTime(additionalTransferTime); - this.scenario = ScenarioUtils.createScenario(this.config); - this.scenario.getConfig().transit().setUseTransit(true); - this.routerConfig = new TransitRouterConfig(this.scenario.getConfig().planCalcScore(), this.scenario.getConfig().plansCalcRoute(), this.scenario.getConfig().transitRouter(), this.scenario.getConfig().vspExperimental()); - this.routerConfig.setSearchRadius(500.0); - this.routerConfig.setBeelineWalkConnectionDistance(100.0); - this.routerConfig.setBeelineWalkSpeed(1.0); // so the agents can walk the distance in 100 seconds - - // network - Network network = this.scenario.getNetwork(); - - Node node0 = network.getFactory().createNode(Id.create("0", Node.class), new Coord(0, 1000)); - Node node1 = network.getFactory().createNode(Id.create("1", Node.class), new Coord(25000, 1000)); - Node node2 = network.getFactory().createNode(Id.create("2", Node.class), new Coord(50000, 1000)); - network.addNode(node0); - network.addNode(node1); - network.addNode(node2); - - Link link0 = network.getFactory().createLink(Id.create("0", Link.class), node0, node1); - Link link1 = network.getFactory().createLink(Id.create("1", Link.class), node1, node2); - network.addLink(link0); - network.addLink(link1); - - // facilities - ActivityFacilities facilities = this.scenario.getActivityFacilities(); - - this.fromFacility = facilities.getFactory().createActivityFacility(Id.create("fromFacility", ActivityFacility.class), new Coord(0, 1102)); - this.toFacility = facilities.getFactory().createActivityFacility(Id.create("toFacility", ActivityFacility.class), new Coord(50000, 898)); - facilities.addActivityFacility(this.fromFacility); - facilities.addActivityFacility(this.toFacility); - - // schedule - this.schedule = this.scenario.getTransitSchedule(); - TransitScheduleFactory sb = this.schedule.getFactory(); - - this.stop0 = sb.createTransitStopFacility(Id.create("0", TransitStopFacility.class), new Coord(0, 1002), false); - this.stop1 = sb.createTransitStopFacility(Id.create("1", TransitStopFacility.class), new Coord(25000, 1002), false); - this.stop2 = sb.createTransitStopFacility(Id.create("2", TransitStopFacility.class), new Coord(25000, 998), false); - this.stop3 = sb.createTransitStopFacility(Id.create("3", TransitStopFacility.class), new Coord(50000, 998), false); - this.schedule.addStopFacility(this.stop0); - this.schedule.addStopFacility(this.stop1); - this.schedule.addStopFacility(this.stop2); - this.schedule.addStopFacility(this.stop3); - this.stop0.setLinkId(link0.getId()); - this.stop1.setLinkId(link0.getId()); - this.stop2.setLinkId(link1.getId()); - this.stop3.setLinkId(link1.getId()); - - // route from 0 to 1 - { - TransitLine line0to1 = sb.createTransitLine(Id.create("0to1", TransitLine.class)); - this.schedule.addTransitLine(line0to1); - NetworkRoute netRoute = RouteUtils.createLinkNetworkRouteImpl(link0.getId(), link0.getId()); - List> routeLinks = new ArrayList<>(); - netRoute.setLinkIds(link0.getId(), routeLinks, link0.getId()); - List stops = new ArrayList<>(); - stops.add(sb.createTransitRouteStopBuilder(this.stop0).departureOffset(0.0).build()); - stops.add(sb.createTransitRouteStopBuilder(this.stop1).arrivalOffset(5*60.0).build()); - TransitRoute route = sb.createTransitRoute(Id.create("0to1", TransitRoute.class), netRoute, stops, "train"); - line0to1.addRoute(route); - - route.addDeparture(sb.createDeparture(Id.create("l0to1 d0", Departure.class), 8.0*3600)); - route.addDeparture(sb.createDeparture(Id.create("l0to1 d1", Departure.class), 9.0*3600)); - route.addDeparture(sb.createDeparture(Id.create("l0to1 d2", Departure.class), 10.0*3600)); - route.addDeparture(sb.createDeparture(Id.create("l0to1 d3", Departure.class), 11.0*3600)); - route.addDeparture(sb.createDeparture(Id.create("l0to1 d4", Departure.class), 12.0*3600)); - } - - // route from 2 to 3 - { - TransitLine line2to3 = sb.createTransitLine(Id.create("2to3", TransitLine.class)); - this.schedule.addTransitLine(line2to3); - NetworkRoute netRoute = RouteUtils.createLinkNetworkRouteImpl(link1.getId(), link1.getId()); - List> routeLinks = new ArrayList<>(); - netRoute.setLinkIds(link1.getId(), routeLinks, link1.getId()); - List stops = new ArrayList<>(); - stops.add(sb.createTransitRouteStopBuilder(this.stop2).departureOffset(0.0).build()); - stops.add(sb.createTransitRouteStopBuilder(this.stop3).arrivalOffset(5*60.0).build()); - TransitRoute route = sb.createTransitRoute(Id.create("2to3", TransitRoute.class), netRoute, stops, "train"); - line2to3.addRoute(route); - - route.addDeparture(sb.createDeparture(Id.create("l2to3 d0", Departure.class), 8.0*3600 + 15 * 60)); - route.addDeparture(sb.createDeparture(Id.create("l2to3 d1", Departure.class), 9.0*3600 + 15 * 60)); - route.addDeparture(sb.createDeparture(Id.create("l2to3 d2", Departure.class), 10.0*3600 + 15 * 60)); - route.addDeparture(sb.createDeparture(Id.create("l2to3 d3", Departure.class), 11.0*3600 + 15 * 60)); - route.addDeparture(sb.createDeparture(Id.create("l2to3 d4", Departure.class), 12.0*3600 + 15 * 60)); - } - } - } -} diff --git a/matsim/src/test/java/org/matsim/pt/router/TransitRouterModuleTest.java b/matsim/src/test/java/org/matsim/pt/router/TransitRouterModuleTest.java index 11b6c5b8226..196ff84dc0c 100644 --- a/matsim/src/test/java/org/matsim/pt/router/TransitRouterModuleTest.java +++ b/matsim/src/test/java/org/matsim/pt/router/TransitRouterModuleTest.java @@ -18,35 +18,13 @@ public class TransitRouterModuleTest { @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - @Test - public void testTransitRoutingAlgorithm_DependencyInjection_Dijkstra() { - Fixture f = new Fixture(); - f.config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); - f.config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - f.config.controler().setLastIteration(0); - f.config.controler().setDumpDataAtEnd(false); - - Controler controler = new Controler(f.scenario); - controler.addOverridingModule(new AbstractModule() { - @Override - public void install() { - bindMobsim().to(DummyMobsim.class); - } - }); - controler.run(); - Injector injector = controler.getInjector(); - - TransitRouter router = injector.getInstance(TransitRouter.class); - Assert.assertEquals(TransitRouterImpl.class, router.getClass()); - } - @Test public void testTransitRoutingAlgorithm_DependencyInjection_Raptor() { Fixture f = new Fixture(); f.config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.SwissRailRaptor); - f.config.controler().setOutputDirectory(this.utils.getOutputDirectory()); - f.config.controler().setLastIteration(0); - f.config.controler().setDumpDataAtEnd(false); + f.config.controller().setOutputDirectory(this.utils.getOutputDirectory()); + f.config.controller().setLastIteration(0); + f.config.controller().setDumpDataAtEnd(false); Controler controler = new Controler(f.scenario); controler.addOverridingModule(new AbstractModule() { @@ -71,4 +49,4 @@ public void run() { } } -} \ No newline at end of file +} diff --git a/matsim/src/test/java/org/matsim/pt/router/TransitRouterNetworkTravelTimeCostTest.java b/matsim/src/test/java/org/matsim/pt/router/TransitRouterNetworkTravelTimeCostTest.java deleted file mode 100644 index 901f33e5737..00000000000 --- a/matsim/src/test/java/org/matsim/pt/router/TransitRouterNetworkTravelTimeCostTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * TransitRouterNetworkTravelTimeCostTest.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2009 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.pt.router; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.matsim.pt.router.TransitRouterNetwork.TransitRouterNetworkLink; -import org.matsim.testcases.MatsimTestUtils; - -/** - * @author mrieser - */ -public class TransitRouterNetworkTravelTimeCostTest { - - @Test public void testTravelTime() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule); - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - // find the link connecting C and G on the red line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == f.redLine) && - (link.fromNode.stop.getStopFacility().getName().equals("C")) && - (link.toNode.stop.getStopFacility().getName().equals("G"))) { - testLink = link; - } - } - assertEquals(9.0*60, tc.getLinkTravelTime(testLink, 6.0*3600, null, null), MatsimTestUtils.EPSILON); - } - - @Test public void testWaitingTime() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule); - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - // find the link connecting C and D on the blue line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == f.blueLine) && - (link.fromNode.stop.getStopFacility().getName().equals("C")) && - (link.toNode.stop.getStopFacility().getName().equals("D"))) { - testLink = link; - } - } - assertEquals(2.0*60 + 7.0*60, tc.getLinkTravelTime(testLink, 6.0*3600, null, null), MatsimTestUtils.EPSILON); - assertEquals(1.0*60 + 7.0*60, tc.getLinkTravelTime(testLink, 6.0*3600 + 60, null, null), MatsimTestUtils.EPSILON); - assertEquals(0.0*60 + 7.0*60, tc.getLinkTravelTime(testLink, 6.0*3600 + 120, null, null), MatsimTestUtils.EPSILON); - assertEquals(20.0*60 -1 + 7.0*60, tc.getLinkTravelTime(testLink, 6.0*3600 + 121, null, null), MatsimTestUtils.EPSILON); - } - - @Test public void testTravelTimeAfterMidnight() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule); - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - // find the link connecting C and D on the blue line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == f.blueLine) && - (link.fromNode.stop.getStopFacility().getName().equals("C")) && - (link.toNode.stop.getStopFacility().getName().equals("D"))) { - testLink = link; - } - } - // planned departure at 25:00, has to wait until 05:22 = 29:22 - assertEquals(22.0*60 + 4.0*3600 + 7.0*60, tc.getLinkTravelTime(testLink, 25.0*3600, null, null), MatsimTestUtils.EPSILON); - // planned departure at 47:00, has to wait until 05:22 = 53:22 - assertEquals(22.0*60 + 6.0*3600 + 7.0*60, tc.getLinkTravelTime(testLink, 47.0*3600, null, null), MatsimTestUtils.EPSILON); - // planned departure at 49:00, has to wait until 05:22 = 53:22, tests explicitly > 2*MIDNIGHT - assertEquals(22.0*60 + 4.0*3600 + 7.0*60, tc.getLinkTravelTime(testLink, 49.0*3600, null, null), MatsimTestUtils.EPSILON); - } - - @Test public void testTravelCostLineSwitch() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule); - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - // find the link connecting C and D on the blue line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == null) && - (link.fromNode.stop.getStopFacility().getName().equals("C")) && - (link.toNode.stop.getStopFacility().getName().equals("C"))) { - testLink = link; - } - } - - double oldCost = - conf.getUtilityOfLineSwitch_utl(); - double cost1 = tc.getLinkTravelDisutility(testLink, 7.0*3600, null, null, null); - conf.setUtilityOfLineSwitch_utl(0.0); - double cost2 = tc.getLinkTravelDisutility(testLink, 6.0*3600, null, null, null); // use different time because of internal caching effects - assertEquals(oldCost, cost1 - cost2, MatsimTestUtils.EPSILON); - conf.setUtilityOfLineSwitch_utl(-40.125); - double cost3 = tc.getLinkTravelDisutility(testLink, 5.0*3600, null, null, null); - assertEquals(40.125, cost3 - cost2, MatsimTestUtils.EPSILON); - } - - @Test public void testTravelCostLineSwitch_AdditionalTransferTime() { - Fixture f = new Fixture(); - f.init(); - TransitRouterConfig conf = new TransitRouterConfig(f.scenario.getConfig().planCalcScore(), - f.scenario.getConfig().plansCalcRoute(), f.scenario.getConfig().transitRouter(), - f.scenario.getConfig().vspExperimental()); - TransitRouterNetworkTravelTimeAndDisutility tc = new TransitRouterNetworkTravelTimeAndDisutility(conf); - TransitRouterImpl router = new TransitRouterImpl(conf, f.schedule); - TransitRouterNetwork routerNet = router.getTransitRouterNetwork(); - // find the link connecting C and D on the blue line - TransitRouterNetworkLink testLink = null; - for (TransitRouterNetworkLink link : routerNet.getLinks().values()) { - if ((link.getLine() == null) && - (link.fromNode.stop.getStopFacility().getName().equals("C")) && - (link.toNode.stop.getStopFacility().getName().equals("C"))) { - testLink = link; - } - } - - double oldCost = - conf.getUtilityOfLineSwitch_utl(); - double cost1 = tc.getLinkTravelDisutility(testLink, 7.0*3600, null, null, null); - conf.setUtilityOfLineSwitch_utl(0.0); - double cost2 = tc.getLinkTravelDisutility(testLink, 6.0*3600, null, null, null); // use different time because of internal caching effects - assertEquals(oldCost, cost1 - cost2, MatsimTestUtils.EPSILON); - conf.setAdditionalTransferTime(120.0); - double cost3 = tc.getLinkTravelDisutility(testLink, 5.0*3600, null, null, null); - assertEquals(-120.0 * conf.getMarginalUtilityOfWaitingPt_utl_s(), cost3 - cost2, MatsimTestUtils.EPSILON); - // test with custom value for utility of waiting, just in case too many of the default marginal utilities are 0.0 - conf.setMarginalUtilityOfWaitingPt_utl_s(-12.0 / 3600.0); - double cost4 = tc.getLinkTravelDisutility(testLink, 7.0*3600, null, null, null); - assertEquals(120.0 * 12.0 / 3600.0, cost4 - cost2, MatsimTestUtils.EPSILON); - } - -} diff --git a/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleReprojectionIOTest.java b/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleReprojectionIOTest.java index 45377793872..526fefcb1d2 100644 --- a/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleReprojectionIOTest.java +++ b/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleReprojectionIOTest.java @@ -54,7 +54,7 @@ */ public class TransitScheduleReprojectionIOTest { private static final Logger log = LogManager.getLogger( TransitScheduleReprojectionIOTest.class ) ; - + private static final String INITIAL_CRS = TransformationFactory.CH1903_LV03_GT; private static final String TARGET_CRS = "EPSG:3857"; private static final CoordinateTransformation transformation = @@ -103,23 +103,23 @@ public void testWithControlerAndConfigParameters() { } final String outputDirectory = utils.getOutputDirectory()+"/output/"; - + // read same thing via scenario loader: Scenario scenario ; { final Config config = ConfigUtils.createConfig( ExamplesUtils.getTestScenarioURL( "pt-tutorial" ) ); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); config.transit().setTransitScheduleFile( "transitschedule.xml" ); config.transit().setUseTransit( true ); config.transit().setInputScheduleCRS( INITIAL_CRS ); config.global().setCoordinateSystem( TARGET_CRS ); - config.controler().setLastIteration( -1 ); - config.controler().setOutputDirectory( outputDirectory ); + config.controller().setLastIteration( -1 ); + config.controller().setOutputDirectory( outputDirectory ); + config.network().setInputFile("multimodalnetwork.xml"); scenario = ScenarioUtils.loadScenario( config ); } - + // TODO: test also with loading from Controler C'tor? - + for ( Id id : originalScenario.getTransitSchedule().getFacilities().keySet() ) { final Coord originalCoord = originalScenario.getTransitSchedule().getFacilities().get( id ).getCoord(); final Coord internalCoord = scenario.getTransitSchedule().getFacilities().get( id ).getCoord(); @@ -129,10 +129,10 @@ public void testWithControlerAndConfigParameters() { transformation.transform(originalCoord), internalCoord); } - + final Controler controler = new Controler( scenario ); controler.run(); - + Scenario dumpedScenario ; { final Config config = ConfigUtils.createConfig( ExamplesUtils.getTestScenarioURL( "pt-tutorial" ) ); @@ -160,7 +160,7 @@ public void testWithControlerAndAttributes() { originalScenario = ScenarioUtils.createScenario( config ); new TransitScheduleReader( originalScenario ).readURL( ConfigGroup.getInputFileURL( config.getContext(), "transitschedule.xml" ) ); } - + final String outputDirectory = utils.getOutputDirectory()+"/output/"; // same thing via scenario loader, @@ -172,23 +172,23 @@ public void testWithControlerAndAttributes() { final String withAttributes = new File( utils.getOutputDirectory() ).getAbsolutePath() + "/transitschedule.xml"; // (need the absolute path since later it is put into the config, and that will otherwise be relative to some other context. kai, sep'18) new TransitScheduleWriter( originalScenario.getTransitSchedule() ).writeFile( withAttributes ); - + final Config config = ConfigUtils.createConfig( ExamplesUtils.getTestScenarioURL( "pt-tutorial" ) ); - config.transit().setRoutingAlgorithmType(TransitRoutingAlgorithmType.DijkstraBased); config.transit().setTransitScheduleFile( withAttributes ); config.transit().setUseTransit( true ); config.transit().setInputScheduleCRS( INITIAL_CRS ); + config.network().setInputFile("multimodalnetwork.xml"); // yyyyyy Is it so plausible that this is given here when the test is about having this in the file? kai, sep'18 config.global().setCoordinateSystem( TARGET_CRS ); - config.controler().setLastIteration( -1 ); - config.controler().setOutputDirectory( outputDirectory ); - + config.controller().setLastIteration( -1 ); + config.controller().setOutputDirectory( outputDirectory ); + log.info( "" ) ; log.info("just before we are getting the exception:") ; log.info( "context=" + config.getContext() ) ; log.info( "transitScheduleFilename=" + withAttributes ) ; log.info("") ; - + // TODO: test also with loading from Controler C'tor? scenario = ScenarioUtils.loadScenario( config ); } diff --git a/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java b/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java index b54560b533d..b568268cbae 100644 --- a/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java +++ b/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java @@ -24,24 +24,21 @@ import org.junit.Assert; import org.junit.rules.TestWatcher; import org.junit.runner.Description; -import org.matsim.api.core.v01.population.Population; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ConfigUtils; import org.matsim.core.gbl.MatsimRandom; -import org.matsim.core.population.PopulationUtils; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.io.UncheckedIOException; import org.matsim.core.utils.misc.CRCChecksum; import org.matsim.utils.eventsfilecomparison.EventsFileComparator; import java.io.BufferedReader; import java.io.File; import java.io.IOException; +import java.io.UncheckedIOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; -import java.security.Permission; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -116,7 +113,7 @@ public Config createConfigWithInputResourcePathAsContext() { Config config = ConfigUtils.createConfig(); config.setContext(inputResourcePath()); this.outputDirectory = getOutputDirectory(); - config.controler().setOutputDirectory(this.outputDirectory); + config.controller().setOutputDirectory(this.outputDirectory); return config; } @@ -124,7 +121,7 @@ public Config createConfigWithClassInputResourcePathAsContext() { Config config = ConfigUtils.createConfig(); config.setContext(classInputResourcePath()); this.outputDirectory = getOutputDirectory(); - config.controler().setOutputDirectory(this.outputDirectory); + config.controller().setOutputDirectory(this.outputDirectory); return config; } @@ -132,7 +129,7 @@ public Config createConfigWithPackageInputResourcePathAsContext() { Config config = ConfigUtils.createConfig(); config.setContext(packageInputResourcePath()); this.outputDirectory = getOutputDirectory(); - config.controler().setOutputDirectory(this.outputDirectory); + config.controller().setOutputDirectory(this.outputDirectory); return config; } @@ -154,7 +151,7 @@ public URL packageInputResourcePath() { private URL getResourceNotNull(String pathString) { URL resource = this.testClass.getResource(pathString); if (resource == null) { - throw new UncheckedIOException("Not found: "+pathString); + throw new UncheckedIOException(new IOException("Not found: "+pathString)); } return resource; } @@ -164,7 +161,7 @@ public Config createConfigWithTestInputFilePathAsContext() { Config config = ConfigUtils.createConfig(); config.setContext(new File(this.getInputDirectory()).toURI().toURL()); this.outputDirectory = getOutputDirectory(); - config.controler().setOutputDirectory(this.outputDirectory); + config.controller().setOutputDirectory(this.outputDirectory); return config; } catch (MalformedURLException e) { throw new RuntimeException(e); @@ -175,7 +172,7 @@ public Config createConfig(URL context) { Config config = ConfigUtils.createConfig(); config.setContext(context); this.outputDirectory = getOutputDirectory(); - config.controler().setOutputDirectory(this.outputDirectory); + config.controller().setOutputDirectory(this.outputDirectory); return config; } @@ -194,7 +191,7 @@ public Config loadConfig(final String configfile, final ConfigGroup... customGro config = ConfigUtils.createConfig( customGroups ); } this.outputDirectory = getOutputDirectory(); - config.controler().setOutputDirectory(this.outputDirectory); + config.controller().setOutputDirectory(this.outputDirectory); return config; } @@ -206,14 +203,14 @@ public Config loadConfig(final URL configfile, final ConfigGroup... customGroups config = ConfigUtils.createConfig( customGroups ); } this.outputDirectory = getOutputDirectory(); - config.controler().setOutputDirectory(this.outputDirectory); + config.controller().setOutputDirectory(this.outputDirectory); return config; } public Config createConfig(final ConfigGroup... customGroups) { Config config = ConfigUtils.createConfig( customGroups ); this.outputDirectory = getOutputDirectory(); - config.controler().setOutputDirectory(this.outputDirectory); + config.controller().setOutputDirectory(this.outputDirectory); return config; } diff --git a/matsim/src/test/java/org/matsim/withinday/controller/ExampleWithinDayControllerTest.java b/matsim/src/test/java/org/matsim/withinday/controller/ExampleWithinDayControllerTest.java index 29b62c7ad50..01a9e44a166 100644 --- a/matsim/src/test/java/org/matsim/withinday/controller/ExampleWithinDayControllerTest.java +++ b/matsim/src/test/java/org/matsim/withinday/controller/ExampleWithinDayControllerTest.java @@ -27,13 +27,12 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Leg; import org.matsim.core.config.Config; -import org.matsim.core.config.groups.ControlerConfigGroup; +import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.population.algorithms.PersonPrepareForSim; import org.matsim.core.population.algorithms.PlanAlgorithm; import org.matsim.core.router.PlanRouter; import org.matsim.core.router.TripRouterFactoryBuilderWithDefaults; -import org.matsim.core.router.costcalculators.FreespeedTravelTimeAndDisutility; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.timing.TimeInterpretation; import org.matsim.testcases.MatsimTestUtils; @@ -46,8 +45,8 @@ public class ExampleWithinDayControllerTest { @Test public void testRun() { Config config = utils.loadConfig("test/scenarios/equil/config.xml"); - config.controler().setLastIteration(1); - config.controler().setRoutingAlgorithmType(ControlerConfigGroup.RoutingAlgorithmType.Dijkstra); + config.controller().setLastIteration(1); + config.controller().setRoutingAlgorithmType(ControllerConfigGroup.RoutingAlgorithmType.Dijkstra); Scenario scenario = ScenarioUtils.loadScenario(config); preparePlans(scenario); final Controler controler = new Controler(scenario); diff --git a/matsim/src/test/java/org/matsim/withinday/controller/ExperiencedPlansWriterTest.java b/matsim/src/test/java/org/matsim/withinday/controller/ExperiencedPlansWriterTest.java index 53e09f74ef5..a9290886cb9 100644 --- a/matsim/src/test/java/org/matsim/withinday/controller/ExperiencedPlansWriterTest.java +++ b/matsim/src/test/java/org/matsim/withinday/controller/ExperiencedPlansWriterTest.java @@ -37,8 +37,8 @@ import org.matsim.api.core.v01.population.*; 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.PlanCalcScoreConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; @@ -81,16 +81,16 @@ public void testWriteFile() { Config config = ConfigUtils.createConfig(); - config.controler().setOutputDirectory(this.utils.getOutputDirectory()); + config.controller().setOutputDirectory(this.utils.getOutputDirectory()); config.qsim().setEndTime(24 * 3600); - config.controler().setLastIteration(0); - config.controler().setRoutingAlgorithmType( ControlerConfigGroup.RoutingAlgorithmType.Dijkstra ); + config.controller().setLastIteration(0); + config.controller().setRoutingAlgorithmType( ControllerConfigGroup.RoutingAlgorithmType.Dijkstra ); ActivityParams homeParams = new ActivityParams("home"); homeParams.setTypicalDuration(16*3600); - config.planCalcScore().addActivityParams(homeParams); + config.scoring().addActivityParams(homeParams); Scenario scenario = ScenarioUtils.createScenario(config); @@ -101,10 +101,10 @@ public void testWriteFile() { population.addPerson(createPerson(scenario, "p02")); Controler controler = new Controler(scenario); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setWriteEventsInterval(0); - controler.getConfig().controler().setOverwriteFileSetting( + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setWriteEventsInterval(0); + controler.getConfig().controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); controler.addOverridingModule(new AbstractModule() { @Override diff --git a/matsim/src/test/java/org/matsim/withinday/replanning/identifiers/tools/ActivityReplanningMapTest.java b/matsim/src/test/java/org/matsim/withinday/replanning/identifiers/tools/ActivityReplanningMapTest.java index 2c0bcdcbc0f..4aebdd6bb91 100644 --- a/matsim/src/test/java/org/matsim/withinday/replanning/identifiers/tools/ActivityReplanningMapTest.java +++ b/matsim/src/test/java/org/matsim/withinday/replanning/identifiers/tools/ActivityReplanningMapTest.java @@ -33,7 +33,7 @@ import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Person; 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.controler.Controler; @@ -103,11 +103,11 @@ public class ActivityReplanningMapTest { Config config = utils.loadConfig("test/scenarios/equil/config.xml"); QSimConfigGroup qSimConfig = config.qsim(); qSimConfig.setNumberOfThreads(2); - config.controler().setMobsim("qsim"); - config.controler().setLastIteration(0); + config.controller().setMobsim("qsim"); + config.controller().setLastIteration(0); config.qsim().setStartTime(0.0); config.qsim().setSimStarttimeInterpretation(QSimConfigGroup.StarttimeInterpretation.onlyUseStarttime); - config.controler().setRoutingAlgorithmType( ControlerConfigGroup.RoutingAlgorithmType.Dijkstra ); + config.controller().setRoutingAlgorithmType( ControllerConfigGroup.RoutingAlgorithmType.Dijkstra ); Controler controler = new Controler(config); controler.addOverridingModule(new WithinDayModule()); @@ -117,10 +117,10 @@ public void install() { addMobsimListenerBinding().to(MobsimListenerForTests.class); } }); - controler.getConfig().controler().setCreateGraphs(false); - controler.getConfig().controler().setDumpDataAtEnd(false); - controler.getConfig().controler().setWriteEventsInterval(0); - controler.getConfig().controler().setWritePlansInterval(0); + controler.getConfig().controller().setCreateGraphs(false); + controler.getConfig().controller().setDumpDataAtEnd(false); + controler.getConfig().controller().setWriteEventsInterval(0); + controler.getConfig().controller().setWritePlansInterval(0); controler.run(); } diff --git a/matsim/src/test/java/org/matsim/withinday/replanning/identifiers/tools/LinkReplanningMapTest.java b/matsim/src/test/java/org/matsim/withinday/replanning/identifiers/tools/LinkReplanningMapTest.java index 3d5c5a1a42c..7dddab430db 100644 --- a/matsim/src/test/java/org/matsim/withinday/replanning/identifiers/tools/LinkReplanningMapTest.java +++ b/matsim/src/test/java/org/matsim/withinday/replanning/identifiers/tools/LinkReplanningMapTest.java @@ -27,7 +27,7 @@ import org.junit.Rule; import org.junit.Test; 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.controler.Controler; @@ -58,9 +58,9 @@ public class LinkReplanningMapTest { qSimConfig.setNumberOfThreads(2); qSimConfig.setFlowCapFactor(100.0); // ensure that agents don't have to wait at an intersection qSimConfig.setStorageCapFactor(100.0); // ensure that agents don't have to wait at an intersection - config.controler().setMobsim("qsim"); - config.controler().setLastIteration(0); - config.controler().setRoutingAlgorithmType( ControlerConfigGroup.RoutingAlgorithmType.Dijkstra ); + config.controller().setMobsim("qsim"); + config.controller().setLastIteration(0); + config.controller().setRoutingAlgorithmType( ControllerConfigGroup.RoutingAlgorithmType.Dijkstra ); Controler controler = new Controler(config); controler.addOverridingModule(new WithinDayModule()); diff --git a/matsim/src/test/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeTest.java b/matsim/src/test/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeTest.java index 90017100395..8a1e15db1f4 100644 --- a/matsim/src/test/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeTest.java +++ b/matsim/src/test/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeTest.java @@ -30,7 +30,7 @@ import org.matsim.api.core.v01.network.Network; 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.QSimConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; @@ -38,7 +38,6 @@ import org.matsim.core.controler.events.StartupEvent; import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.gbl.Gbl; -import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.mobsim.framework.events.MobsimAfterSimStepEvent; import org.matsim.core.mobsim.framework.events.MobsimBeforeSimStepEvent; import org.matsim.core.mobsim.framework.events.MobsimInitializedEvent; @@ -76,21 +75,21 @@ public void testGetLinkTravelTime_noFastCapacityUpdate() { private void testGetLinkTravelTime(boolean isUsingFastCapacityUpdate) { Config config = ConfigUtils.loadConfig("test/scenarios/equil/config.xml"); - config.controler().setOutputDirectory(helper.getOutputDirectory()+"fastCapacityUpdate_"+isUsingFastCapacityUpdate); + config.controller().setOutputDirectory(helper.getOutputDirectory()+"fastCapacityUpdate_"+isUsingFastCapacityUpdate); QSimConfigGroup qSimConfig = config.qsim(); qSimConfig.setNumberOfThreads(2); qSimConfig.setUsingFastCapacityUpdate(isUsingFastCapacityUpdate); - config.controler().setLastIteration(0); + config.controller().setLastIteration(0); - config.controler().setCreateGraphs(false); - config.controler().setDumpDataAtEnd(false); - config.controler().setWriteEventsInterval(0); - config.controler().setWritePlansInterval(0); + config.controller().setCreateGraphs(false); + config.controller().setDumpDataAtEnd(false); + config.controller().setWriteEventsInterval(0); + config.controller().setWritePlansInterval(0); - config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); - config.controler().setRoutingAlgorithmType( ControlerConfigGroup.RoutingAlgorithmType.Dijkstra ); + config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setRoutingAlgorithmType( ControllerConfigGroup.RoutingAlgorithmType.Dijkstra ); config.network().setTimeVariantNetwork(true); diff --git a/matsim/src/test/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeWithNetworkChangeEventsTest.java b/matsim/src/test/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeWithNetworkChangeEventsTest.java index a3a5c4070a1..ef68744005b 100644 --- a/matsim/src/test/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeWithNetworkChangeEventsTest.java +++ b/matsim/src/test/java/org/matsim/withinday/trafficmonitoring/WithinDayTravelTimeWithNetworkChangeEventsTest.java @@ -42,8 +42,8 @@ import org.matsim.api.core.v01.population.PopulationFactory; 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.PlanCalcScoreConfigGroup.ActivityParams; +import org.matsim.core.config.groups.ControllerConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; @@ -58,9 +58,9 @@ /** * Tests if network change events are considered by {@link WithinDayTravelTime}. -* +* * @author ikaddoura -* +* */ public class WithinDayTravelTimeWithNetworkChangeEventsTest { @@ -70,84 +70,84 @@ public class WithinDayTravelTimeWithNetworkChangeEventsTest { private Id link01 = Id.createLinkId("link_0_1"); private Id link12 = Id.createLinkId("link_1_2"); private Id link23 = Id.createLinkId("link_2_3"); - + @Test public final void testTTviaMobSimAfterSimStepListener() { - + String outputDirectory = testUtils.getOutputDirectory() + "output_TTviaMobsimAfterSimStepListener/"; - + final Config config = ConfigUtils.createConfig(); - - config.controler().setFirstIteration(0); - config.controler().setLastIteration(0); - config.controler().setOutputDirectory(outputDirectory); - config.controler().setRoutingAlgorithmType( ControlerConfigGroup.RoutingAlgorithmType.Dijkstra ); + + config.controller().setFirstIteration(0); + config.controller().setLastIteration(0); + config.controller().setOutputDirectory(outputDirectory); + config.controller().setRoutingAlgorithmType( ControllerConfigGroup.RoutingAlgorithmType.Dijkstra ); config.qsim().setStartTime(6. * 3600.); config.qsim().setEndTime(11 * 3600.); - + ActivityParams paramsA = new ActivityParams(); paramsA.setActivityType("home"); paramsA.setTypicalDuration(1234.); - config.planCalcScore().addActivityParams(paramsA); - + config.scoring().addActivityParams(paramsA); + ActivityParams paramsB = new ActivityParams(); paramsB.setActivityType("work"); paramsB.setTypicalDuration(1234.); - config.planCalcScore().addActivityParams(paramsB); - + config.scoring().addActivityParams(paramsB); + config.network().setTimeVariantNetwork(true); - + final Scenario scenario = ScenarioUtils.createScenario(config); createNetwork(scenario); createPopulation(scenario); - + NetworkChangeEvent nce = new NetworkChangeEvent(10. * 3600.); nce.addLink(scenario.getNetwork().getLinks().get(link12)); nce.setFreespeedChange(new ChangeValue(NetworkChangeEvent.ChangeType.ABSOLUTE_IN_SI_UNITS, 1.)); NetworkUtils.addNetworkChangeEvent(scenario.getNetwork(), nce); - + final Controler controler = new Controler(scenario); - controler.getConfig().controler().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); + controler.getConfig().controller().setOverwriteFileSetting(OverwriteFileSetting.overwriteExistingFiles); Set analyzedModes = new HashSet<>(); analyzedModes.add(TransportMode.car); final WithinDayTravelTime travelTime = new WithinDayTravelTime(controler.getScenario(), analyzedModes); - + final TtmobsimListener ttmobsimListener = new TtmobsimListener(nce); controler.addOverridingModule( new AbstractModule() { @Override public void install() { - + this.bind(TravelTime.class).toInstance(travelTime); this.addEventHandlerBinding().toInstance(travelTime); this.addMobsimListenerBinding().toInstance(travelTime); - + this.addMobsimListenerBinding().toInstance(ttmobsimListener); } }) ; - + controler.run(); - + Assert.assertEquals(true, ttmobsimListener.isCase1()); Assert.assertEquals(true, ttmobsimListener.isCase2()); - + } private void createPopulation(Scenario scenario) { Population population = scenario.getPopulation(); PopulationFactory popFactory = scenario.getPopulation().getFactory(); LinkNetworkRouteFactory routeFactory = new LinkNetworkRouteFactory(); - + Leg leg = popFactory.createLeg("car"); List> linkIds = new ArrayList>(); linkIds.add(link12); - + NetworkRoute route = (NetworkRoute) routeFactory.createRoute(link01, link23); route.setLinkIds(link01, linkIds, link23); leg.setRoute(route); - + Person person0 = popFactory.createPerson(Id.createPersonId("person0")); { Plan plan0 = popFactory.createPlan(); @@ -159,8 +159,8 @@ private void createPopulation(Scenario scenario) { plan0.addActivity(workAct0); person0.addPlan(plan0); } - - + + Person person1 = popFactory.createPerson(Id.createPersonId("person1")); { Plan plan1 = popFactory.createPlan(); @@ -172,13 +172,13 @@ private void createPopulation(Scenario scenario) { plan1.addActivity(workAct1); person1.addPlan(plan1); } - + population.addPerson(person0); population.addPerson(person1); } private void createNetwork(Scenario scenario) { - + Network network = scenario.getNetwork(); network.setEffectiveCellSize(7.5); network.setCapacityPeriod(3600.); @@ -187,32 +187,32 @@ private void createNetwork(Scenario scenario) { Node node1 = network.getFactory().createNode(Id.create("1", Node.class), new Coord(1000., 0.)); Node node2 = network.getFactory().createNode(Id.create("2", Node.class), new Coord(2000., 0.)); Node node3 = network.getFactory().createNode(Id.create("3", Node.class), new Coord(3000., 0.)); - + Link link1 = network.getFactory().createLink(link01 , node0, node1); Link link2 = network.getFactory().createLink(link12, node1, node2); Link link3 = network.getFactory().createLink(link23, node2, node3); - + Set modes = new HashSet(); modes.add("car"); - + link1.setAllowedModes(modes); link1.setCapacity(7200); link1.setFreespeed(10.123); link1.setNumberOfLanes(2); link1.setLength(1000); - + link2.setAllowedModes(modes); link2.setCapacity(7200); link2.setFreespeed(10.123); link2.setNumberOfLanes(2); link2.setLength(1000); - + link3.setAllowedModes(modes); link3.setCapacity(7200); link3.setFreespeed(10.123); link3.setNumberOfLanes(2); link3.setLength(1000); - + network.addNode(node0); network.addNode(node1); network.addNode(node2); diff --git a/matsim/src/test/java/org/matsim/withinday/utils/EditRoutesTest.java b/matsim/src/test/java/org/matsim/withinday/utils/EditRoutesTest.java index e26e178fb84..d6d29521b27 100644 --- a/matsim/src/test/java/org/matsim/withinday/utils/EditRoutesTest.java +++ b/matsim/src/test/java/org/matsim/withinday/utils/EditRoutesTest.java @@ -43,8 +43,8 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup; -import org.matsim.core.config.groups.PlansCalcRouteConfigGroup.AccessEgressType; +import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.RoutingConfigGroup.AccessEgressType; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Injector; import org.matsim.core.population.PopulationUtils; @@ -95,7 +95,7 @@ public class EditRoutesTest { int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -155,7 +155,7 @@ public class EditRoutesTest { int scndAct = 2 ; int scndCarLeg = 3 ; // 3-->9 int thrdAct = 4 ; - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndAct = 6 ; scndCarLeg = 9 ; // 3-->9 @@ -232,7 +232,7 @@ public class EditRoutesTest { createScenario(); int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -280,7 +280,7 @@ public class EditRoutesTest { EditRoutes ed = new EditRoutes(scenario.getNetwork(), pathCalculator, scenario.getPopulation().getFactory()); int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -304,7 +304,7 @@ public class EditRoutesTest { int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -324,7 +324,7 @@ public class EditRoutesTest { int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -345,7 +345,7 @@ public class EditRoutesTest { int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -364,7 +364,7 @@ public class EditRoutesTest { int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -383,7 +383,7 @@ public class EditRoutesTest { int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -402,7 +402,7 @@ public class EditRoutesTest { int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -421,7 +421,7 @@ public class EditRoutesTest { int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } @@ -442,7 +442,7 @@ public class EditRoutesTest { int firstCarLeg = 1 ; // 1-->3 int scndCarLeg = 3 ; // 3-->9 - if ( !scenario.getConfig().plansCalcRoute().getAccessEgressType().equals(PlansCalcRouteConfigGroup.AccessEgressType.none) ) { + if ( !scenario.getConfig().routing().getAccessEgressType().equals(RoutingConfigGroup.AccessEgressType.none) ) { firstCarLeg = 3 ; // 1-->3 scndCarLeg = 9 ; // 3-->9 } diff --git a/matsim/src/test/resources/test/input/org/matsim/pt/counts/alight.xml b/matsim/src/test/resources/test/input/org/matsim/pt/counts/alight.xml deleted file mode 100644 index 79b47e2e478..00000000000 --- a/matsim/src/test/resources/test/input/org/matsim/pt/counts/alight.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/matsim/src/test/resources/test/input/org/matsim/pt/counts/board.xml b/matsim/src/test/resources/test/input/org/matsim/pt/counts/board.xml deleted file mode 100644 index 381e85d2a75..00000000000 --- a/matsim/src/test/resources/test/input/org/matsim/pt/counts/board.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/matsim/src/test/resources/test/input/org/matsim/pt/counts/config.xml b/matsim/src/test/resources/test/input/org/matsim/pt/counts/config.xml deleted file mode 100644 index c50817201c1..00000000000 --- a/matsim/src/test/resources/test/input/org/matsim/pt/counts/config.xml +++ /dev/null @@ -1,220 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/matsim/src/test/resources/test/input/org/matsim/pt/counts/configLocal.xml b/matsim/src/test/resources/test/input/org/matsim/pt/counts/configLocal.xml deleted file mode 100644 index 938cc6b78fa..00000000000 --- a/matsim/src/test/resources/test/input/org/matsim/pt/counts/configLocal.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/matsim/src/test/resources/test/input/org/matsim/pt/counts/occupancy.xml b/matsim/src/test/resources/test/input/org/matsim/pt/counts/occupancy.xml deleted file mode 100644 index c324013d5dc..00000000000 --- a/matsim/src/test/resources/test/input/org/matsim/pt/counts/occupancy.xml +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/matsim/src/test/resources/test/input/org/matsim/pt/counts/ptNet.xml b/matsim/src/test/resources/test/input/org/matsim/pt/counts/ptNet.xml deleted file mode 100644 index 28a1af67ab5..00000000000 --- a/matsim/src/test/resources/test/input/org/matsim/pt/counts/ptNet.xml +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/matsim/src/test/resources/test/input/org/matsim/pt/counts/ptPop.xml b/matsim/src/test/resources/test/input/org/matsim/pt/counts/ptPop.xml deleted file mode 100644 index c72e1d3c4b0..00000000000 --- a/matsim/src/test/resources/test/input/org/matsim/pt/counts/ptPop.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/matsim/src/test/resources/test/input/org/matsim/pt/counts/transitSchedule.xml b/matsim/src/test/resources/test/input/org/matsim/pt/counts/transitSchedule.xml deleted file mode 100644 index a52c4a22a81..00000000000 --- a/matsim/src/test/resources/test/input/org/matsim/pt/counts/transitSchedule.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - pt - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/matsim/src/test/resources/test/input/org/matsim/pt/counts/vehicles.xml b/matsim/src/test/resources/test/input/org/matsim/pt/counts/vehicles.xml deleted file mode 100644 index da59ba707bd..00000000000 --- a/matsim/src/test/resources/test/input/org/matsim/pt/counts/vehicles.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - Bus - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/matsim/test/input/org/matsim/core/config/groups/PlanCalcScoreConfigGroupTest/config_v2_w_scoringparams.xml b/matsim/test/input/org/matsim/core/config/groups/ScoringConfigGroupTest/config_v2_w_scoringparams.xml similarity index 100% rename from matsim/test/input/org/matsim/core/config/groups/PlanCalcScoreConfigGroupTest/config_v2_w_scoringparams.xml rename to matsim/test/input/org/matsim/core/config/groups/ScoringConfigGroupTest/config_v2_w_scoringparams.xml diff --git a/matsim/test/input/org/matsim/core/config/groups/PlanCalcScoreConfigGroupTest/config_v2_wo_scoringparams.xml b/matsim/test/input/org/matsim/core/config/groups/ScoringConfigGroupTest/config_v2_wo_scoringparams.xml similarity index 100% rename from matsim/test/input/org/matsim/core/config/groups/PlanCalcScoreConfigGroupTest/config_v2_wo_scoringparams.xml rename to matsim/test/input/org/matsim/core/config/groups/ScoringConfigGroupTest/config_v2_wo_scoringparams.xml diff --git a/matsim/test/input/scenarios/berlin/config_multimodal.xml b/matsim/test/input/scenarios/berlin/config_multimodal.xml index 24f9ce13cbe..b2c4374bbe9 100644 --- a/matsim/test/input/scenarios/berlin/config_multimodal.xml +++ b/matsim/test/input/scenarios/berlin/config_multimodal.xml @@ -23,20 +23,20 @@ - + - + - + - + @@ -45,7 +45,7 @@ - + @@ -55,12 +55,12 @@ - + - + @@ -69,12 +69,12 @@ - + - + @@ -83,7 +83,7 @@ - + diff --git a/matsim/test/input/scenarios/berlin/config_withinday.xml b/matsim/test/input/scenarios/berlin/config_withinday.xml index 68f37a118b0..7e6074c74d0 100644 --- a/matsim/test/input/scenarios/berlin/config_withinday.xml +++ b/matsim/test/input/scenarios/berlin/config_withinday.xml @@ -23,16 +23,16 @@ - + - + - + @@ -46,12 +46,12 @@ - + - + @@ -60,12 +60,12 @@ - + - + @@ -74,7 +74,7 @@ - + diff --git a/pom.xml b/pom.xml index 5a1f03471cf..8be88f56e2f 100644 --- a/pom.xml +++ b/pom.xml @@ -30,11 +30,11 @@ 17 - 2.20.0 + 2.21.0 29.2 1.19.0 7.0.0 - 2.15.2 + 2.15.3 @@ -93,7 +93,7 @@ com.google.guava guava - 32.1.2-jre + 32.1.3-jre org.apache.commons @@ -108,7 +108,7 @@ org.apache.commons commons-compress - 1.23.0 + 1.24.0 commons-logging @@ -185,7 +185,7 @@ com.google.errorprone error_prone_annotations - 2.21.1 + 2.23.0 @@ -203,7 +203,7 @@ org.codehaus.woodstox stax2-api - 4.2.1 + 4.2.2 @@ -264,7 +264,7 @@ org.checkerframework checker-qual - 3.38.0 + 3.39.0 @@ -289,7 +289,7 @@ org.mockito mockito-core - 5.5.0 + 5.6.0 test @@ -308,7 +308,7 @@ net.bytebuddy byte-buddy - 1.14.7 + 1.14.9 test @@ -325,7 +325,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.4.0 + 3.4.1 enforce @@ -412,7 +412,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.5.0 + 3.6.0 org.codehaus.mojo @@ -469,7 +469,7 @@ org.jacoco jacoco-maven-plugin - 0.8.10 + 0.8.11 default-prepare-agent