diff --git a/.github/workflows/code-coverage.yaml b/.github/workflows/code-coverage.yaml index 20ffe41971a..a5a28e1fdef 100644 --- a/.github/workflows/code-coverage.yaml +++ b/.github/workflows/code-coverage.yaml @@ -15,9 +15,9 @@ jobs: uses: actions/checkout@v4 - name: Setup Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - java-version: 17 + java-version: 21 distribution: 'zulu' cache: 'maven' @@ -26,7 +26,7 @@ jobs: run: mvn verify -P jacoco --batch-mode --also-make --projects matsim -Dmaven.test.redirectTestOutputToFile -Dmatsim.preferLocalDtds=true - name: Push coverage to CodeCov - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: files: ./matsim/target/site/jacoco/jacoco.xml diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 021bae1c67c..c3601652607 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -19,15 +19,15 @@ jobs: uses: actions/checkout@v4 - name: Setup Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - java-version: 17 + java-version: 21 distribution: 'zulu' cache: 'maven' # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: 'java' # If you wish to specify custom queries, you can do so here or in a config file. @@ -41,9 +41,9 @@ jobs: # 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 + uses: github/codeql-action/autobuild@v3 - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 with: category: "/language:java" diff --git a/.github/workflows/deploy-dtds.yaml b/.github/workflows/deploy-dtds.yaml new file mode 100644 index 00000000000..bb48f61d27b --- /dev/null +++ b/.github/workflows/deploy-dtds.yaml @@ -0,0 +1,24 @@ +name: deploy-dtds-on-website + +on: + push: + branches: + - master + paths: + - matsim/src/main/resources/dtd + +jobs: + rsync-dtds: + name: sync DTDs to website + runs-on: ubuntu-latest + + steps: + - name: rsync dtds + uses: burnett01/rsync-deployments@7.0.1 + with: + switches: -avz + path: matsim/src/main/resources/dtd/ + remote_path: ~/httpdocs/files/dtd/ + remote_host: ${{ secrets.WEBSITE_DEPLOY_HOST }} + remote_user: ${{ secrets.WEBSITE_DEPLOY_USER }} + remote_key: ${{ secrets.WEBSITE_SSH_PRIVATE_KEY }} diff --git a/.github/workflows/deploy-on-pr-merge.yaml b/.github/workflows/deploy-on-pr-merge.yaml index 332a3dfe178..44828163634 100644 --- a/.github/workflows/deploy-on-pr-merge.yaml +++ b/.github/workflows/deploy-on-pr-merge.yaml @@ -20,9 +20,9 @@ jobs: uses: actions/checkout@v4 - name: Setup Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - java-version: 17 + java-version: 21 distribution: 'zulu' cache: 'maven' server-id: 'matsim-releases' @@ -46,7 +46,7 @@ jobs: - 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 + uses: advanced-security/maven-dependency-submission-action@v4 env: MAVEN_OPTS: -Xmx2g diff --git a/.github/workflows/deploy-on-release-created.yaml b/.github/workflows/deploy-on-release-created.yaml index 7c37d3c6f7d..a490c614a91 100644 --- a/.github/workflows/deploy-on-release-created.yaml +++ b/.github/workflows/deploy-on-release-created.yaml @@ -14,9 +14,9 @@ jobs: uses: actions/checkout@v4 - name: Setup Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - java-version: 17 + java-version: 21 distribution: 'zulu' cache: 'maven' server-id: matsim-releases diff --git a/.github/workflows/deploy-weekly.yaml b/.github/workflows/deploy-weekly.yaml index 0861a80ff91..f30f7371684 100644 --- a/.github/workflows/deploy-weekly.yaml +++ b/.github/workflows/deploy-weekly.yaml @@ -15,9 +15,9 @@ jobs: uses: actions/checkout@v4 - name: Setup Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - java-version: 17 + java-version: 21 distribution: 'zulu' cache: 'maven' server-id: 'matsim-releases' diff --git a/.github/workflows/full-integration.yaml b/.github/workflows/full-integration.yaml index 57789d54a8c..a75ea5767da 100644 --- a/.github/workflows/full-integration.yaml +++ b/.github/workflows/full-integration.yaml @@ -1,6 +1,7 @@ name: full-integration on: + workflow_dispatch: schedule: - cron: '30 0 * * *' # daily at 0:30 UTC @@ -13,7 +14,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest] + os: [ubuntu-latest, windows-latest, macos-latest] steps: - name: Prepare git @@ -24,9 +25,9 @@ jobs: uses: actions/checkout@v4 - name: Setup Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - java-version: 17 + java-version: 21 distribution: 'zulu' cache: 'maven' diff --git a/.github/workflows/verify-push.yaml b/.github/workflows/verify-push.yaml index f2a5b59d8ee..f7f5bce3718 100644 --- a/.github/workflows/verify-push.yaml +++ b/.github/workflows/verify-push.yaml @@ -66,6 +66,7 @@ jobs: - contribs/simwrapper - contribs/sbb-extensions - contribs/simulatedannealing + - contribs/small-scale-traffic-generation - benchmark steps: @@ -75,7 +76,7 @@ jobs: - name: Detect changes against master # we only want to build matsim (module) if changes are not limited to contribs id: detect-changes - uses: dorny/paths-filter@v2 + uses: dorny/paths-filter@v3 if: ${{matrix.module == 'matsim'}} with: filters: | @@ -84,9 +85,9 @@ jobs: - name: Setup Java if: ${{matrix.module != 'matsim' || steps.detect-changes.outputs.outside-contribs == 'true'}} - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - java-version: 17 + java-version: 21 distribution: 'zulu' cache: 'maven' diff --git a/.gitignore b/.gitignore index 96f823b9a9c..6adadab9bb5 100644 --- a/.gitignore +++ b/.gitignore @@ -12,5 +12,8 @@ matsimExamples matsim/docs/doxygen/html matsim/src/main/java/Doxyfile +# VS Code files +.vscode + # ignore output directories: output/ diff --git a/benchmark/pom.xml b/benchmark/pom.xml index 43ee7d820b2..22db5bc0464 100644 --- a/benchmark/pom.xml +++ b/benchmark/pom.xml @@ -4,7 +4,7 @@ org.matsim matsim-all - 16.0-SNAPSHOT + 2025.0-SNAPSHOT 4.0.0 jar @@ -33,16 +33,20 @@ org.matsim matsim - 16.0-SNAPSHOT + 2025.0-SNAPSHOT org.matsim matsim-examples - 16.0-SNAPSHOT + 2025.0-SNAPSHOT - junit - junit + org.junit.jupiter + junit-jupiter-engine + + + org.junit.jupiter + junit-jupiter diff --git a/contribs/README.md b/contribs/README.md index f29f739c4ef..4507e513d46 100644 --- a/contribs/README.md +++ b/contribs/README.md @@ -46,6 +46,7 @@ The MATSim core development team cannot make any guarantee that these extensions | [shared_mobility](shared_mobility/README.md) | Simulate human-driven shared mobility (i.e., micromobility) | [signals](signals/README.md) | Simulate traffic lights microscopically | [simwrapper](simwrapper/README.md) | Creates dashboards automatically with [SimWrapper](https://simwrapper.github.io/) +| [small-scale-traffic-generation](small-scale-traffic-generation/README.md) | Tool to generate small-scale commercial traffic | [socnetsim](socnetsim/README.md) | Social network simulation | [sumo](sumo/README.md) | Converter and integrations for [SUMO](https://sumo.dlr.de/]) | [taxi](taxi/README.md) | Taxi service functionality diff --git a/contribs/accessibility/pom.xml b/contribs/accessibility/pom.xml index 300f8fb1bd1..c4ead8bf378 100644 --- a/contribs/accessibility/pom.xml +++ b/contribs/accessibility/pom.xml @@ -2,7 +2,7 @@ org.matsim contrib - 16.0-SNAPSHOT + 2025.0-SNAPSHOT 4.0.0 org.matsim.contrib @@ -37,12 +37,12 @@ org.matsim.contrib matrixbasedptrouter - 16.0-SNAPSHOT + 2025.0-SNAPSHOT org.matsim.contrib roadpricing - 16.0-SNAPSHOT + 2025.0-SNAPSHOT net.sf.trove4j @@ -52,7 +52,7 @@ org.openstreetmap.osmosis osmosis-core - 0.48.3 + ${osmosis.version} @@ -65,12 +65,12 @@ org.openstreetmap.osmosis osmosis-xml - 0.48.3 + ${osmosis.version} org.matsim.contrib analysis - 16.0-SNAPSHOT + 2025.0-SNAPSHOT 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 db9adc47ccd..1ed755c12b6 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 @@ -20,6 +20,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.geotools.api.feature.simple.SimpleFeature; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; @@ -39,9 +40,8 @@ import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; import org.matsim.core.utils.geometry.CoordUtils; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.facilities.*; -import org.opengis.feature.simple.SimpleFeature; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -225,7 +225,7 @@ public static final ActivityFacilities createFacilityForEachLink(String facility public static final ActivityFacilities createFacilityFromBuildingShapefile(String shapeFileName, String identifierCaption, String numberOfHouseholdsCaption) { - ShapeFileReader shapeFileReader = new ShapeFileReader(); + GeoFileReader shapeFileReader = new GeoFileReader(); Collection features = shapeFileReader.readFileAndInitialize(shapeFileName); ActivityFacilities facilities = FacilitiesUtils.createActivityFacilities("DensitiyFacilities"); diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/FeatureSHP.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/FeatureSHP.java index 9ff4d3711ed..2e5cee46039 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/FeatureSHP.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/FeatureSHP.java @@ -24,11 +24,11 @@ import java.util.HashSet; import java.util.Set; -import org.geotools.data.DataStore; -import org.geotools.data.FileDataStoreFinder; +import org.geotools.api.data.DataStore; +import org.geotools.api.data.FileDataStoreFinder; +import org.geotools.api.data.SimpleFeatureSource; +import org.geotools.api.feature.simple.SimpleFeature; import org.geotools.data.simple.SimpleFeatureIterator; -import org.geotools.data.simple.SimpleFeatureSource; -import org.opengis.feature.simple.SimpleFeature; /** * Utility class for reading shape (.shp) files. diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/GridUtils.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/GridUtils.java index b8cfc04417f..6e5aa187364 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/GridUtils.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/GridUtils.java @@ -20,7 +20,6 @@ import org.matsim.facilities.ActivityFacility; import org.matsim.facilities.FacilitiesUtils; import org.matsim.utils.gis.shp2matsim.ShpGeometryUtils; -import org.opengis.feature.simple.SimpleFeature; public final class GridUtils { // used from outside, e.g. in vsp playgrounds diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/VoronoiExample.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/VoronoiExample.java index 24544971132..d1fe1df43d7 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/VoronoiExample.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/VoronoiExample.java @@ -22,23 +22,23 @@ import java.util.Collection; import java.util.List; +import org.geotools.api.feature.simple.SimpleFeature; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Polygon; import org.locationtech.jts.triangulate.VoronoiDiagramBuilder; import org.matsim.contrib.matrixbasedptrouter.utils.BoundingBox; -import org.matsim.core.utils.gis.ShapeFileWriter; -import org.opengis.feature.simple.SimpleFeature; +import org.matsim.core.utils.gis.GeoFileWriter; /** * @author dziemke */ class VoronoiExample { - + public static void main(String[] args) { GeometryFactory geometryFactory = new GeometryFactory(); - + Collection sites = new ArrayList<>(); sites.add(new Coordinate(70, 70)); sites.add(new Coordinate(50, 150)); @@ -48,16 +48,16 @@ public static void main(String[] args) { sites.add(new Coordinate(250, 150)); sites.add(new Coordinate(350, 50)); sites.add(new Coordinate(370, 170)); - + VoronoiDiagramBuilder voronoiDiagramBuilder = new VoronoiDiagramBuilder(); - voronoiDiagramBuilder.setSites(sites); - + voronoiDiagramBuilder.setSites(sites); + List polygons = voronoiDiagramBuilder.getSubdivision().getVoronoiCellPolygons(geometryFactory); - + BoundingBox boundingBox = BoundingBox.createBoundingBox(0, 0, 400, 200); Polygon boundingPolygon = VoronoiGeometryUtils.createBoundingPolygon(boundingBox); Collection cutGeometries = VoronoiGeometryUtils.cutPolygonsByBoundary(polygons, boundingPolygon); Collection features = VoronoiGeometryUtils.createFeaturesFromPolygons(cutGeometries); - ShapeFileWriter.writeGeometries(features, "/Users/dominik/voronoi_test.shp"); + GeoFileWriter.writeGeometries(features, "/Users/dominik/voronoi_test.shp"); } } diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/VoronoiGeometryUtils.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/VoronoiGeometryUtils.java index 76e7273fd87..bcf0edc7b73 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/VoronoiGeometryUtils.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/VoronoiGeometryUtils.java @@ -27,6 +27,8 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.geotools.api.feature.simple.SimpleFeature; +import org.geotools.api.feature.simple.SimpleFeatureType; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.locationtech.jts.geom.Coordinate; @@ -40,8 +42,6 @@ import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.facilities.ActivityFacilities; import org.matsim.facilities.ActivityFacility; -import org.opengis.feature.simple.SimpleFeature; -import org.opengis.feature.simple.SimpleFeatureType; /** * @author dziemke diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/gis/CRSUtils.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/gis/CRSUtils.java index a7171739b6a..92f3d94c5b8 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/gis/CRSUtils.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/gis/CRSUtils.java @@ -24,18 +24,18 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.geotools.api.metadata.Identifier; +import org.geotools.api.referencing.FactoryException; +import org.geotools.api.referencing.NoSuchAuthorityCodeException; +import org.geotools.api.referencing.crs.CRSAuthorityFactory; +import org.geotools.api.referencing.crs.CoordinateReferenceSystem; +import org.geotools.api.referencing.operation.MathTransform; +import org.geotools.api.referencing.operation.TransformException; import org.geotools.referencing.CRS; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Point; -import org.opengis.metadata.Identifier; -import org.opengis.referencing.FactoryException; -import org.opengis.referencing.NoSuchAuthorityCodeException; -import org.opengis.referencing.crs.CRSAuthorityFactory; -import org.opengis.referencing.crs.CoordinateReferenceSystem; -import org.opengis.referencing.operation.MathTransform; -import org.opengis.referencing.operation.TransformException; /** * Utility-class providing functionality related to coordinate reference @@ -94,7 +94,7 @@ public static int getSRID(CoordinateReferenceSystem crs) { /* * Randomly get one identifier. */ - Identifier identifier = (Identifier) (crs.getIdentifiers().iterator().next()); + Identifier identifier = crs.getIdentifiers().iterator().next(); if (identifier == null) { return 0; } else { @@ -118,7 +118,7 @@ public static MathTransform findTransform(Geometry source, Geometry target) { CoordinateReferenceSystem targetCRS = getCRS(target.getSRID()); try { - return CRS.findMathTransform(sourceCRS, targetCRS); + return CRS.findMathTransform(sourceCRS, targetCRS); } catch (FactoryException e) { e.printStackTrace(); return null; diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/gis/ZoneLayer.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/gis/ZoneLayer.java index c39948b714f..28bc2c41059 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/gis/ZoneLayer.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/gis/ZoneLayer.java @@ -24,13 +24,13 @@ import java.util.List; import java.util.Set; +import org.geotools.api.referencing.FactoryException; +import org.geotools.api.referencing.crs.CoordinateReferenceSystem; +import org.geotools.api.referencing.operation.MathTransform; import org.geotools.referencing.CRS; import org.locationtech.jts.geom.Point; import org.locationtech.jts.index.SpatialIndex; import org.locationtech.jts.index.quadtree.Quadtree; -import org.opengis.referencing.FactoryException; -import org.opengis.referencing.crs.CoordinateReferenceSystem; -import org.opengis.referencing.operation.MathTransform; /** * Representation of a spatial index containing zones backed by a quadtree. diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/osm/CombinedOsmSink.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/osm/CombinedOsmSink.java index f7e39f4b588..7c5c1bcf2d2 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/osm/CombinedOsmSink.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/osm/CombinedOsmSink.java @@ -22,6 +22,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.geotools.api.feature.simple.SimpleFeature; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; @@ -41,7 +42,6 @@ import org.matsim.facilities.ActivityOption; import org.matsim.facilities.FacilitiesUtils; import org.matsim.utils.objectattributes.ObjectAttributes; -import org.opengis.feature.simple.SimpleFeature; import org.openstreetmap.osmosis.core.container.v0_6.BoundContainer; import org.openstreetmap.osmosis.core.container.v0_6.EntityContainer; import org.openstreetmap.osmosis.core.container.v0_6.EntityProcessor; @@ -89,7 +89,7 @@ class CombinedOsmSink implements Sink { private Map typeCount = new HashMap<>(); - private List landUseAreas = new ArrayList (); + private List landUseAreas = new ArrayList<>(); private int featureErrorCounter = 0; private int buildingErrorCounter = 0; diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/osm/LandUseBuildingSink.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/osm/LandUseBuildingSink.java index 0a5989ad5e8..3b55793e0d6 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/osm/LandUseBuildingSink.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/osm/LandUseBuildingSink.java @@ -22,6 +22,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.geotools.api.feature.simple.SimpleFeature; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; @@ -40,7 +41,6 @@ import org.matsim.facilities.ActivityOption; import org.matsim.facilities.FacilitiesUtils; import org.matsim.utils.objectattributes.ObjectAttributes; -import org.opengis.feature.simple.SimpleFeature; import org.openstreetmap.osmosis.core.container.v0_6.BoundContainer; import org.openstreetmap.osmosis.core.container.v0_6.EntityContainer; import org.openstreetmap.osmosis.core.container.v0_6.EntityProcessor; @@ -69,11 +69,11 @@ class LandUseBuildingSink implements Sink { private Map relationMap; private ActivityFacilities facilities; private ObjectAttributes facilityAttributes; - private Map landUseTypeMap = new HashMap<>(); - private Map buildingTypeMap = new HashMap<>(); + private final Map landUseTypeMap; + private Map buildingTypeMap; private Map typeCount = new HashMap<>(); - private List features = new ArrayList (); + private List features = new ArrayList<>(); private double buildingTypeFromVicinityRange; private String[] tagsToIgnoreBuildings; diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GeoJsonPolygonFeatureWriter.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GeoJsonPolygonFeatureWriter.java index c022be98067..f0e3dc08db3 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GeoJsonPolygonFeatureWriter.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GeoJsonPolygonFeatureWriter.java @@ -1,6 +1,6 @@ package org.matsim.contrib.accessibility.utils; -import org.json.simple.JSONValue; +import com.google.gson.Gson; import org.matsim.api.core.v01.Coord; import java.util.*; @@ -34,7 +34,7 @@ public String asGeoJson() { featureCollectionMap.put("features", featuresList); featureCollectionMap.put("crs", parseCRS()); featureCollectionMap.put("bbox", boundingBox.getBoundingBox()); - return JSONValue.toJSONString(featureCollectionMap); + return new Gson().toJson(featureCollectionMap); } private List> parseFeatureList() { diff --git a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GeoserverUpdater.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GeoserverUpdater.java index 2f25f641a4c..d489d7ca811 100644 --- a/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GeoserverUpdater.java +++ b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GeoserverUpdater.java @@ -28,9 +28,11 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.geotools.data.DataStore; -import org.geotools.data.DataStoreFinder; -import org.geotools.data.simple.SimpleFeatureStore; +import org.geotools.api.data.DataStore; +import org.geotools.api.data.DataStoreFinder; +import org.geotools.api.data.SimpleFeatureStore; +import org.geotools.api.feature.simple.SimpleFeature; +import org.geotools.api.feature.simple.SimpleFeatureType; import org.geotools.feature.DefaultFeatureCollection; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; @@ -47,10 +49,8 @@ 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.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.matsim.facilities.ActivityFacility; -import org.opengis.feature.simple.SimpleFeature; -import org.opengis.feature.simple.SimpleFeatureType; public class GeoserverUpdater implements FacilityDataExchangeInterface { @@ -74,7 +74,7 @@ public GeoserverUpdater (String crs, String name, Map, Geom this.pushing2Geoserver = pushing2Geoserver; this.createQGisOutput = createQGisOutput; } - + private Map, Map> accessibilitiesMap = new HashMap<>() ; @Override @@ -95,16 +95,16 @@ public void finish() { SimpleFeatureTypeBuilder featureTypeBuilder = createFeatureTypeBuilder(); SimpleFeatureType featureType = featureTypeBuilder.buildFeatureType(); DefaultFeatureCollection featureCollection = createFeatureCollection(geometryFactory, featureType); - + if (outputDirectory != null) { File file = new File(outputDirectory); file.mkdirs(); } - + if (createQGisOutput) { - ShapeFileWriter.writeGeometries(featureCollection, outputDirectory + "/result.shp"); + GeoFileWriter.writeGeometries(featureCollection, outputDirectory + "/result.shp"); } - + if (pushing2Geoserver) { updateOnGeoserver(featureType, featureCollection); } @@ -130,7 +130,7 @@ private DefaultFeatureCollection createFeatureCollection(GeometryFactory geometr LOG.info("Start creating features from accessibility data."); DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal", featureType); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); - + CoordinateTransformation transformation = TransformationFactory.getCoordinateTransformation(this.crs, TransformationFactory.WGS84); for (Entry, Map> entry : accessibilitiesMap.entrySet()) { @@ -145,10 +145,10 @@ private DefaultFeatureCollection createFeatureCollection(GeometryFactory geometr i++; } featureBuilder.add(geometryFactory.createPolygon(transformedCoordinates)); - + featureBuilder.add(Integer.parseInt(entry.getKey().getFirst().getId().toString())); featureBuilder.add(entry.getKey().getSecond()); - + for (Modes4Accessibility modeEnum : Modes4Accessibility.values()) { String mode = modeEnum.toString(); Double accessibility = entry.getValue().get(mode); @@ -188,14 +188,14 @@ private void updateOnGeoserver(SimpleFeatureType featureType, DefaultFeatureColl // There have been errors with the data store if the dependency "gt-jdbc-postgis", version 13.0 was missing! DataStore dataStore = DataStoreFinder.getDataStore(params); LOG.info("dataStore = " + dataStore); - + // Remove schema in case it already exists try { dataStore.removeSchema(name); } catch (IllegalArgumentException e) { LOG.warn("Could not remove schema. Probably, it has not existed yet."); } - + dataStore.createSchema(featureType); SimpleFeatureStore featureStore = (SimpleFeatureStore) dataStore.getFeatureSource(name); featureStore.addFeatures(featureCollection); diff --git a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/LeastCostPathTreeTest.java b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/LeastCostPathTreeTest.java index fcd995bd7b7..23d32279ec6 100644 --- a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/LeastCostPathTreeTest.java +++ b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/LeastCostPathTreeTest.java @@ -5,8 +5,8 @@ import java.util.List; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Node; @@ -24,9 +24,9 @@ public class LeastCostPathTreeTest { Scenario scenario; - + @Test - public void testRouteChoiceTestSpanningTree(){ + void testRouteChoiceTestSpanningTree(){ this.scenario = new ScenarioBuilder(ConfigUtils.createConfig()).setNetwork(CreateTestNetwork.createTriangularNetwork()).build() ; compareRouteChoices(); } @@ -55,11 +55,11 @@ private void compareRouteChoices(){ printResults(arrivalTime, travelTime); // travel time = cost = (50s+50s) = 100s // check route (visited nodes should be 1,2,4) List> spTimeVisitedNodes = getVisitedNodes(lcptTime, destination, "Travel Time"); - Assert.assertTrue( containsNode(spTimeVisitedNodes, Id.create("2", Node.class))); + Assertions.assertTrue( containsNode(spTimeVisitedNodes, Id.create("2", Node.class))); // check travel duration - Assert.assertTrue( travelTime == 100 ); + Assertions.assertTrue( travelTime == 100 ); // check travel time - Assert.assertTrue( arrivalTime - departureTime == 100 ); + Assertions.assertTrue( arrivalTime - departureTime == 100 ); lcptDistance.calculate(this.scenario.getNetwork(), origin, departureTime); double arrivalTimeTD = lcptDistance.getTree().get( destination.getId() ).getTime(); @@ -67,11 +67,11 @@ private void compareRouteChoices(){ printResults(arrivalTimeTD, travelDistance); // travel time = 1000s, cost = (50m+50m) = 100m // check route ( visited nodes should be 1,3,4) List> spDistenceVisitedNodes = getVisitedNodes(lcptDistance, destination, "Travel Distance"); - Assert.assertTrue( containsNode(spDistenceVisitedNodes, Id.create("3", Node.class))); + Assertions.assertTrue( containsNode(spDistenceVisitedNodes, Id.create("3", Node.class))); // check travel distance - Assert.assertTrue( travelDistance == 100 ); + Assertions.assertTrue( travelDistance == 100 ); // check travel time - Assert.assertTrue( arrivalTimeTD - departureTime == 1000 ); + Assertions.assertTrue( arrivalTimeTD - departureTime == 1000 ); } private void printResults(double tt, double tc){ diff --git a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/grid/SpatialGridTest.java b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/grid/SpatialGridTest.java index b9f82d4cfa1..74bae0a5363 100644 --- a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/grid/SpatialGridTest.java +++ b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/grid/SpatialGridTest.java @@ -1,8 +1,8 @@ package org.matsim.contrib.accessibility.grid; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.network.Network; import org.matsim.contrib.accessibility.SpatialGrid; import org.matsim.contrib.matrixbasedptrouter.utils.BoundingBox; @@ -11,13 +11,14 @@ public class SpatialGridTest { - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension + private MatsimTestUtils utils = new MatsimTestUtils(); private double cellSize = 10.; - @Test public void testSpatialGrid() { + @Test + void testSpatialGrid() { // get network Network network = CreateTestNetwork.createTestNetwork(); @@ -31,11 +32,11 @@ public class SpatialGridTest { // get number of rows int rows = testGrid.getNumRows(); double numOfExpectedRows = ((nbb.getYMax() - nbb.getYMin()) / cellSize) + 1; - Assert.assertTrue(rows == numOfExpectedRows); + Assertions.assertTrue(rows == numOfExpectedRows); // get number of columns int cols = testGrid.getNumCols(0); double numOfExpectedCols = ((nbb.getXMax() - nbb.getXMin()) / cellSize) + 1; - Assert.assertTrue(cols == numOfExpectedCols); + Assertions.assertTrue(cols == numOfExpectedCols); } } diff --git a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/CompareLogsumFormulas2Test.java b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/CompareLogsumFormulas2Test.java index b561798a16d..f7e6672c053 100644 --- a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/CompareLogsumFormulas2Test.java +++ b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/CompareLogsumFormulas2Test.java @@ -22,9 +22,9 @@ */ package org.matsim.contrib.accessibility.logsumComputations; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.testcases.MatsimTestUtils; /** @@ -33,12 +33,12 @@ */ public class CompareLogsumFormulas2Test { - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension + private MatsimTestUtils utils = new MatsimTestUtils(); - - @Test public void testLogsumFormulas(){ + @Test + void testLogsumFormulas(){ double walkTravelTime2Network = 2.; // 2min double travelTimeOnNetwork = 6.; // 6min @@ -66,7 +66,7 @@ public class CompareLogsumFormulas2Test { double Sum2 =PreFactor * AggregationSum; System.out.println(Sum2); - Assert.assertTrue( Sum1 == Sum2 ); + Assertions.assertTrue( Sum1 == Sum2 ); } } diff --git a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/CompareLogsumFormulasTest.java b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/CompareLogsumFormulasTest.java index 8c85aabbe9f..19501ebb49f 100644 --- a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/CompareLogsumFormulasTest.java +++ b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/CompareLogsumFormulasTest.java @@ -22,9 +22,9 @@ */ package org.matsim.contrib.accessibility.logsumComputations; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.testcases.MatsimTestUtils; /** @@ -33,8 +33,8 @@ */ public class CompareLogsumFormulasTest { - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension + private MatsimTestUtils utils = new MatsimTestUtils(); /** * underlying network @@ -47,7 +47,8 @@ public class CompareLogsumFormulasTest { * cjk3 */ - @Test public void testLogsumFormulas(){ + @Test + void testLogsumFormulas(){ double betaWalkTT = -2.; double betaWalkTD = -1.; @@ -72,7 +73,7 @@ public class CompareLogsumFormulasTest { double Ai = computeLogsum(betaWalkTT, betaWalkTD, cik1TT, cik2TT, cik3TT, cik1TD, cik2TD, cik3TD); double Ai2 =computeTransformedLogsum(betaWalkTT, betaWalkTD, cijTT, cjk1TT, cjk2TT, cjk3TT, cijTD, cjk1TD, cjk2TD, cjk3TD); - Assert.assertTrue( Ai == Ai2 ); + Assertions.assertTrue( Ai == Ai2 ); } /** diff --git a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/ComputeLogsumFormulas3Test.java b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/ComputeLogsumFormulas3Test.java index 81eb7bc3254..1b35497b3c7 100644 --- a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/ComputeLogsumFormulas3Test.java +++ b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/logsumComputations/ComputeLogsumFormulas3Test.java @@ -22,9 +22,9 @@ */ package org.matsim.contrib.accessibility.logsumComputations; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.testcases.MatsimTestUtils; /** @@ -33,8 +33,8 @@ */ public class ComputeLogsumFormulas3Test { - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension + private MatsimTestUtils utils = new MatsimTestUtils(); /** * underlying network @@ -48,7 +48,8 @@ public class ComputeLogsumFormulas3Test { */ @SuppressWarnings("static-method") - @Test public void testLogsumFormulas(){ + @Test + void testLogsumFormulas(){ double betaWalkTT = -10. / 3600.0; // [util/sec] double betaWalkTD = -10.; // [util/meter] @@ -100,7 +101,7 @@ public class ComputeLogsumFormulas3Test { // double expNewVhj= Math.exp( VhjNew ); // double expNewVhk= expNewVhj * sumExpVjk; - Assert.assertTrue(VhjOld == VhjNew); // old accessibility computation == new accessibility computation + Assertions.assertTrue(VhjOld == VhjNew); // old accessibility computation == new accessibility computation /////// // NEW @@ -112,7 +113,7 @@ public class ComputeLogsumFormulas3Test { double dummyExp1 = Math.exp( dummyVijCar + dummyVhiWalk ); double dummyExp2 = Math.exp( dummyVijCar ) * Math.exp( dummyVhiWalk ); - Assert.assertEquals(dummyExp1,dummyExp2,1.e-10); // exp(VijCar + VijWalk) == exp(VijCar) * exp(VijWalk) + Assertions.assertEquals(dummyExp1,dummyExp2,1.e-10); // exp(VijCar + VijWalk) == exp(VijCar) * exp(VijWalk) } } 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 b843e1ae3b5..25b3a4598eb 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 @@ -27,10 +27,10 @@ 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.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.locationtech.jts.geom.Envelope; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; @@ -74,11 +74,11 @@ public class AccessibilityIntegrationTest { private static final Logger LOG = LogManager.getLogger(AccessibilityIntegrationTest.class); - @Rule public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension private MatsimTestUtils utils = new MatsimTestUtils(); - @Ignore + @Disabled @Test - public void testRunAccessibilityExample() { + void testRunAccessibilityExample() { Config config = ConfigUtils.loadConfig("./examples/RunAccessibilityExample/config.xml"); AccessibilityConfigGroup accConfig = ConfigUtils.addOrGetModule(config, AccessibilityConfigGroup.class); @@ -101,15 +101,15 @@ public void startRow(String[] row) { if (x == 50) { if (y == 50) { - Assert.assertEquals("Wrong work accessibility value at x=" + x + ", y=" + y + ":", 2.1486094237531126, value, utils.EPSILON); + Assertions.assertEquals(2.1486094237531126, value, utils.EPSILON, "Wrong work accessibility value at x=" + x + ", y=" + y + ":"); } else if (y == 150){ - Assert.assertEquals("Wrong work accessibility value at x=" + x + ", y=" + y + ":", 2.1766435716006005, value, utils.EPSILON); + Assertions.assertEquals(2.1766435716006005, value, utils.EPSILON, "Wrong work accessibility value at x=" + x + ", y=" + y + ":"); } } else if (x == 150) { if (y == 50) { - Assert.assertEquals("Wrong work accessibility value at x=" + x + ", y=" + y + ":", 2.1486094237531126, value, utils.EPSILON); + Assertions.assertEquals(2.1486094237531126, value, utils.EPSILON, "Wrong work accessibility value at x=" + x + ", y=" + y + ":"); } else if (y == 150){ - Assert.assertEquals("Wrong work accessibility value at x=" + x + ", y=" + y + ":", 2.2055702759681273, value, utils.EPSILON); + Assertions.assertEquals(2.2055702759681273, value, utils.EPSILON, "Wrong work accessibility value at x=" + x + ", y=" + y + ":"); } } } @@ -119,7 +119,7 @@ public void startRow(String[] row) { @Test - public void testWithBoundingBoxConfigFile() { + void testWithBoundingBoxConfigFile() { Config config = ConfigUtils.loadConfig(utils.getInputDirectory() + "config.xml"); AccessibilityConfigGroup acg = ConfigUtils.addOrGetModule(config, AccessibilityConfigGroup.class) ; @@ -159,7 +159,7 @@ public void install() { @Test - public void testWithBoundingBox() { + void testWithBoundingBox() { final Config config = createTestConfig(); double min = 0.; // Values for bounding box usually come from a config file @@ -197,7 +197,7 @@ public void install() { @Test - public void testWithBoundingBoxUsingOpportunityWeights() { + void testWithBoundingBoxUsingOpportunityWeights() { final Config config = createTestConfig(); double min = 0.; // Values for bounding box usually come from a config file @@ -237,7 +237,7 @@ public void install() { @Test - public void testWithExtentDeterminedByNetwork() { + void testWithExtentDeterminedByNetwork() { final Config config = createTestConfig() ; config.routing().setRoutingRandomness(0.); @@ -264,14 +264,14 @@ public void install() { @Test - public void testWithExtentDeterminedShapeFile() { + void testWithExtentDeterminedShapeFile() { Config config = createTestConfig() ; File f = new File(this.utils.getInputDirectory() + "shapefile.shp"); // shape file completely covers the road network if(!f.exists()){ LOG.error("Shape file not found! testWithExtentDeterminedShapeFile could not be tested..."); - Assert.assertTrue(f.exists()); + Assertions.assertTrue(f.exists()); } final AccessibilityConfigGroup acg = ConfigUtils.addOrGetModule(config, AccessibilityConfigGroup.class); @@ -304,14 +304,14 @@ public void install() { @Test - public void testWithPredefinedMeasuringPoints() { + void testWithPredefinedMeasuringPoints() { Config config = createTestConfig() ; File f = new File(this.utils.getInputDirectory() + "measuringPoints.xml"); if(!f.exists()){ LOG.error("Facilities file with measuring points not found! testWithMeasuringPointsInFacilitiesFile could not be performed..."); - Assert.assertTrue(f.exists()); + Assertions.assertTrue(f.exists()); } Scenario measuringPointsSc = ScenarioUtils.createScenario(ConfigUtils.createConfig()); @@ -350,16 +350,16 @@ public void install() { } - @Ignore + @Disabled @Test - public void testWithFile(){ + void testWithFile(){ /*TODO Complete - JWJ, Dec'16 */ Config config = createTestConfig(); File f = new File(this.utils.getInputDirectory() + "pointFile.csv"); if(!f.exists()){ LOG.error("Point file not found! testWithFile could not be tested..."); - Assert.assertTrue(f.exists()); + Assertions.assertTrue(f.exists()); } final AccessibilityConfigGroup acg = ConfigUtils.addOrGetModule(config, AccessibilityConfigGroup.class); @@ -598,12 +598,12 @@ public void finish() { for (String mode : accessibilitiesMap.get(tuple).keySet()) { double value = accessibilitiesMap.get(tuple).get(mode); switch (mode) { // commented values are before (a) Marcel's change of the QuadTree in Oct'18, (b) change in TravelTimeCalculator in Apr'21 - case "freespeed": Assert.assertEquals(2.207441799716032, value, MatsimTestUtils.EPSILON); break; // (a) 2.1486094237531126 - case TransportMode.car: Assert.assertEquals(2.2058369602991204, value, MatsimTestUtils.EPSILON); break; // (a) 2.1482840466191093 (b) 2.205836861444427 - case TransportMode.bike: Assert.assertEquals(2.2645288908389554, value, MatsimTestUtils.EPSILON); break; // (a) 2.2257398663221 - case TransportMode.walk: Assert.assertEquals(1.8697283849051263, value, MatsimTestUtils.EPSILON); break; // (a) 1.70054725728361 - case TransportMode.pt: Assert.assertEquals(2.1581641260040683, value, MatsimTestUtils.EPSILON); break; - case "matrixBasedPt": Assert.assertEquals(1.6542905235735796, value, MatsimTestUtils.EPSILON); break; // (a) 0.461863556339195 + case "freespeed": Assertions.assertEquals(2.207441799716032, value, MatsimTestUtils.EPSILON); break; // (a) 2.1486094237531126 + case TransportMode.car: Assertions.assertEquals(2.2058369602991204, value, MatsimTestUtils.EPSILON); break; // (a) 2.1482840466191093 (b) 2.205836861444427 + case TransportMode.bike: Assertions.assertEquals(2.2645288908389554, value, MatsimTestUtils.EPSILON); break; // (a) 2.2257398663221 + case TransportMode.walk: Assertions.assertEquals(1.8697283849051263, value, MatsimTestUtils.EPSILON); break; // (a) 1.70054725728361 + case TransportMode.pt: Assertions.assertEquals(2.1581641260040683, value, MatsimTestUtils.EPSILON); break; + case "matrixBasedPt": Assertions.assertEquals(1.6542905235735796, value, MatsimTestUtils.EPSILON); break; // (a) 0.461863556339195 } } } @@ -611,12 +611,12 @@ else if (tuple.getFirst().getCoord().getY() == 150.) { for (String mode : accessibilitiesMap.get(tuple).keySet()) { double value = accessibilitiesMap.get(tuple).get(mode); switch (mode) { - case "freespeed": Assert.assertEquals(2.207441799716032, value, MatsimTestUtils.EPSILON); break; // (a) 2.1766435716006005 - case TransportMode.car: Assert.assertEquals(2.207441960299121, value, MatsimTestUtils.EPSILON); break; // (a) 2.176238564675181 (b) 2.207441799716032 - case TransportMode.bike: Assert.assertEquals(2.2645288908389554, value, MatsimTestUtils.EPSILON); break; // (a) 2.2445468698643367 - case TransportMode.walk: Assert.assertEquals(1.8697283849051263, value, MatsimTestUtils.EPSILON); break; // (a) 1.7719146868026079 - case TransportMode.pt: Assert.assertEquals(2.1581641260040683, value, MatsimTestUtils.EPSILON); break; // (a) 2.057596373646452 - case "matrixBasedPt": Assert.assertEquals(1.6542905235735796, value, MatsimTestUtils.EPSILON); break; // (a) 0.461863556339195 + case "freespeed": Assertions.assertEquals(2.207441799716032, value, MatsimTestUtils.EPSILON); break; // (a) 2.1766435716006005 + case TransportMode.car: Assertions.assertEquals(2.207441960299121, value, MatsimTestUtils.EPSILON); break; // (a) 2.176238564675181 (b) 2.207441799716032 + case TransportMode.bike: Assertions.assertEquals(2.2645288908389554, value, MatsimTestUtils.EPSILON); break; // (a) 2.2445468698643367 + case TransportMode.walk: Assertions.assertEquals(1.8697283849051263, value, MatsimTestUtils.EPSILON); break; // (a) 1.7719146868026079 + case TransportMode.pt: Assertions.assertEquals(2.1581641260040683, value, MatsimTestUtils.EPSILON); break; // (a) 2.057596373646452 + case "matrixBasedPt": Assertions.assertEquals(1.6542905235735796, value, MatsimTestUtils.EPSILON); break; // (a) 0.461863556339195 } } } @@ -626,12 +626,12 @@ else if (tuple.getFirst().getCoord().getY() == 150.) { for (String mode : accessibilitiesMap.get(tuple).keySet()) { double value = accessibilitiesMap.get(tuple).get(mode); switch (mode) { - case "freespeed": Assert.assertEquals(2.235503385314382, value, MatsimTestUtils.EPSILON); break; // (a) 2.1486094237531126 - case TransportMode.car: Assert.assertEquals(2.23550352057971, value, MatsimTestUtils.EPSILON); break; // (a) 2.1482840466191093 (b) 2.235503385314382 - case TransportMode.bike: Assert.assertEquals(2.2833435568892395, value, MatsimTestUtils.EPSILON); break; // (a) 2.2257398663221 - case TransportMode.walk: Assert.assertEquals(1.9418539664691532, value, MatsimTestUtils.EPSILON); break; // (a) 1.70054725728361 - case TransportMode.pt: Assert.assertEquals(2.0032465393091434, value, MatsimTestUtils.EPSILON); break; - case "matrixBasedPt": Assert.assertEquals(1.6542905235735796, value, MatsimTestUtils.EPSILON); break; // (a) 0.461863556339195 + case "freespeed": Assertions.assertEquals(2.235503385314382, value, MatsimTestUtils.EPSILON); break; // (a) 2.1486094237531126 + case TransportMode.car: Assertions.assertEquals(2.23550352057971, value, MatsimTestUtils.EPSILON); break; // (a) 2.1482840466191093 (b) 2.235503385314382 + case TransportMode.bike: Assertions.assertEquals(2.2833435568892395, value, MatsimTestUtils.EPSILON); break; // (a) 2.2257398663221 + case TransportMode.walk: Assertions.assertEquals(1.9418539664691532, value, MatsimTestUtils.EPSILON); break; // (a) 1.70054725728361 + case TransportMode.pt: Assertions.assertEquals(2.0032465393091434, value, MatsimTestUtils.EPSILON); break; + case "matrixBasedPt": Assertions.assertEquals(1.6542905235735796, value, MatsimTestUtils.EPSILON); break; // (a) 0.461863556339195 } } } @@ -639,12 +639,12 @@ else if (tuple.getFirst().getCoord().getY() == 150.) { for (String mode : accessibilitiesMap.get(tuple).keySet()) { double value = accessibilitiesMap.get(tuple).get(mode); switch (mode) { - case "freespeed": Assert.assertEquals(2.235503385314382, value, MatsimTestUtils.EPSILON); break; // (a) 2.2055702759681273 - case TransportMode.car: Assert.assertEquals(2.23550352057971, value, MatsimTestUtils.EPSILON); break; // (a) 2.2052225231109226 (b) 2.235503385314382 - case TransportMode.bike: Assert.assertEquals(2.2833435568892395, value, MatsimTestUtils.EPSILON); break; // (a) 2.2637376515333636 - case TransportMode.walk: Assert.assertEquals(1.9418539664691532, value, MatsimTestUtils.EPSILON); break; // (a) 1.851165291193725 - case TransportMode.pt: Assert.assertEquals(2.0032465393091434, value, MatsimTestUtils.EPSILON); break; // (a) 1.9202710265495115 - case "matrixBasedPt": Assert.assertEquals(1.5073890466447624, value, MatsimTestUtils.EPSILON); break; // (a) 0.624928280738513 + case "freespeed": Assertions.assertEquals(2.235503385314382, value, MatsimTestUtils.EPSILON); break; // (a) 2.2055702759681273 + case TransportMode.car: Assertions.assertEquals(2.23550352057971, value, MatsimTestUtils.EPSILON); break; // (a) 2.2052225231109226 (b) 2.235503385314382 + case TransportMode.bike: Assertions.assertEquals(2.2833435568892395, value, MatsimTestUtils.EPSILON); break; // (a) 2.2637376515333636 + case TransportMode.walk: Assertions.assertEquals(1.9418539664691532, value, MatsimTestUtils.EPSILON); break; // (a) 1.851165291193725 + case TransportMode.pt: Assertions.assertEquals(2.0032465393091434, value, MatsimTestUtils.EPSILON); break; // (a) 1.9202710265495115 + case "matrixBasedPt": Assertions.assertEquals(1.5073890466447624, value, MatsimTestUtils.EPSILON); break; // (a) 0.624928280738513 } } } @@ -656,12 +656,12 @@ else if (tuple.getFirst().getCoord().getY() == 150.) { for (String mode : accessibilitiesMap.get(tuple).keySet()) { double value = accessibilitiesMap.get(tuple).get(mode); switch (mode) { - case "freespeed": Assert.assertEquals(3.5937361608359226, value, MatsimTestUtils.EPSILON); break; // (a) 3.534903784873003 - case TransportMode.car: Assert.assertEquals(3.592131321419011, value, MatsimTestUtils.EPSILON); break; // (a) 3.534578407739 (b) 3.592131222564318 - case TransportMode.bike: Assert.assertEquals(3.650823251958846, value, MatsimTestUtils.EPSILON); break; // (a) 3.6120342274419914 - case TransportMode.walk: Assert.assertEquals(3.256022746025017, value, MatsimTestUtils.EPSILON); break; // (a) 3.086841618403501 - case TransportMode.pt: Assert.assertEquals(3.5444584871239586, value, MatsimTestUtils.EPSILON); break; - case "matrixBasedPt": Assert.assertEquals(3.0405848846934704, value, MatsimTestUtils.EPSILON); break; // (a) 1.8481579174590859 + case "freespeed": Assertions.assertEquals(3.5937361608359226, value, MatsimTestUtils.EPSILON); break; // (a) 3.534903784873003 + case TransportMode.car: Assertions.assertEquals(3.592131321419011, value, MatsimTestUtils.EPSILON); break; // (a) 3.534578407739 (b) 3.592131222564318 + case TransportMode.bike: Assertions.assertEquals(3.650823251958846, value, MatsimTestUtils.EPSILON); break; // (a) 3.6120342274419914 + case TransportMode.walk: Assertions.assertEquals(3.256022746025017, value, MatsimTestUtils.EPSILON); break; // (a) 3.086841618403501 + case TransportMode.pt: Assertions.assertEquals(3.5444584871239586, value, MatsimTestUtils.EPSILON); break; + case "matrixBasedPt": Assertions.assertEquals(3.0405848846934704, value, MatsimTestUtils.EPSILON); break; // (a) 1.8481579174590859 } } } @@ -669,12 +669,12 @@ else if (tuple.getFirst().getCoord().getY() == 150.) { for (String mode : accessibilitiesMap.get(tuple).keySet()) { double value = accessibilitiesMap.get(tuple).get(mode); switch (mode) { - case "freespeed": Assert.assertEquals(3.5937361608359226, value, MatsimTestUtils.EPSILON); break; // (a) 3.562937932720491 - case TransportMode.car: Assert.assertEquals(3.5937363214190112, value, MatsimTestUtils.EPSILON); break; // (a) 3.5625329257950717 (b) 3.5937361608359226 - case TransportMode.bike: Assert.assertEquals(3.650823251958846, value, MatsimTestUtils.EPSILON); break; // (a) 3.6308412309842275 - case TransportMode.walk: Assert.assertEquals(3.256022746025017, value, MatsimTestUtils.EPSILON); break; // (a) 3.1582090479224982 - case TransportMode.pt: Assert.assertEquals(3.5444584871239586, value, MatsimTestUtils.EPSILON); break; // (a) 3.443890734766343 - case "matrixBasedPt": Assert.assertEquals(3.0405848846934704, value, MatsimTestUtils.EPSILON); break; // (a) 1.8481579174590859 + case "freespeed": Assertions.assertEquals(3.5937361608359226, value, MatsimTestUtils.EPSILON); break; // (a) 3.562937932720491 + case TransportMode.car: Assertions.assertEquals(3.5937363214190112, value, MatsimTestUtils.EPSILON); break; // (a) 3.5625329257950717 (b) 3.5937361608359226 + case TransportMode.bike: Assertions.assertEquals(3.650823251958846, value, MatsimTestUtils.EPSILON); break; // (a) 3.6308412309842275 + case TransportMode.walk: Assertions.assertEquals(3.256022746025017, value, MatsimTestUtils.EPSILON); break; // (a) 3.1582090479224982 + case TransportMode.pt: Assertions.assertEquals(3.5444584871239586, value, MatsimTestUtils.EPSILON); break; // (a) 3.443890734766343 + case "matrixBasedPt": Assertions.assertEquals(3.0405848846934704, value, MatsimTestUtils.EPSILON); break; // (a) 1.8481579174590859 } } } @@ -684,12 +684,12 @@ else if (tuple.getFirst().getCoord().getY() == 150.) { for (String mode : accessibilitiesMap.get(tuple).keySet()) { double value = accessibilitiesMap.get(tuple).get(mode); switch (mode) { - case "freespeed": Assert.assertEquals(3.621797746434273, value, MatsimTestUtils.EPSILON); break; // (a) 3.534903784873003 - case TransportMode.car: Assert.assertEquals(3.621797881699601, value, MatsimTestUtils.EPSILON); break; // (a) 3.534578407739 (b) 3.621797746434273 - case TransportMode.bike: Assert.assertEquals(3.66963791800913, value, MatsimTestUtils.EPSILON); break; // (a) 3.6120342274419914 - case TransportMode.walk: Assert.assertEquals(3.328148327589044, value, MatsimTestUtils.EPSILON); break; // (a) 3.086841618403501 - case TransportMode.pt: Assert.assertEquals(3.389540900429034, value, MatsimTestUtils.EPSILON); break; - case "matrixBasedPt": Assert.assertEquals(3.0405848846934704, value, MatsimTestUtils.EPSILON); break; // (a) 1.8481579174590859 + case "freespeed": Assertions.assertEquals(3.621797746434273, value, MatsimTestUtils.EPSILON); break; // (a) 3.534903784873003 + case TransportMode.car: Assertions.assertEquals(3.621797881699601, value, MatsimTestUtils.EPSILON); break; // (a) 3.534578407739 (b) 3.621797746434273 + case TransportMode.bike: Assertions.assertEquals(3.66963791800913, value, MatsimTestUtils.EPSILON); break; // (a) 3.6120342274419914 + case TransportMode.walk: Assertions.assertEquals(3.328148327589044, value, MatsimTestUtils.EPSILON); break; // (a) 3.086841618403501 + case TransportMode.pt: Assertions.assertEquals(3.389540900429034, value, MatsimTestUtils.EPSILON); break; + case "matrixBasedPt": Assertions.assertEquals(3.0405848846934704, value, MatsimTestUtils.EPSILON); break; // (a) 1.8481579174590859 } } } @@ -697,12 +697,12 @@ else if (tuple.getFirst().getCoord().getY() == 150.) { for (String mode : accessibilitiesMap.get(tuple).keySet()) { double value = accessibilitiesMap.get(tuple).get(mode); switch (mode) { - case "freespeed": Assert.assertEquals(3.621797746434273, value, MatsimTestUtils.EPSILON); break; // (a) 3.5918646370880176 - case TransportMode.car: Assert.assertEquals(3.621797881699601, value, MatsimTestUtils.EPSILON); break; // (a) 3.591516884230813 (b) 3.621797746434273 - case TransportMode.bike: Assert.assertEquals(3.66963791800913, value, MatsimTestUtils.EPSILON); break; // (a) 3.6500320126532544 - case TransportMode.walk: Assert.assertEquals(3.328148327589044, value, MatsimTestUtils.EPSILON); break; // (a) 3.2374596523136154 - case TransportMode.pt: Assert.assertEquals(3.389540900429034, value, MatsimTestUtils.EPSILON); break; // (a) 3.3065653876694023 - case "matrixBasedPt": Assert.assertEquals(2.893683407764653, value, MatsimTestUtils.EPSILON); break; // (a) 2.0112226418584043 + case "freespeed": Assertions.assertEquals(3.621797746434273, value, MatsimTestUtils.EPSILON); break; // (a) 3.5918646370880176 + case TransportMode.car: Assertions.assertEquals(3.621797881699601, value, MatsimTestUtils.EPSILON); break; // (a) 3.591516884230813 (b) 3.621797746434273 + case TransportMode.bike: Assertions.assertEquals(3.66963791800913, value, MatsimTestUtils.EPSILON); break; // (a) 3.6500320126532544 + case TransportMode.walk: Assertions.assertEquals(3.328148327589044, value, MatsimTestUtils.EPSILON); break; // (a) 3.2374596523136154 + case TransportMode.pt: Assertions.assertEquals(3.389540900429034, value, MatsimTestUtils.EPSILON); break; // (a) 3.3065653876694023 + case "matrixBasedPt": Assertions.assertEquals(2.893683407764653, value, MatsimTestUtils.EPSILON); break; // (a) 2.0112226418584043 } } } diff --git a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/NetworkUtilTest.java b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/NetworkUtilTest.java index 405bc54c3e9..cf03d50fa9d 100644 --- a/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/NetworkUtilTest.java +++ b/contribs/accessibility/src/test/java/org/matsim/contrib/accessibility/run/NetworkUtilTest.java @@ -21,9 +21,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; @@ -39,14 +39,14 @@ * @author dziemke */ public class NetworkUtilTest { - + private static final Logger log = LogManager.getLogger(NetworkUtilTest.class); - - @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - + + @RegisterExtension private MatsimTestUtils utils = new MatsimTestUtils(); + @Test - public void testNetworkUtil() { + void testNetworkUtil() { /* create a sample network: * * (e) (f) @@ -62,10 +62,10 @@ public void testNetworkUtil() { * * The network contains an exactly horizontal, an exactly vertical, an exactly diagonal * and another link with no special slope to also test possible special cases. - * + * * why is that a "special case"? in a normal network all sort of slopes are *normally* present. dz, feb'16 */ - + Network network = NetworkUtils.createNetwork(); 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) 0, (double) 1000)); @@ -76,7 +76,7 @@ public void testNetworkUtil() { Link link2 = NetworkUtils.createAndAddLink(network, Id.create("2", Link.class), node2, node3, 1500, 1, 3600, 1); Link link3 = NetworkUtils.createAndAddLink(network, Id.create("3", Link.class), node3, node4, 1000, 1, 3600, 1); Link link4 = NetworkUtils.createAndAddLink(network, Id.create("4", Link.class), node4, node5, 2800, 1, 3600, 1); - + Coord a = new Coord(100., 0.); Coord b = new Coord(100., 100.); Coord c = new Coord(100., 1000.); @@ -86,122 +86,122 @@ public void testNetworkUtil() { Coord g = new Coord(2300., 2000.); Coord h = new Coord(1700., 1000.); Coord i = new Coord(0., 1200.); - - + + Distances distanceA11 = NetworkUtil.getDistances2NodeViaGivenLink(a, link1, node1); - Assert.assertEquals("distanceA11.getDistancePoint2Road()", 100., distanceA11.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceA11.getDistanceRoad2Node()", 0., distanceA11.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(100., distanceA11.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceA11.getDistancePoint2Road()"); + Assertions.assertEquals(0., distanceA11.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceA11.getDistanceRoad2Node()"); + Coord projectionA11 = CoordUtils.orthogonalProjectionOnLineSegment(link1.getFromNode().getCoord(), link1.getToNode().getCoord(), a); - Assert.assertEquals("projectionA11.getX()", 0., projectionA11.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionA11.getY()", 0., projectionA11.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(0., projectionA11.getX(), MatsimTestUtils.EPSILON, "projectionA11.getX()"); + Assertions.assertEquals(0., projectionA11.getY(), MatsimTestUtils.EPSILON, "projectionA11.getY()"); + + Distances distanceB11 = NetworkUtil.getDistances2NodeViaGivenLink(b, link1, node1); - Assert.assertEquals("distanceB11.getDistancePoint2Road()", 100., distanceB11.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceB11.getDistanceRoad2Node()", 100., distanceB11.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(100., distanceB11.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceB11.getDistancePoint2Road()"); + Assertions.assertEquals(100., distanceB11.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceB11.getDistanceRoad2Node()"); + Coord projectionB11 = CoordUtils.orthogonalProjectionOnLineSegment(link1.getFromNode().getCoord(), link1.getToNode().getCoord(), b); - Assert.assertEquals("projectionB11.getX()", 0., projectionB11.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionB11.getY()", 100., projectionB11.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(0., projectionB11.getX(), MatsimTestUtils.EPSILON, "projectionB11.getX()"); + Assertions.assertEquals(100., projectionB11.getY(), MatsimTestUtils.EPSILON, "projectionB11.getY()"); + + Distances distanceB12 = NetworkUtil.getDistances2NodeViaGivenLink(b, link1, node2); - Assert.assertEquals("distanceB12.getDistancePoint2Road()", 100., distanceB12.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceB12.getDistanceRoad2Node()", 900., distanceB12.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(100., distanceB12.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceB12.getDistancePoint2Road()"); + Assertions.assertEquals(900., distanceB12.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceB12.getDistanceRoad2Node()"); + Coord projectionB12 = CoordUtils.orthogonalProjectionOnLineSegment(link1.getFromNode().getCoord(), link1.getToNode().getCoord(), b); - Assert.assertEquals("projectionB12.getX()", 0., projectionB12.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionB12.getY()", 100., projectionB12.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(0., projectionB12.getX(), MatsimTestUtils.EPSILON, "projectionB12.getX()"); + Assertions.assertEquals(100., projectionB12.getY(), MatsimTestUtils.EPSILON, "projectionB12.getY()"); + + Distances distanceC11 = NetworkUtil.getDistances2NodeViaGivenLink(c, link1, node1); - Assert.assertEquals("distanceC11.getDistancePoint2Road()", 100., distanceC11.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceC11.getDistanceRoad2Node()", 1000., distanceC11.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(100., distanceC11.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceC11.getDistancePoint2Road()"); + Assertions.assertEquals(1000., distanceC11.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceC11.getDistanceRoad2Node()"); + Coord projectionC11 = CoordUtils.orthogonalProjectionOnLineSegment(link1.getFromNode().getCoord(), link1.getToNode().getCoord(), c); - Assert.assertEquals("projectionC11.getX()", 0., projectionC11.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionC11.getY()", 1000., projectionC11.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(0., projectionC11.getX(), MatsimTestUtils.EPSILON, "projectionC11.getX()"); + Assertions.assertEquals(1000., projectionC11.getY(), MatsimTestUtils.EPSILON, "projectionC11.getY()"); + + Distances distanceC12 = NetworkUtil.getDistances2NodeViaGivenLink(c, link1, node2); - Assert.assertEquals("distanceC12.getDistancePoint2Road()", 100., distanceC12.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceC12.getDistanceRoad2Node()", 0., distanceC12.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(100., distanceC12.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceC12.getDistancePoint2Road()"); + Assertions.assertEquals(0., distanceC12.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceC12.getDistanceRoad2Node()"); + Coord projectionC12 = CoordUtils.orthogonalProjectionOnLineSegment(link1.getFromNode().getCoord(), link1.getToNode().getCoord(), c); - Assert.assertEquals("projectionC12.getX()", 0., projectionC12.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionC12.getY()", 1000., projectionC12.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(0., projectionC12.getX(), MatsimTestUtils.EPSILON, "projectionC12.getX()"); + Assertions.assertEquals(1000., projectionC12.getY(), MatsimTestUtils.EPSILON, "projectionC12.getY()"); + + Distances distanceC22 = NetworkUtil.getDistances2NodeViaGivenLink(c, link2, node2); - Assert.assertEquals("distanceC22.getDistancePoint2Road()", Math.sqrt(2.) / 2. * 100., distanceC22.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceC22.getDistanceRoad2Node()", Math.sqrt(2.) / 2. * 100., distanceC22.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(Math.sqrt(2.) / 2. * 100., distanceC22.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceC22.getDistancePoint2Road()"); + Assertions.assertEquals(Math.sqrt(2.) / 2. * 100., distanceC22.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceC22.getDistanceRoad2Node()"); + Coord projectionC22 = CoordUtils.orthogonalProjectionOnLineSegment(link2.getFromNode().getCoord(), link2.getToNode().getCoord(), c); - Assert.assertEquals("projectionC22.getX()", 50., projectionC22.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionC22.getY()", 1050., projectionC22.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(50., projectionC22.getX(), MatsimTestUtils.EPSILON, "projectionC22.getX()"); + Assertions.assertEquals(1050., projectionC22.getY(), MatsimTestUtils.EPSILON, "projectionC22.getY()"); + + Distances distanceC23 = NetworkUtil.getDistances2NodeViaGivenLink(c, link2, node3); - Assert.assertEquals("distanceC23.getDistancePoint2Road()", Math.sqrt(2.) / 2. * 100., distanceC23.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceC23.getDistanceRoad2Node()", Math.sqrt(2) * 1000. - Math.sqrt(2.) / 2. * 100., distanceC23.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(Math.sqrt(2.) / 2. * 100., distanceC23.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceC23.getDistancePoint2Road()"); + Assertions.assertEquals(Math.sqrt(2) * 1000. - Math.sqrt(2.) / 2. * 100., distanceC23.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceC23.getDistanceRoad2Node()"); + Coord projectionC23 = CoordUtils.orthogonalProjectionOnLineSegment(link2.getFromNode().getCoord(), link2.getToNode().getCoord(), c); - Assert.assertEquals("projectionC23.getX()", 50., projectionC23.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionC23.getY()", 1050., projectionC23.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(50., projectionC23.getX(), MatsimTestUtils.EPSILON, "projectionC23.getX()"); + Assertions.assertEquals(1050., projectionC23.getY(), MatsimTestUtils.EPSILON, "projectionC23.getY()"); + + Distances distanceD22 = NetworkUtil.getDistances2NodeViaGivenLink(d, link2, node2); - Assert.assertEquals("distanceD22.getDistancePoint2Road()", Math.sqrt(2.) / 2. * 100.0, distanceD22.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceD22.getDistanceRoad2Node()", Math.sqrt(2.) / 2. * 100.0 + Math.sqrt(2) * 200., distanceD22.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(Math.sqrt(2.) / 2. * 100.0, distanceD22.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceD22.getDistancePoint2Road()"); + Assertions.assertEquals(Math.sqrt(2.) / 2. * 100.0 + Math.sqrt(2) * 200., distanceD22.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceD22.getDistanceRoad2Node()"); + Coord projectionD22 = CoordUtils.orthogonalProjectionOnLineSegment(link2.getFromNode().getCoord(), link2.getToNode().getCoord(), d); - Assert.assertEquals("projectionD22.getX()", 250., projectionD22.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionD22.getY()", 1250., projectionD22.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(250., projectionD22.getX(), MatsimTestUtils.EPSILON, "projectionD22.getX()"); + Assertions.assertEquals(1250., projectionD22.getY(), MatsimTestUtils.EPSILON, "projectionD22.getY()"); + + Distances distanceD23 = NetworkUtil.getDistances2NodeViaGivenLink(d, link2, node3); - Assert.assertEquals("distanceD23.getDistancePoint2Road()", Math.sqrt(2.)/2.*100.0, distanceD23.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceD23.getDistanceRoad2Node()", Math.sqrt(2.)/2.*100.0 + Math.sqrt(2) * 700., distanceD23.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(Math.sqrt(2.)/2.*100.0, distanceD23.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceD23.getDistancePoint2Road()"); + Assertions.assertEquals(Math.sqrt(2.)/2.*100.0 + Math.sqrt(2) * 700., distanceD23.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceD23.getDistanceRoad2Node()"); + Coord projectionD23 = CoordUtils.orthogonalProjectionOnLineSegment(link2.getFromNode().getCoord(), link2.getToNode().getCoord(), d); - Assert.assertEquals("projectionD23.getX()", 250., projectionD23.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionD23.getY()", 1250., projectionD23.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(250., projectionD23.getX(), MatsimTestUtils.EPSILON, "projectionD23.getX()"); + Assertions.assertEquals(1250., projectionD23.getY(), MatsimTestUtils.EPSILON, "projectionD23.getY()"); + + Distances distanceE33 = NetworkUtil.getDistances2NodeViaGivenLink(e, link3, node3); - Assert.assertEquals("distanceE33.getDistancePoint2Road()", 100.0, distanceE33.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceE33.getDistanceRoad2Node()", 300.0, distanceE33.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(100.0, distanceE33.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceE33.getDistancePoint2Road()"); + Assertions.assertEquals(300.0, distanceE33.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceE33.getDistanceRoad2Node()"); Coord projectionE33 = CoordUtils.orthogonalProjectionOnLineSegment(link3.getFromNode().getCoord(), link3.getToNode().getCoord(), e); - Assert.assertEquals("projectionE33.getX()", 1300., projectionE33.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionE33.getY()", 2000., projectionE33.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(1300., projectionE33.getX(), MatsimTestUtils.EPSILON, "projectionE33.getX()"); + Assertions.assertEquals(2000., projectionE33.getY(), MatsimTestUtils.EPSILON, "projectionE33.getY()"); + + Distances distanceE34 = NetworkUtil.getDistances2NodeViaGivenLink(e, link3, node4); - Assert.assertEquals("distanceE34.getDistancePoint2Road()", 100.0, distanceE34.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceE34.getDistanceRoad2Node()", 700.0, distanceE34.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(100.0, distanceE34.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceE34.getDistancePoint2Road()"); + Assertions.assertEquals(700.0, distanceE34.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceE34.getDistanceRoad2Node()"); Coord projectionE34 = CoordUtils.orthogonalProjectionOnLineSegment(link3.getFromNode().getCoord(), link3.getToNode().getCoord(), e); - Assert.assertEquals("projectionE34.getX()", 1300., projectionE34.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionE34.getY()", 2000., projectionE34.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(1300., projectionE34.getX(), MatsimTestUtils.EPSILON, "projectionE34.getX()"); + Assertions.assertEquals(2000., projectionE34.getY(), MatsimTestUtils.EPSILON, "projectionE34.getY()"); + + Distances distanceF33 = NetworkUtil.getDistances2NodeViaGivenLink(f, link3, node3); - Assert.assertEquals("distanceF33.getDistancePoint2Road()", Math.sqrt(Math.pow(100, 2) + Math.pow(300, 2)), distanceF33.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceF33.getDistanceRoad2Node()", 1000., distanceF33.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(Math.sqrt(Math.pow(100, 2) + Math.pow(300, 2)), distanceF33.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceF33.getDistancePoint2Road()"); + Assertions.assertEquals(1000., distanceF33.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceF33.getDistanceRoad2Node()"); + Coord projectionF33 = CoordUtils.orthogonalProjectionOnLineSegment(link3.getFromNode().getCoord(), link3.getToNode().getCoord(), e); - Assert.assertEquals("projectionF33.getX()", 1300., projectionF33.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionF33.getY()", 2000., projectionF33.getY(), MatsimTestUtils.EPSILON); - - + Assertions.assertEquals(1300., projectionF33.getX(), MatsimTestUtils.EPSILON, "projectionF33.getX()"); + Assertions.assertEquals(2000., projectionF33.getY(), MatsimTestUtils.EPSILON, "projectionF33.getY()"); + + Distances distanceF34 = NetworkUtil.getDistances2NodeViaGivenLink(f, link3, node4); - Assert.assertEquals("distanceF34.getDistancePoint2Road()", Math.sqrt(Math.pow(100, 2) + Math.pow(300, 2)), distanceF34.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON); - Assert.assertEquals("distanceF34.getDistanceRoad2Node()", 0., distanceF34.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON); - + Assertions.assertEquals(Math.sqrt(Math.pow(100, 2) + Math.pow(300, 2)), distanceF34.getDistancePoint2Intersection(), MatsimTestUtils.EPSILON, "distanceF34.getDistancePoint2Road()"); + Assertions.assertEquals(0., distanceF34.getDistanceIntersection2Node(), MatsimTestUtils.EPSILON, "distanceF34.getDistanceRoad2Node()"); + Coord projectionF34 = CoordUtils.orthogonalProjectionOnLineSegment(link3.getFromNode().getCoord(), link3.getToNode().getCoord(), f); - Assert.assertEquals("projectionF34.getX()", 2000., projectionF34.getX(), MatsimTestUtils.EPSILON); - Assert.assertEquals("projectionF34.getY()", 2000., projectionF34.getY(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(2000., projectionF34.getX(), MatsimTestUtils.EPSILON, "projectionF34.getX()"); + Assertions.assertEquals(2000., projectionF34.getY(), MatsimTestUtils.EPSILON, "projectionF34.getY()"); } -} \ No newline at end of file +} 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 29283b26ede..8c1e52924b4 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 @@ -23,9 +23,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; @@ -57,10 +57,10 @@ public class TinyAccessibilityTest { private static final Logger LOG = LogManager.getLogger(TinyAccessibilityTest.class); - @Rule public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension private MatsimTestUtils utils = new MatsimTestUtils(); @Test - public void runFromEvents() { + void runFromEvents() { final Config config = createTestConfig(); double min = 0.; // Values for bounding box usually come from a config file @@ -86,7 +86,7 @@ public void runFromEvents() { } @Test - public void testWithBoundingBox() { + void testWithBoundingBox() { final Config config = createTestConfig(); double min = 0.; // Values for bounding box usually come from a config file @@ -262,20 +262,20 @@ public void finish() { LOG.warn("CHECK X = " + tuple.getFirst().getCoord().getX() + " -- Y = " + tuple.getFirst().getCoord().getY() + " -- car value = " + accessibilitiesMap.get(tuple).get(TransportMode.car)); if (tuple.getFirst().getCoord().getX() == 50.) { if (tuple.getFirst().getCoord().getY() == 50.) { - Assert.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); - Assert.assertEquals(-0.017240250823867296, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); + Assertions.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); + Assertions.assertEquals(-0.017240250823867296, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); } else if (tuple.getFirst().getCoord().getY() == 150.) { - Assert.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); - Assert.assertEquals(-0.017240250823867296, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); + Assertions.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); + Assertions.assertEquals(-0.017240250823867296, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); } } if (tuple.getFirst().getCoord().getX() == 150.) { if (tuple.getFirst().getCoord().getY() == 50.) { - Assert.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); - Assert.assertEquals(0.27582980607476704, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.27582980607476704, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); } else if (tuple.getFirst().getCoord().getY() == 150.) { - Assert.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); - Assert.assertEquals(0.27582980607476704, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.27582980607476704, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); } } } 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 bde5a98c612..43574962078 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 @@ -21,10 +21,10 @@ 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.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; @@ -65,11 +65,12 @@ public class TinyMultimodalAccessibilityTest { private static final Logger LOG = LogManager.getLogger(TinyMultimodalAccessibilityTest.class); - @Rule public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension private MatsimTestUtils utils = new MatsimTestUtils(); + // non-deterministic presumably because of multi-threading. kai, sep'19 @Test - @Ignore // non-deterministic presumably because of multi-threading. kai, sep'19 - public void testWithBoundingBox() { + @Disabled + void testWithBoundingBox() { final Config config = createTestConfig(); double min = 0.; // Values for bounding box usually come from a config file @@ -309,24 +310,24 @@ public void finish() { LOG.warn("CHECK X = " + tuple.getFirst().getCoord().getX() + " -- Y = " + tuple.getFirst().getCoord().getY() + " -- car value = " + accessibilitiesMap.get(tuple).get(TransportMode.car)); if (tuple.getFirst().getCoord().getX() == 50.) { if (tuple.getFirst().getCoord().getY() == 50.) { - Assert.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); - Assert.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); - Assert.assertEquals(0.0020510618020555325, accessibilitiesMap.get(tuple).get(TransportMode.pt), MatsimTestUtils.EPSILON); + Assertions.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); + Assertions.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.0020510618020555325, accessibilitiesMap.get(tuple).get(TransportMode.pt), MatsimTestUtils.EPSILON); } else if (tuple.getFirst().getCoord().getY() == 150.) { - Assert.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); - Assert.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); - Assert.assertEquals(-0.04152005026781742, accessibilitiesMap.get(tuple).get(TransportMode.pt), MatsimTestUtils.EPSILON); + Assertions.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); + Assertions.assertEquals(-0.017248522428805767, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); + Assertions.assertEquals(-0.04152005026781742, accessibilitiesMap.get(tuple).get(TransportMode.pt), MatsimTestUtils.EPSILON); } } if (tuple.getFirst().getCoord().getX() == 150.) { if (tuple.getFirst().getCoord().getY() == 50.) { - Assert.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); - Assert.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); - Assert.assertEquals(0.25069951470887114, accessibilitiesMap.get(tuple).get(TransportMode.pt), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.25069951470887114, accessibilitiesMap.get(tuple).get(TransportMode.pt), MatsimTestUtils.EPSILON); } else if (tuple.getFirst().getCoord().getY() == 150.) { - Assert.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); - Assert.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); - Assert.assertEquals(0.25069951470887114, accessibilitiesMap.get(tuple).get(TransportMode.pt), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get("freespeed"), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.2758252376673665, accessibilitiesMap.get(tuple).get(TransportMode.car), MatsimTestUtils.EPSILON); + Assertions.assertEquals(0.25069951470887114, accessibilitiesMap.get(tuple).get(TransportMode.pt), MatsimTestUtils.EPSILON); } } } diff --git a/contribs/accidents/pom.xml b/contribs/accidents/pom.xml index 365d6c8a8d0..b3b74179e0a 100644 --- a/contribs/accidents/pom.xml +++ b/contribs/accidents/pom.xml @@ -3,7 +3,7 @@ org.matsim contrib - 16.0-SNAPSHOT + 2025.0-SNAPSHOT 4.0.0 org.matsim.contrib diff --git a/contribs/accidents/src/main/java/org/matsim/contrib/accidents/runExample/AccidentsNetworkModification.java b/contribs/accidents/src/main/java/org/matsim/contrib/accidents/runExample/AccidentsNetworkModification.java index 6794cd558d6..0cd56b5fd7f 100644 --- a/contribs/accidents/src/main/java/org/matsim/contrib/accidents/runExample/AccidentsNetworkModification.java +++ b/contribs/accidents/src/main/java/org/matsim/contrib/accidents/runExample/AccidentsNetworkModification.java @@ -28,10 +28,11 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.geotools.data.DataStore; -import org.geotools.data.FileDataStoreFinder; +import org.geotools.api.data.DataStore; +import org.geotools.api.data.FileDataStoreFinder; +import org.geotools.api.data.SimpleFeatureSource; +import org.geotools.api.feature.simple.SimpleFeature; import org.geotools.data.simple.SimpleFeatureIterator; -import org.geotools.data.simple.SimpleFeatureSource; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; @@ -44,8 +45,7 @@ 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; +import org.matsim.core.utils.gis.GeoFileReader; /** * @author mmayobre, ikaddoura @@ -59,26 +59,26 @@ public class AccidentsNetworkModification { public AccidentsNetworkModification(Scenario scenario) { this.scenario = scenario; } - + public Network setLinkAttributsBasedOnOSMFile(String landuseOsmFile, String osmCRS, String[] tunnelLinkIDs, String[] planfreeLinkIDs) throws MalformedURLException, IOException { - + AccidentsConfigGroup accidentsCfg = (AccidentsConfigGroup) scenario.getConfig().getModules().get(AccidentsConfigGroup.GROUP_NAME); - + Map landUseFeaturesBB = new HashMap<>(); Map landUseDataBB = new HashMap<>(); - + log.info("Initializing all link-specific information..."); - + if (landuseOsmFile == null) { log.warn("Landuse shape file is null. Using default values..."); } else { SimpleFeatureSource ftsLandUseBB; if (!landuseOsmFile.startsWith("http")) { - ftsLandUseBB = ShapeFileReader.readDataFile(landuseOsmFile); + ftsLandUseBB = GeoFileReader.readDataFile(landuseOsmFile); } else { ftsLandUseBB = FileDataStoreFinder.getDataStore(new URL(landuseOsmFile)).getFeatureSource(); - } + } try (SimpleFeatureIterator itLandUseBB = ftsLandUseBB.getFeatures().features()) { while (itLandUseBB.hasNext()) { SimpleFeature ftLandUseBB = itLandUseBB.next(); @@ -95,23 +95,23 @@ public Network setLinkAttributsBasedOnOSMFile(String landuseOsmFile, String osmC e.printStackTrace(); } } - + int linkCounter = 0; for (Link link : this.scenario.getNetwork().getLinks().values()) { - + if (linkCounter % 100 == 0) { log.info("Link #" + linkCounter + " (" + (int) ((double) linkCounter / this.scenario.getNetwork().getLinks().size() * 100) + "%)"); } - linkCounter++; - + linkCounter++; + link.getAttributes().putAttribute(accidentsCfg.getAccidentsComputationMethodAttributeName(), AccidentsConfigGroup.AccidentsComputationMethod.BVWP.toString()); - + ArrayList bvwpRoadType = new ArrayList<>(); - + // 'plangleich', 'planfrei' or tunnel? bvwpRoadType.add(0, 1); - + for(int j=0; j < planfreeLinkIDs.length; j++){ if(planfreeLinkIDs[j].equals(String.valueOf(link.getId()))){ bvwpRoadType.set(0, 0); // Change to Plan free @@ -119,7 +119,7 @@ public Network setLinkAttributsBasedOnOSMFile(String landuseOsmFile, String osmC break; } } - + for(int i=0; i < tunnelLinkIDs.length; i++){ if(tunnelLinkIDs[i].equals(String.valueOf(link.getId()))){ bvwpRoadType.set(0, 2); // Change to Tunnel @@ -127,25 +127,25 @@ public Network setLinkAttributsBasedOnOSMFile(String landuseOsmFile, String osmC break; } } - + // builtup or not builtup area? String osmLandUseFeatureBBId = getOSMLandUseFeatureBBId(link, landUseFeaturesBB, osmCRS); - - if (osmLandUseFeatureBBId == null) { + + if (osmLandUseFeatureBBId == null) { log.warn("No area type found for link " + link.getId() + ". Using default value: not built-up area."); if (link.getFreespeed() > 16.) { bvwpRoadType.add(1, 0); } else { bvwpRoadType.add(1, 2); } - + } else { String landUseTypeBB = landUseDataBB.get(osmLandUseFeatureBBId); if (landUseTypeBB.matches("commercial|industrial|recreation_ground|residential|retail")) { //built-up area if (link.getFreespeed() > 16.) { bvwpRoadType.add(1, 1); } else { - bvwpRoadType.add(1, 3); + bvwpRoadType.add(1, 3); } } else { if (link.getFreespeed() > 16.) { @@ -163,85 +163,85 @@ public Network setLinkAttributsBasedOnOSMFile(String landuseOsmFile, String osmC numberOfLanesBVWP = (int) link.getNumberOfLanes(); } bvwpRoadType.add(2, numberOfLanesBVWP); - + link.getAttributes().putAttribute( AccidentsConfigGroup.BVWP_ROAD_TYPE_ATTRIBUTE_NAME, bvwpRoadType.get(0) + "," + bvwpRoadType.get(1) + "," + bvwpRoadType.get(2)); } log.info("Initializing all link-specific information... Done."); return scenario.getNetwork(); } - + private String getOSMLandUseFeatureBBId(Link link, Map landUseFeaturesBB, String osmCRS) { - + if (landUseFeaturesBB == null || landUseFeaturesBB.isEmpty()) return null; - + CoordinateTransformation ctScenarioCRS2osmCRS = TransformationFactory.getCoordinateTransformation(this.scenario.getConfig().global().getCoordinateSystem(), osmCRS); - + Coord linkCoordinateTransformedToOSMCRS = ctScenarioCRS2osmCRS.transform(link.getCoord()); // this Method gives the middle point of the link back Point pMiddle = MGC.xy2Point(linkCoordinateTransformedToOSMCRS.getX(), linkCoordinateTransformedToOSMCRS.getY()); - + Coord linkStartCoordinateTransformedToOSMCRS = ctScenarioCRS2osmCRS.transform(link.getFromNode().getCoord()); Point pStart = MGC.xy2Point(linkStartCoordinateTransformedToOSMCRS.getX(), linkStartCoordinateTransformedToOSMCRS.getY()); - + Coord linkEndCoordinateTransformedToOSMCRS = ctScenarioCRS2osmCRS.transform(link.getToNode().getCoord()); Point pEnd = MGC.xy2Point(linkEndCoordinateTransformedToOSMCRS.getX(), linkEndCoordinateTransformedToOSMCRS.getY()); - + String osmLandUseFeatureBBId = null; - + for (SimpleFeature feature : landUseFeaturesBB.values()) { if (((Geometry) feature.getDefaultGeometry()).contains(pMiddle)) { return osmLandUseFeatureBBId = feature.getAttribute("osm_id").toString(); } } - + for (SimpleFeature feature : landUseFeaturesBB.values()) { if (((Geometry) feature.getDefaultGeometry()).contains(pStart)) { return osmLandUseFeatureBBId = feature.getAttribute("osm_id").toString(); } } - + for (SimpleFeature feature : landUseFeaturesBB.values()) { if (((Geometry) feature.getDefaultGeometry()).contains(pEnd)) { return osmLandUseFeatureBBId = feature.getAttribute("osm_id").toString(); } } - + // look around the link - + GeometryFactory geoFac = new GeometryFactory(); CoordinateTransformation cTosmCRSToGK4 = TransformationFactory.getCoordinateTransformation(osmCRS, "EPSG:31468"); - - double distance = 10.0; - + + double distance = 10.0; + while (osmLandUseFeatureBBId == null && distance <= 500) { Coord coordGK4 = cTosmCRSToGK4.transform(MGC.coordinate2Coord(pMiddle.getCoordinate())); Point pGK4 = geoFac.createPoint(MGC.coord2Coordinate(coordGK4)); - + Point pRightGK4 = geoFac.createPoint(new Coordinate(pGK4.getX() + distance, pGK4.getY())); Point pRight = transformPointFromGK4ToOSMCRS(pRightGK4, osmCRS); - + Point pDownGK4 = geoFac.createPoint(new Coordinate(pGK4.getX(), pGK4.getY() - distance)); Point pDown = transformPointFromGK4ToOSMCRS(pDownGK4, osmCRS); - + Point pLeftGK4 = geoFac.createPoint(new Coordinate(pGK4.getX() - distance, pGK4.getY())); Point pLeft = transformPointFromGK4ToOSMCRS(pLeftGK4, osmCRS); - + Point pUpGK4 = geoFac.createPoint(new Coordinate(pGK4.getX(), pGK4.getY() + distance)); Point pUp = transformPointFromGK4ToOSMCRS(pUpGK4, osmCRS); - + Point pUpRightGK4 = geoFac.createPoint(new Coordinate(pGK4.getX() + distance, pGK4.getY() + distance)); Point pUpRight = transformPointFromGK4ToOSMCRS(pUpRightGK4, osmCRS); - + Point pDownRightGK4 = geoFac.createPoint(new Coordinate(pGK4.getX() + distance, pGK4.getY() - distance)); Point pDownRight = transformPointFromGK4ToOSMCRS(pDownRightGK4, osmCRS); - + Point pDownLeftGK4 = geoFac.createPoint(new Coordinate(pGK4.getX() - distance, pGK4.getY() - distance)); Point pDownLeft = transformPointFromGK4ToOSMCRS(pDownLeftGK4, osmCRS); - + Point pUpLeftGK4 = geoFac.createPoint(new Coordinate(pGK4.getX() - distance, pGK4.getY() + distance)); Point pUpLeft = transformPointFromGK4ToOSMCRS(pUpLeftGK4, osmCRS); - + for (SimpleFeature feature : landUseFeaturesBB.values()) { - + if (((Geometry) feature.getDefaultGeometry()).contains(pRight)) { osmLandUseFeatureBBId = feature.getAttribute("osm_id").toString(); return osmLandUseFeatureBBId; @@ -268,17 +268,17 @@ private String getOSMLandUseFeatureBBId(Link link, Map la return osmLandUseFeatureBBId; } } - + distance += 10.0; } - + log.warn("No area type found. Returning null..."); return null; } private Point transformPointFromGK4ToOSMCRS(Point pointGK4, String osmCRS) { CoordinateTransformation ctGK4toOSMCRS = TransformationFactory.getCoordinateTransformation("EPSG:31468", osmCRS); - + Coord coordGK4 = MGC.coordinate2Coord(pointGK4.getCoordinate()); Point pointOSMCRS = new GeometryFactory().createPoint(MGC.coord2Coordinate(ctGK4toOSMCRS.transform(coordGK4))); return pointOSMCRS; diff --git a/contribs/accidents/src/test/java/org/matsim/contrib/accidents/BvwpAccidentsCostComputationTest.java b/contribs/accidents/src/test/java/org/matsim/contrib/accidents/BvwpAccidentsCostComputationTest.java index 9acd427bef7..3cb595ee1e6 100644 --- a/contribs/accidents/src/test/java/org/matsim/contrib/accidents/BvwpAccidentsCostComputationTest.java +++ b/contribs/accidents/src/test/java/org/matsim/contrib/accidents/BvwpAccidentsCostComputationTest.java @@ -2,8 +2,8 @@ import java.util.ArrayList; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; @@ -12,7 +12,7 @@ import org.matsim.api.core.v01.network.Node; import org.matsim.core.network.NetworkUtils; import org.matsim.testcases.MatsimTestUtils; -; + /** * @author ikaddoura, mmayobre @@ -20,9 +20,9 @@ * */ public class BvwpAccidentsCostComputationTest { - + @Test - public void test1() { + void test1() { Network network = NetworkUtils.createNetwork(); NetworkFactory factory = network.getFactory(); @@ -40,11 +40,11 @@ public void test1() { list.add(2, 2); //2 Lanes double costs = AccidentCostComputationBVWP.computeAccidentCosts(4820, link1, list); - Assert.assertEquals("wrong cost", 1772.13863066011, costs, MatsimTestUtils.EPSILON); + Assertions.assertEquals(1772.13863066011, costs, MatsimTestUtils.EPSILON, "wrong cost"); } - + @Test - public void test2() { + void test2() { Network network = NetworkUtils.createNetwork(); NetworkFactory factory = network.getFactory(); @@ -62,11 +62,11 @@ public void test2() { list.add(2, 2); //2 Lanes double costs = AccidentCostComputationBVWP.computeAccidentCosts(1000, link1, list); - Assert.assertEquals("wrong cost", 23.165, costs, MatsimTestUtils.EPSILON); + Assertions.assertEquals(23.165, costs, MatsimTestUtils.EPSILON, "wrong cost"); } - + @Test - public void test3() { + void test3() { Network network = NetworkUtils.createNetwork(); NetworkFactory factory = network.getFactory(); @@ -84,6 +84,6 @@ public void test3() { list.add(2, 3); //2 Lanes double costs = AccidentCostComputationBVWP.computeAccidentCosts(1000, link1, list); - Assert.assertEquals("wrong cost", 101.53, costs, MatsimTestUtils.EPSILON); + Assertions.assertEquals(101.53, costs, MatsimTestUtils.EPSILON, "wrong cost"); } } 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 b98c144164f..f07d1d8d5f9 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 @@ -3,9 +3,9 @@ import java.io.BufferedReader; import java.io.IOException; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.accidents.AccidentsConfigGroup.AccidentsComputationMethod; @@ -24,10 +24,10 @@ */ public class RunTest { - @Rule public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension private MatsimTestUtils utils = new MatsimTestUtils(); @Test - public void test1() { + void test1() { String configFile = utils.getPackageInputDirectory() + "/trial_scenario/trial_scenario_config.xml"; String outputDirectory = utils.getOutputDirectory(); @@ -86,12 +86,12 @@ public void test1() { if (lineCounter == 0 && column == 25) { double accidentCosts = Double.valueOf(columns[column]); - Assert.assertEquals("wrong accident costs", 10.38, accidentCosts , MatsimTestUtils.EPSILON); + Assertions.assertEquals(10.38, accidentCosts , MatsimTestUtils.EPSILON, "wrong accident costs"); } if (lineCounter == 1 && column == 25) { double accidentCosts = Double.valueOf(columns[column]); - Assert.assertEquals("wrong accident costs", 16.68, accidentCosts , MatsimTestUtils.EPSILON); + Assertions.assertEquals(16.68, accidentCosts , MatsimTestUtils.EPSILON, "wrong accident costs"); } } 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 d537b8c40e4..486baf7f3ec 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 @@ -1,10 +1,11 @@ package org.matsim.contrib.accidents; import java.io.BufferedReader; -import java.io.IOException; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import java.io.IOException; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; @@ -15,14 +16,14 @@ import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; -import org.matsim.testcases.MatsimTestUtils; - +import org.matsim.testcases.MatsimTestUtils; + public class RunTestEquil { - @Rule public MatsimTestUtils utils = new MatsimTestUtils(); - - @Test - public void test1() { + @RegisterExtension private MatsimTestUtils utils = new MatsimTestUtils(); + + @Test + void test1() { String configFile = utils.getPackageInputDirectory() + "/equil_scenario/config.xml"; String outputDirectory = utils.getOutputDirectory(); String runId = "run1"; @@ -88,7 +89,7 @@ public void test1() { int agents = 100; int lengthKM = 35; double accidentCostsManualCalculation = (agents * lengthKM * 61.785) / 1000. * 10; - Assert.assertEquals("wrong accident costs", accidentCostsManualCalculation, accidentCosts , 0.01); + Assertions.assertEquals(accidentCostsManualCalculation, accidentCosts , 0.01, "wrong accident costs"); } // link 1 if (lineCounter == 11 && column == 121) { @@ -96,7 +97,7 @@ public void test1() { int agents = 100; int lengthKM = 10; double accidentCostsManualCalculation = (agents * lengthKM * 61.785) / 1000. * 10; - Assert.assertEquals("wrong accident costs", accidentCostsManualCalculation, accidentCosts , 0.01); + Assertions.assertEquals(accidentCostsManualCalculation, accidentCosts , 0.01, "wrong accident costs"); } // link 6 @@ -105,7 +106,7 @@ public void test1() { int agents = 100; int lengthKM = 10; double accidentCostsManualCalculation = (agents * lengthKM * 34.735) / 1000. * 10; - Assert.assertEquals("wrong accident costs", accidentCostsManualCalculation, accidentCosts , 0.01); + Assertions.assertEquals(accidentCostsManualCalculation, accidentCosts , 0.01, "wrong accident costs"); } // link 15 @@ -114,7 +115,7 @@ public void test1() { int agents = 100; int lengthKM = 5; double accidentCostsManualCalculation = (agents * lengthKM * 31.63) / 1000. * 10; - Assert.assertEquals("wrong accident costs", accidentCostsManualCalculation, accidentCosts , 0.01); + Assertions.assertEquals(accidentCostsManualCalculation, accidentCosts , 0.01, "wrong accident costs"); } } diff --git a/contribs/analysis/pom.xml b/contribs/analysis/pom.xml index e164c142592..74a32b64c03 100644 --- a/contribs/analysis/pom.xml +++ b/contribs/analysis/pom.xml @@ -3,7 +3,7 @@ org.matsim contrib - 16.0-SNAPSHOT + 2025.0-SNAPSHOT 4.0.0 org.matsim.contrib @@ -13,26 +13,26 @@ org.matsim.contrib roadpricing - 16.0-SNAPSHOT + 2025.0-SNAPSHOT org.osgeo proj4j 0.1.0 - - com.googlecode.json-simple - json-simple - 1.1.1 - - + + com.google.code.gson + gson + 2.11.0 + + org.apache.commons commons-math3 org.apache.httpcomponents.client5 httpclient5 - 5.2.1 + 5.3.1 diff --git a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/TravelTimesWriter.java b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/TravelTimesWriter.java index 21e616f6896..12b9efdcffb 100644 --- a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/TravelTimesWriter.java +++ b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/christoph/TravelTimesWriter.java @@ -28,6 +28,8 @@ import java.util.Map; import java.util.Map.Entry; +import org.geotools.api.feature.simple.SimpleFeature; +import org.geotools.api.referencing.crs.CoordinateReferenceSystem; import org.locationtech.jts.geom.Coordinate; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.network.Link; @@ -41,10 +43,8 @@ import org.matsim.core.trafficmonitoring.TimeBinUtils; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.gis.PolylineFeatureFactory; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.matsim.core.utils.io.IOUtils; -import org.opengis.feature.simple.SimpleFeature; -import org.opengis.referencing.crs.CoordinateReferenceSystem; /** * Analyzes the average link travel times and writes them to files (absolute and @@ -190,7 +190,7 @@ private void writeRows(BufferedWriter timesWriter, boolean absolute) throws IOEx public void writeAbsoluteSHPTravelTimes(String file, CoordinateReferenceSystem crs, boolean ignoreExitLinks) { try { Collection ft = generateSHPFileData(crs, this.network, true, ignoreExitLinks); - ShapeFileWriter.writeGeometries(ft, file); + GeoFileWriter.writeGeometries(ft, file); } catch (Exception e) { throw new RuntimeException(e); } @@ -199,7 +199,7 @@ public void writeAbsoluteSHPTravelTimes(String file, CoordinateReferenceSystem c public void writeRelativeSHPTravelTimes(String file, CoordinateReferenceSystem crs, boolean ignoreExitLinks) { try { Collection ft = generateSHPFileData(crs, this.network, false, ignoreExitLinks); - ShapeFileWriter.writeGeometries(ft, file); + GeoFileWriter.writeGeometries(ft, file); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidator.java b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidator.java index b8aa76c34e1..7d35886428d 100644 --- a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidator.java +++ b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidator.java @@ -1,11 +1,11 @@ package org.matsim.contrib.analysis.vsp.traveltimedistance; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; import org.matsim.api.core.v01.Coord; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.geometry.CoordinateTransformation; @@ -20,6 +20,7 @@ import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Locale; +import java.util.Optional; public class GoogleMapRouteValidator implements TravelTimeDistanceValidator { private static final Logger log = LogManager.getLogger(GoogleMapRouteValidator.class); @@ -51,9 +52,6 @@ public Tuple getTravelTime(NetworkTrip trip) { @Override public Tuple getTravelTime(Coord fromCoord, Coord toCoord, double departureTime, String tripId) { - long travelTime = 0; - long distance = 0; - double adjustedDepartureTime = calculateGoogleDepartureTime(departureTime); Coord from = ct.transform(fromCoord); Coord to = ct.transform(toCoord); @@ -71,32 +69,46 @@ public Tuple getTravelTime(Coord fromCoord, Coord toCoord, doubl "&origins=" + df.format(from.getY()) + "%2C" + df.format(from.getX()) + "&key=" + apiAccessKey; + log.info(urlString); + + Optional> result; try { - log.info(urlString); URL url = new URL(urlString); - try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) { - JSONParser jp = new JSONParser(); - JSONObject jsonObject = (JSONObject) jp.parse(in); - JSONArray rows = (JSONArray) jsonObject.get("rows"); - if (!rows.isEmpty()) { - JSONArray elements = (JSONArray) ((JSONObject) rows.get(0)).get("elements"); - JSONObject results = (JSONObject) elements.get(0); - if (results.containsKey("distance")) { - JSONObject distanceResults = (JSONObject) results.get("distance"); - distance = (long) distanceResults.get("value"); - } - if (results.containsKey("duration_in_traffic")) { - JSONObject timeResults = (JSONObject) results.get("duration_in_traffic"); - travelTime = (long) timeResults.get("value"); - } - } - } - } catch (IOException | ParseException e) { + BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); + result = readFromJson(in); + } catch (IOException e) { log.error("The contents on the URL cannot be read properly. Please check your API or check the contents on URL manually", e); + result = Optional.empty(); } - return new Tuple<>((double) travelTime, (double) distance); + return result.orElse(new Tuple<>(0.0, 0.0)); } + Optional> readFromJson(BufferedReader reader) throws IOException { + JsonElement jsonElement = JsonParser.parseReader(reader); + if(!jsonElement.isJsonObject()){ + return Optional.empty(); + } + JsonObject jsonObject = jsonElement.getAsJsonObject(); + JsonArray rows = jsonObject.getAsJsonArray("rows"); + + if (rows.isEmpty()) { + return Optional.empty(); + } + + JsonObject results = rows.get(0).getAsJsonObject().get("elements").getAsJsonArray().get(0).getAsJsonObject(); + + if (!results.has("distance") && !results.has("duration_in_traffic")) { + return Optional.empty(); + } + + JsonObject distanceResults = results.get("distance").getAsJsonObject(); + double distance = distanceResults.get("value").getAsDouble(); + JsonObject timeResults = results.get("duration_in_traffic").getAsJsonObject(); + double travelTime = timeResults.get("value").getAsDouble(); + + return Optional.of(new Tuple<>(travelTime, distance)); + } + private double calculateGoogleDepartureTime(double departureTime) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate googleDate0 = LocalDate.parse("1970-01-01", dateTimeFormatter); diff --git a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidator.java b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidator.java index 9af9cff72c9..b437d7dffb8 100644 --- a/contribs/analysis/src/main/java/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidator.java +++ b/contribs/analysis/src/main/java/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidator.java @@ -28,13 +28,14 @@ import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; +import java.util.Optional; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; import org.matsim.api.core.v01.Coord; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.geometry.CoordinateTransformation; @@ -91,9 +92,6 @@ public Tuple getTravelTime(NetworkTrip trip) { @Override public Tuple getTravelTime(Coord fromCoord, Coord toCoord, double departureTime, String tripId) { - long travelTime = 0; - long distance = 0; - Coord from = transformation.transform(fromCoord); Coord to = transformation.transform(toCoord); @@ -110,36 +108,48 @@ public Tuple getTravelTime(Coord fromCoord, Coord toCoord, doubl log.info(urlString); + Optional> result; try { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); - JSONParser jp = new JSONParser(); - JSONObject jsonObject = (JSONObject) jp.parse(in); - JSONArray routes = (JSONArray) jsonObject.get("routes"); - - if (!routes.isEmpty()) { - JSONObject route = (JSONObject) routes.get(0); - JSONArray sections = (JSONArray) route.get("sections"); - JSONObject section = (JSONObject) sections.get(0); - JSONObject summary = (JSONObject) section.get("summary"); - travelTime = (long) summary.get("duration"); - distance = (long) summary.get("length"); - if (writeDetailedFiles) { - String filename = outputPath + "/" + tripId + ".json.gz"; - BufferedWriter bw = IOUtils.getBufferedWriter(filename); - bw.write(jsonObject.toString()); - bw.flush(); - bw.close(); - } - } - - in.close(); + result = readFromJson(in, tripId); } catch (MalformedURLException e) { log.error("URL is not working. Please check your API key", e); - } catch (IOException | ParseException e) { + result = Optional.empty(); + } catch (IOException e) { log.error("Cannot read the content on the URL properly. Please manually check the URL", e); + result = Optional.empty(); } - return new Tuple((double) travelTime, (double) distance); + return result.orElse(new Tuple<>(0.0, 0.0)); } + Optional> readFromJson(BufferedReader reader, String tripId) throws IOException { + JsonElement jsonElement = JsonParser.parseReader(reader); + if(!jsonElement.isJsonObject()){ + return Optional.empty(); + } + JsonObject jsonObject = jsonElement.getAsJsonObject(); + JsonArray routes = jsonObject.getAsJsonArray("routes"); + + if(routes.isEmpty()){ + return Optional.empty(); + } + + JsonObject route = routes.get(0).getAsJsonObject(); + JsonArray sections = route.get("sections").getAsJsonArray(); + JsonObject section = sections.get(0).getAsJsonObject(); + JsonObject summary = section.get("summary").getAsJsonObject(); + double travelTime = summary.get("duration").getAsDouble(); + double distance = summary.get("length").getAsDouble(); + if (writeDetailedFiles) { + String filename = outputPath + "/" + tripId + ".json.gz"; + BufferedWriter bw = IOUtils.getBufferedWriter(filename); + bw.write(jsonObject.toString()); + bw.flush(); + bw.close(); + } + reader.close(); + return Optional.of(new Tuple<>(travelTime, distance)); + } + } diff --git a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/filters/population/PersonIntersectAreaFilterTest.java b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/filters/population/PersonIntersectAreaFilterTest.java index 2c856118e92..aed33926f02 100644 --- a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/filters/population/PersonIntersectAreaFilterTest.java +++ b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/filters/population/PersonIntersectAreaFilterTest.java @@ -20,13 +20,13 @@ package org.matsim.contrib.analysis.filters.population; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashMap; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; @@ -51,11 +51,12 @@ */ public class PersonIntersectAreaFilterTest { - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension + private MatsimTestUtils utils = new MatsimTestUtils(); - @Test public void testFilter() throws Exception { + @Test + void testFilter() throws Exception { /* create a simple network where agents can drive from the lower left * to the upper right */ Network network = NetworkUtils.createNetwork(); @@ -113,25 +114,25 @@ public class PersonIntersectAreaFilterTest { aoi.clear(); aoi.put(link2.getId(), link2); filter = new PersonIntersectAreaFilter(null, aoi, network); - assertTrue("test route through aoi", filter.judge(person)); + assertTrue(filter.judge(person), "test route through aoi"); // test departure link aoi.clear(); aoi.put(link0.getId(), link0); filter = new PersonIntersectAreaFilter(null, aoi, network); - assertTrue("test departure link as aoi", filter.judge(person)); + assertTrue(filter.judge(person), "test departure link as aoi"); // test arrival link aoi.clear(); aoi.put(link5.getId(), link5); filter = new PersonIntersectAreaFilter(null, aoi, network); - assertTrue("test arrival link as aoi", filter.judge(person)); + assertTrue(filter.judge(person), "test arrival link as aoi"); // test route outside aoi aoi.clear(); aoi.put(link4.getId(), link4); filter = new PersonIntersectAreaFilter(null, aoi, network); - assertFalse("test route outside aoi", filter.judge(person)); + assertFalse(filter.judge(person), "test route outside aoi"); // prepare bee-line tests leg.setMode(TransportMode.walk); @@ -141,21 +142,21 @@ public class PersonIntersectAreaFilterTest { aoi.clear(); aoi.put(link2.getId(), link2); filter = new PersonIntersectAreaFilter(null, aoi, network); - assertFalse("test bee-line without alternative aoi", filter.judge(person)); + assertFalse(filter.judge(person), "test bee-line without alternative aoi"); // test bee-line with too small alternative aoi aoi.clear(); aoi.put(link2.getId(), link2); filter = new PersonIntersectAreaFilter(null, aoi, network); filter.setAlternativeAOI(new Coord((double) 100, (double) 0), 20.0); - assertFalse("test bee-line with too small alternative aoi", filter.judge(person)); + assertFalse(filter.judge(person), "test bee-line with too small alternative aoi"); // test bee-line with big enough alternative aoi aoi.clear(); aoi.put(link2.getId(), link2); filter = new PersonIntersectAreaFilter(null, aoi, network); filter.setAlternativeAOI(new Coord((double) 100, (double) 0), 80.0); - assertTrue("test bee-line with big enough alternative aoi", filter.judge(person)); + assertTrue(filter.judge(person), "test bee-line with big enough alternative aoi"); } diff --git a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/filters/population/RouteLinkFilterTest.java b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/filters/population/RouteLinkFilterTest.java index 01f4b00a334..c434dca8a24 100644 --- a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/filters/population/RouteLinkFilterTest.java +++ b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/filters/population/RouteLinkFilterTest.java @@ -20,11 +20,11 @@ package org.matsim.contrib.analysis.filters.population; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.TransportMode; @@ -50,11 +50,12 @@ public class RouteLinkFilterTest { - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension + private MatsimTestUtils utils = new MatsimTestUtils(); - @Test public void testRouteLinkFilter() { + @Test + void testRouteLinkFilter() { // used to set the default dtd-location utils.loadConfig((String)null); Population population = getTestPopulation(); diff --git a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/kai/KNAnalysisEventsHandlerTest.java b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/kai/KNAnalysisEventsHandlerTest.java index 8d6e64b29f9..67352fcabbf 100644 --- a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/kai/KNAnalysisEventsHandlerTest.java +++ b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/kai/KNAnalysisEventsHandlerTest.java @@ -22,12 +22,12 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; @@ -55,10 +55,10 @@ public class KNAnalysisEventsHandlerTest { - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension + public MatsimTestUtils utils = new MatsimTestUtils(); - // yy this test is probably not doing anything with respect to some of the newer statistics, such as money. kai, mar'14 + // yy this test is probably not doing anything with respect to some of the newer statistics, such as money. kai, mar'14 public static final String BASE_FILE_NAME = "stats_"; public final Id DEFAULT_PERSON_ID = Id.create(123, Person.class); @@ -68,7 +68,7 @@ public class KNAnalysisEventsHandlerTest { private Population population = null ; private Network network = null ; - @Before + @BeforeEach public void setUp() throws Exception { scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); @@ -101,15 +101,15 @@ public void setUp() throws Exception { this.network.addLink(link); } - @After + @AfterEach public void tearDown() throws Exception { this.population = null; this.network = null; } - @Test - @Ignore - public void testNoEvents() { + @Test + @Disabled + void testNoEvents() { KNAnalysisEventsHandler testee = new KNAnalysisEventsHandler(this.scenario); @@ -121,10 +121,10 @@ public void testNoEvents() { this.runTest(testee); } - @Test - @Ignore - public void testAveraging() { - // yy this test is probably not doing anything with respect to some of the newer statistics, such as money. kai, mar'14 + @Test + @Disabled + void testAveraging() { + // yy this test is probably not doing anything with respect to some of the newer statistics, such as money. kai, mar'14 KNAnalysisEventsHandler testee = new KNAnalysisEventsHandler(this.scenario); @@ -172,7 +172,7 @@ protected void runTest(KNAnalysisEventsHandler calcLegTimes) { LogManager.getLogger(this.getClass()).info( "comparing " + str ); final long expectedChecksum = CRCChecksum.getCRCFromFile(utils.getInputDirectory() + str); final long actualChecksum = CRCChecksum.getCRCFromFile(utils.getOutputDirectory() + str); - Assert.assertEquals("Output files differ.", expectedChecksum, actualChecksum); + Assertions.assertEquals(expectedChecksum, actualChecksum, "Output files differ."); } } diff --git a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/spatial/GridTest.java b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/spatial/GridTest.java index a3253515666..804de493d3a 100644 --- a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/spatial/GridTest.java +++ b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/spatial/GridTest.java @@ -1,17 +1,17 @@ package org.matsim.contrib.analysis.spatial; -import static org.junit.Assert.assertEquals; - import java.util.Collection; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; public class GridTest { - @Test - public void initializeSquareGrid() { + @Test + void initializeSquareGrid() { final String testValue = "Test-value"; Grid grid = new SquareGrid<>(2, () -> testValue, SpatialTestUtils.createRect(10, 10)); @@ -23,8 +23,8 @@ public void initializeSquareGrid() { values.forEach(value -> assertEquals(testValue, value.getValue())); } - @Test - public void initializeHexagonalGrid() { + @Test + void initializeHexagonalGrid() { final String testValue = "test-value"; Grid grid = new HexagonalGrid<>(2, () -> testValue, SpatialTestUtils.createRect(10, 10)); @@ -38,8 +38,8 @@ public void initializeHexagonalGrid() { values.forEach(value -> assertEquals(testValue, value.getValue())); } - @Test - public void getArea_squareGrid() { + @Test + void getArea_squareGrid() { final double horizontalDistance = 2; final double expected = 2 * 2; // area of square is d^2 @@ -49,8 +49,8 @@ public void getArea_squareGrid() { assertEquals(expected, grid.getCellArea(), 0.0001); } - @Test - public void getArea_HexagonalGrid() { + @Test + void getArea_HexagonalGrid() { // actually area of hexagon is r^2 * sqrt(3)/2 final double horizontalDistance = 2; @@ -65,8 +65,8 @@ public void getArea_HexagonalGrid() { assertEquals(expected5, grid5.getCellArea(), 0.0001); } - @Test - public void getValue_withExactCoord() { + @Test + void getValue_withExactCoord() { final String testValue = "initialValue"; final Coordinate expectedCoordinate = new Coordinate(2, 1+Math.sqrt(3)); @@ -77,8 +77,8 @@ public void getValue_withExactCoord() { assertEquals(expectedCoordinate, result.getCoordinate()); } - @Test - public void getValue_closeCoordinate() { + @Test + void getValue_closeCoordinate() { final String testValue = "initialValue"; Grid grid = new HexagonalGrid<>(2, () -> testValue, SpatialTestUtils.createRect(10, 10)); @@ -89,8 +89,8 @@ public void getValue_closeCoordinate() { assertEquals(new Coordinate(2, 1+Math.sqrt(3)), result.getCoordinate()); } - @Test - public void getValue_coordOutsideOfGrid() { + @Test + void getValue_coordOutsideOfGrid() { final String testValue = "initialValue"; Grid grid = new HexagonalGrid<>(2, () -> testValue, SpatialTestUtils.createRect(10, 10)); @@ -100,8 +100,8 @@ public void getValue_coordOutsideOfGrid() { assertEquals(new Coordinate(8, 1 + 5*Math.sqrt(3)), result.getCoordinate()); } - @Test - public void getValues() { + @Test + void getValues() { final String testValue = "initialValue"; Grid grid = new HexagonalGrid<>(2, () -> testValue, SpatialTestUtils.createRect(10, 10)); diff --git a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/spatial/SpatialInterpolationTest.java b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/spatial/SpatialInterpolationTest.java index 49e3f8e4a8a..1fe102d3534 100644 --- a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/spatial/SpatialInterpolationTest.java +++ b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/spatial/SpatialInterpolationTest.java @@ -1,15 +1,14 @@ package org.matsim.contrib.analysis.spatial; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; public class SpatialInterpolationTest { - @Test - public void calculateWeightFromLine() { + @Test + void calculateWeightFromLine() { final Coordinate from = new Coordinate(1, 1); final Coordinate to = new Coordinate(4, 5); @@ -22,33 +21,37 @@ public void calculateWeightFromLine() { assertEquals(0.0011109434390476694, weight, 0.001); } - @Test(expected = IllegalArgumentException.class) - public void calculateWeightFromLine_invalidSmoothingRadius() { + @Test + void calculateWeightFromLine_invalidSmoothingRadius() { + assertThrows(IllegalArgumentException.class, () -> { - final Coordinate from = new Coordinate(0, 1); - final Coordinate to = new Coordinate(10, 1); - final Coordinate cellCentroid = new Coordinate(5, 1); - final double smoothingRadius = 0; + final Coordinate from = new Coordinate(0, 1); + final Coordinate to = new Coordinate(10, 1); + final Coordinate cellCentroid = new Coordinate(5, 1); + final double smoothingRadius = 0; - double weight = SpatialInterpolation.calculateWeightFromLine(from, to, cellCentroid, smoothingRadius); + double weight = SpatialInterpolation.calculateWeightFromLine(from, to, cellCentroid, smoothingRadius); - fail("smoothing radius <= 0 should cause exception"); - } + fail("smoothing radius <= 0 should cause exception"); + }); + } - @Test(expected = IllegalArgumentException.class) - public void calculateWeightFromPoint_invalidSmoothingRadius() { + @Test + void calculateWeightFromPoint_invalidSmoothingRadius() { + assertThrows(IllegalArgumentException.class, () -> { - final Coordinate source = new Coordinate(10, 10); - final Coordinate centroid = new Coordinate(10, 10); - final double smoothingRadius = 0; + final Coordinate source = new Coordinate(10, 10); + final Coordinate centroid = new Coordinate(10, 10); + final double smoothingRadius = 0; - double weight = SpatialInterpolation.calculateWeightFromPoint(source, centroid, smoothingRadius); + double weight = SpatialInterpolation.calculateWeightFromPoint(source, centroid, smoothingRadius); - fail("smoothing radius <= 0 should cause exception"); - } + fail("smoothing radius <= 0 should cause exception"); + }); + } - @Test - public void calculateWeightFromPoint() { + @Test + void calculateWeightFromPoint() { final Coordinate point = new Coordinate(5, 5); final Coordinate cell = new Coordinate (9, 5); diff --git a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/time/TimeBinMapTest.java b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/time/TimeBinMapTest.java index a15b076f567..13e5e7f291c 100644 --- a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/time/TimeBinMapTest.java +++ b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/time/TimeBinMapTest.java @@ -1,15 +1,15 @@ package org.matsim.contrib.analysis.time; -import org.junit.Test; - import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; public class TimeBinMapTest { - @Test - public void getTimeBin() { + @Test + void getTimeBin() { TimeBinMap> map = new TimeBinMap<>(10); @@ -18,8 +18,8 @@ public void getTimeBin() { assertEquals(10, bin.getStartTime(), 0.001); } - @Test - public void getTimeBinWithStartTime() { + @Test + void getTimeBinWithStartTime() { TimeBinMap> map = new TimeBinMap<>(10, 20); @@ -28,18 +28,20 @@ public void getTimeBinWithStartTime() { assertEquals(20, bin.getStartTime(), 0.001); } - @Test(expected = IllegalArgumentException.class) - public void getTimeInvalidTime_exception() { + @Test + void getTimeInvalidTime_exception() { + assertThrows(IllegalArgumentException.class, () -> { - TimeBinMap> map = new TimeBinMap<>(10, 20); + TimeBinMap> map = new TimeBinMap<>(10, 20); - TimeBinMap.TimeBin> bin = map.getTimeBin(19); + TimeBinMap.TimeBin> bin = map.getTimeBin(19); - assertEquals(20, bin.getStartTime(), 0.001); - } + assertEquals(20, bin.getStartTime(), 0.001); + }); + } - @Test - public void getMultipleTimeBins() { + @Test + void getMultipleTimeBins() { TimeBinMap> map = new TimeBinMap<>(10); @@ -55,8 +57,8 @@ public void getMultipleTimeBins() { assertEquals(30, fourth.getStartTime(), 0.001); } - @Test - public void getEndOfLastTimeBucket() { + @Test + void getEndOfLastTimeBucket() { TimeBinMap> map = new TimeBinMap<>(10); @@ -68,8 +70,8 @@ public void getEndOfLastTimeBucket() { assertEquals(120, map.getEndTimeOfLastBin(), 0.0001); } - @Test - public void getAllTimeBins() { + @Test + void getAllTimeBins() { TimeBinMap> map = new TimeBinMap<>(10); @@ -81,8 +83,8 @@ public void getAllTimeBins() { assertEquals(4, map.getTimeBins().size()); } - @Test - public void timeBin_setEntry() { + @Test + void timeBin_setEntry() { final String testValue = "some-value"; @@ -97,7 +99,7 @@ public void timeBin_setEntry() { } @Test - public void timeBin_getValue() { + void timeBin_getValue() { final String testValue = "some-value"; diff --git a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidatorTest.java b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidatorTest.java new file mode 100644 index 00000000000..96b87268dc9 --- /dev/null +++ b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidatorTest.java @@ -0,0 +1,32 @@ +package org.matsim.contrib.analysis.vsp.traveltimedistance; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.matsim.core.utils.collections.Tuple; +import org.matsim.testcases.MatsimTestUtils; + +import java.io.*; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class GoogleMapRouteValidatorTest { + @RegisterExtension + private MatsimTestUtils utils = new MatsimTestUtils(); + + @Test + void testReadJson() throws IOException { + GoogleMapRouteValidator googleMapRouteValidator = getDummyValidator(); + BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(utils.getClassInputDirectory() + "route.json"))); + Optional> result = googleMapRouteValidator.readFromJson(reader); + assertTrue(result.isPresent()); + assertEquals(413, result.get().getFirst(), MatsimTestUtils.EPSILON); + assertEquals(2464, result.get().getSecond(), MatsimTestUtils.EPSILON); + } + + //All values with null filled are not necessary for this test + private GoogleMapRouteValidator getDummyValidator() { + return new GoogleMapRouteValidator(utils.getOutputDirectory(), null, null, null, null); + } +} diff --git a/contribs/analysis/src/test/java/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidatorTest.java b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidatorTest.java new file mode 100644 index 00000000000..bd95386c9a0 --- /dev/null +++ b/contribs/analysis/src/test/java/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidatorTest.java @@ -0,0 +1,39 @@ +package org.matsim.contrib.analysis.vsp.traveltimedistance; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.matsim.core.utils.collections.Tuple; +import org.matsim.testcases.MatsimTestUtils; + +import java.io.*; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +public class HereMapsRouteValidatorTest { + @RegisterExtension + private MatsimTestUtils utils = new MatsimTestUtils(); + + @Test + void testReadJson() throws IOException { + HereMapsRouteValidator hereMapsRouteValidator = getDummyValidator(false); + BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(utils.getClassInputDirectory() + "route.json"))); + Optional> result = hereMapsRouteValidator.readFromJson(reader, null); + assertTrue(result.isPresent()); + assertEquals(394, result.get().getFirst(), MatsimTestUtils.EPSILON); + assertEquals(2745, result.get().getSecond(), MatsimTestUtils.EPSILON); + } + + @Test + void testWriteFile() throws IOException { + HereMapsRouteValidator hereMapsRouteValidator = getDummyValidator(true); + BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(utils.getClassInputDirectory() + "route.json"))); + hereMapsRouteValidator.readFromJson(reader, "tripId"); + assertTrue(new File(utils.getOutputDirectory() + "tripId.json.gz").isFile()); + } + + //All values with null filled are not necessary for this test + private HereMapsRouteValidator getDummyValidator(boolean writeDetailedFiles) { + return new HereMapsRouteValidator(utils.getOutputDirectory(), null, null, null, null, writeDetailedFiles); + } +} diff --git a/contribs/analysis/src/test/java/org/matsim/contrib/travelsummary/events2traveldiaries/RunEventsToTravelDiariesIT.java b/contribs/analysis/src/test/java/org/matsim/contrib/travelsummary/events2traveldiaries/RunEventsToTravelDiariesIT.java index 2fd76b243bd..c3a4f24d7fd 100644 --- a/contribs/analysis/src/test/java/org/matsim/contrib/travelsummary/events2traveldiaries/RunEventsToTravelDiariesIT.java +++ b/contribs/analysis/src/test/java/org/matsim/contrib/travelsummary/events2traveldiaries/RunEventsToTravelDiariesIT.java @@ -18,20 +18,20 @@ * *********************************************************************** */ package org.matsim.contrib.travelsummary.events2traveldiaries; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.testcases.MatsimTestUtils; /** * @author nagel */ public class RunEventsToTravelDiariesIT { - @Rule - public MatsimTestUtils utils = new MatsimTestUtils(); + @RegisterExtension + public MatsimTestUtils utils = new MatsimTestUtils(); - @SuppressWarnings("static-method") - @Test - public final void test() { + @SuppressWarnings("static-method") + @Test + final void test() { String[] str = {"../../examples/scenarios/equil/config.xml", "../../examples/scenarios/equil/output_events.xml.gz", "_test", utils.getOutputDirectory()}; // This goes through the file system (nothing to do with resource paths etc.) diff --git a/contribs/analysis/test/input/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidatorTest/route.json b/contribs/analysis/test/input/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidatorTest/route.json new file mode 100644 index 00000000000..14e61b35177 --- /dev/null +++ b/contribs/analysis/test/input/org/matsim/contrib/analysis/vsp/traveltimedistance/GoogleMapRouteValidatorTest/route.json @@ -0,0 +1,30 @@ +{ + "destination_addresses": [ + "Kaiserin-Augusta-Allee 104, 10553 Berlin, Germany" + ], + "origin_addresses": [ + "B2 135, 10623 Berlin, Germany" + ], + "rows": [ + { + "elements": [ + { + "distance": { + "text": "2.5 km", + "value": 2464 + }, + "duration": { + "text": "7 mins", + "value": 400 + }, + "duration_in_traffic": { + "text": "7 mins", + "value": 413 + }, + "status": "OK" + } + ] + } + ], + "status": "OK" +} \ No newline at end of file diff --git a/contribs/analysis/test/input/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidatorTest/route.json b/contribs/analysis/test/input/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidatorTest/route.json new file mode 100644 index 00000000000..2dfdae5e032 --- /dev/null +++ b/contribs/analysis/test/input/org/matsim/contrib/analysis/vsp/traveltimedistance/HereMapsRouteValidatorTest/route.json @@ -0,0 +1,49 @@ +{ + "routes": [ + { + "id": "ed5396be-8f97-4c25-a373-a019da78b696", + "sections": [ + { + "id": "5f0ff311-d1d0-4a6a-a631-1c59fd5eaee4", + "type": "vehicle", + "departure": { + "time": "2023-12-11T10:00:00+01:00", + "place": { + "type": "place", + "location": { + "lat": 52.5127381, + "lng": 13.3268076 + }, + "originalLocation": { + "lat": 52.512638, + "lng": 13.326826 + } + } + }, + "arrival": { + "time": "2023-12-11T10:06:34+01:00", + "place": { + "type": "place", + "location": { + "lat": 52.5258281, + "lng": 13.3209817 + }, + "originalLocation": { + "lat": 52.5256489, + "lng": 13.320944 + } + } + }, + "summary": { + "duration": 394, + "length": 2745, + "baseDuration": 325 + }, + "transport": { + "mode": "car" + } + } + ] + } + ] +} \ No newline at end of file diff --git a/contribs/application/pom.xml b/contribs/application/pom.xml index 546d465e7d2..83422007fee 100644 --- a/contribs/application/pom.xml +++ b/contribs/application/pom.xml @@ -1,9 +1,10 @@ - + org.matsim contrib - 16.0-SNAPSHOT + 2025.0-SNAPSHOT 4.0.0 @@ -20,47 +21,56 @@ + + 1.12.0 + + tech.tablesaw tablesaw-core + + org.apache.avro + avro + ${avro.version} + org.matsim.contrib otfvis - 16.0-SNAPSHOT + 2025.0-SNAPSHOT org.matsim.contrib osm - 16.0-SNAPSHOT + 2025.0-SNAPSHOT org.matsim.contrib sumo - 16.0-SNAPSHOT + 2025.0-SNAPSHOT org.matsim.contrib analysis - 16.0-SNAPSHOT + 2025.0-SNAPSHOT org.matsim.contrib emissions - 16.0-SNAPSHOT + 2025.0-SNAPSHOT org.matsim.contrib noise - 16.0-SNAPSHOT + 2025.0-SNAPSHOT org.matsim.contrib freight - 16.0-SNAPSHOT + 2025.0-SNAPSHOT @@ -77,8 +87,9 @@ com.github.matsim-org gtfs2matsim - master-33809c4f0f-1 + 0bd5850fd6 + org.geotools * @@ -87,6 +98,18 @@ org.matsim * + + com.amazonaws + * + + + com.graphql-java + * + + + org.postgresql + * + @@ -94,7 +117,7 @@ info.picocli picocli - 4.7.5 + 4.7.6 it.unimi.dsi @@ -125,6 +148,35 @@ xercesImpl 2.12.2 + + org.matsim.contrib + dvrp + 2025.0-SNAPSHOT + compile + + + + + + + + org.apache.avro + avro-maven-plugin + ${avro.version} + + + generate-sources + + schema + + + ${project.basedir}/src/main/avro/ + ${project.basedir}/src/main/java/ + + + + + + - diff --git a/contribs/application/src/main/avro/network.avsc b/contribs/application/src/main/avro/network.avsc new file mode 100644 index 00000000000..fe257c6d8c6 --- /dev/null +++ b/contribs/application/src/main/avro/network.avsc @@ -0,0 +1,79 @@ +{ + "namespace": "org.matsim.application.avro", + "type": "record", + "name": "AvroNetwork", + "fields": [ + { + "name": "crs", + "type": "string", + "doc": "Coordinate reference system" + }, + { + "name": "nodeAttributes", + "type": { + "type": "array", + "items": "string" + } + }, + { + "name": "linkAttributes", + "type": { + "type": "array", + "items": "string" + } + }, + { + "type": { + "type": "array", + "items": "string" + }, + "name": "nodeId" + }, + { + "type": { + "type": "array", + "items": "float" + }, + "name": "nodeCoordinates" + }, + {"type": {"type": "array", "items": "string" }, "name": "linkId"}, + {"type": {"type": "array", "items": "int" }, "name": "from"}, + {"type": {"type": "array", "items": "int"}, "name": "to"}, + {"type": { "type": "array", "items": "string"}, "name": "modes"}, + { + "type": { + "type": "array", + "items": "float" + }, + "name": "length" + }, + { + "type": { + "type": "array", + "items": "float" + }, + "name": "freespeed" + }, + { + "type": { + "type": "array", + "items": "float" + }, + "name": "capacity" + }, + { + "type": { + "type": "array", + "items": "float" + }, + "name": "permlanes" + }, + { + "type": { + "type": "array", + "items": "int" + }, + "name": "allowedModes" + } + ] +} diff --git a/contribs/application/src/main/avro/xyt.avsc b/contribs/application/src/main/avro/xyt.avsc new file mode 100644 index 00000000000..0d56d538c99 --- /dev/null +++ b/contribs/application/src/main/avro/xyt.avsc @@ -0,0 +1,47 @@ +{ + "namespace": "org.matsim.application.avro", + "type": "record", + "name": "XYTData", + "fields": [ + { + "name": "crs", + "type": "string", + "doc": "Coordinate reference system" + }, + { + "name": "xCoords", + "doc": "List of x coordinates", + "type": { + "type": "array", + "items": "float" + } + }, + { + "name": "yCoords", + "doc": "List of y coordinates", + "type": { + "type": "array", + "items": "float" + } + }, + { + "name": "timestamps", + "doc": "List of timestamps in seconds", + "type": { + "type": "array", + "items": "int" + } + }, + { + "name": "data", + "doc": "XYT data for each dataset. The key is the name, the data is stored in one chunk of data.", + "type": { + "type": "map", + "values": { + "type": "array", + "items": "float" + } + } + } + ] +} \ No newline at end of file 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 89086cb00d3..0a13fbe9311 100644 --- a/contribs/application/src/main/java/org/matsim/application/ApplicationUtils.java +++ b/contribs/application/src/main/java/org/matsim/application/ApplicationUtils.java @@ -1,5 +1,9 @@ package org.matsim.application; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; @@ -7,11 +11,14 @@ import org.matsim.application.options.InputOptions; import org.matsim.application.options.OutputOptions; 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.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import picocli.CommandLine; +import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; @@ -21,20 +28,232 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; -import java.util.Optional; +import java.util.*; +import java.util.stream.Collectors; import java.util.stream.Stream; +import java.util.stream.StreamSupport; public class ApplicationUtils { private static final Logger log = LogManager.getLogger(ApplicationUtils.class); + /** + * This encoding indicates command line was used to start the jar. + */ + private static final String WIN_CLI_ENCODING = "cp850"; + private ApplicationUtils() { } + + /** + * Merge given arguments with custom ones. + * + * @param args given args, usually input from command line / main method + * @param defaultArgs default arguments that will be added to existing ones. + */ + public static String[] mergeArgs(String[] args, String... defaultArgs) { + String[] mergedArgs = new String[args.length + defaultArgs.length]; + System.arraycopy(args, 0, mergedArgs, 0, args.length); + System.arraycopy(defaultArgs, 0, mergedArgs, args.length, defaultArgs.length); + return mergedArgs; + } + + /** + * Utility method to check if a jar might be run from the desktop (using double-click). + */ + public static boolean isRunFromDesktop() { + + // check if gui was explicitly enabled + String env = System.getenv().getOrDefault("RUN_GUI", "undefined"); + if (env.equalsIgnoreCase("true") || env.equals("1")) + return true; + else if (env.equalsIgnoreCase("false") || env.equals("0")) + return false; + + String property = System.getProperty("RUN_GUI", "undefined"); + if (property.equalsIgnoreCase("true") || property.equals("1")) + return true; + else if (property.equalsIgnoreCase("false") || property.equals("0")) + return false; + + String macIdentifier = System.getenv().getOrDefault("__CFBundleIdentifier", "none"); + + if (macIdentifier.equals("com.apple.java.JarLauncher") || macIdentifier.equals("com.apple.JavaLauncher")) + return true; + + String os = System.getProperty("os.name"); + + if (os.toLowerCase().startsWith("windows")) { + + // presence of the prompt variable indicates that the jar was run from the command line + boolean hasPrompt = System.getenv().containsKey("PROMPT"); + + // this prompt is not set in PowerShell, so we need another check + if (hasPrompt) + return false; + + // stdout.encoding from CLI are usually cp850 + String encoding = System.getProperty("stdout.encoding", "none"); + String sunEncoding = System.getProperty("sun.stdout.encoding", "none"); + + if (encoding.equals(WIN_CLI_ENCODING) || sunEncoding.equals(WIN_CLI_ENCODING)) + return false; + + // Run from intelij, will not start the gui by default + if (System.getenv().containsKey("IDEA_INITIAL_DIRECTORY")) + return false; + // also file.encoding=UTF-8, seems to be set by default in IntelliJ + + // if no other cli indicators are present, we have to assume that the jar was run from the desktop + return true; + } + + return false; + + } + + /** + * Apply run configuration in yaml format. + */ + public static void applyConfigUpdate(Config config, Path yaml) { + + if (!Files.exists(yaml)) { + throw new IllegalArgumentException("Given config yaml does not exist: " + yaml); + } + + ObjectMapper mapper = new ObjectMapper(new YAMLFactory() + .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)); + + ConfigAliases aliases = new ConfigAliases(); + Deque emptyStack = new ArrayDeque<>(); + + try (BufferedReader reader = Files.newBufferedReader(yaml)) { + + JsonNode node = mapper.readTree(reader); + + Iterator> fields = node.fields(); + + while (fields.hasNext()) { + Map.Entry field = fields.next(); + String configGroupName = aliases.resolveAlias(field.getKey(), emptyStack); + ConfigGroup group = config.getModules().get(configGroupName); + if (group == null) { + group = new ConfigGroup(configGroupName); + config.addModule(group); + } + + applyNodeToConfigGroup(field.getValue(), group); + } + + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + } + + /** + * Sets the json config into + */ + private static void applyNodeToConfigGroup(JsonNode node, ConfigGroup group) { + + Iterator> fields = node.fields(); + + while (fields.hasNext()) { + Map.Entry field = fields.next(); + + if (isParameterSet(field.getValue())) { + + // store the current parameters sets, newly added sets are not merged with each other + List params = new ArrayList<>(group.getParameterSets(field.getKey())); + + for (JsonNode item : field.getValue()) { + + + // Special case of parameter sets that have only one entry + if (field.getValue().size() == 1 && params.size() == 1 && field.getValue().get(0).isObject()) { + + applyNodeToConfigGroup(field.getValue().get(0), params.get(0)); + + } else { + + applyNodeAsParameterSet(field.getKey(), item, group, params); + } + } + } else { + + if (field.getValue().isTextual()) + group.addParam(field.getKey(), field.getValue().textValue()); + else if (field.getValue().isArray()) { + // arrays are joined using "," + Stream stream = StreamSupport.stream(field.getValue().spliterator(), false); + String string = stream.map(n -> n.isTextual() ? n.textValue() : n.toString()).collect(Collectors.joining(",")); + group.addParam(field.getKey(), string); + } else + group.addParam(field.getKey(), field.getValue().toString()); + } + } + } + + /** + * Any array of complex object can be considered a config group. + */ + private static boolean isParameterSet(JsonNode node) { + + if (!node.isArray()) + return false; + + // any object can be assigned as parameter set + for (JsonNode el : node) { + if (!el.isObject()) + return false; + } + + return true; + } + + /** + * Handle possible update and creation of parameter sets within a config group. + */ + private static void applyNodeAsParameterSet(String groupName, JsonNode item, ConfigGroup group, List params) { + + Iterator> it = item.fields(); + + // There was at least one matching group + boolean matched = false; + + while (!params.isEmpty() && it.hasNext()) { + + Map.Entry attr = it.next(); + List candidates = params.stream() + .filter(p -> p.getParams().containsKey(attr.getKey())) + .filter(p -> p.getParams().get(attr.getKey()) + .equals(attr.getValue().isTextual() ? attr.getValue().textValue() : attr.getValue().toString())) + .toList(); + + if (candidates.isEmpty()) + break; + + matched = true; + params = candidates; + } + + if (params.size() > 1) { + throw new IllegalArgumentException("Ambiguous parameter set: " + item); + } else if (params.size() == 1 && matched) { + applyNodeToConfigGroup(item, params.get(0)); + } else { + ConfigGroup newGroup = group.createParameterSet(groupName); + group.addParameterSet(newGroup); + applyNodeToConfigGroup(item, newGroup); + } + } + /** - * Extends a context (usually config location) with an relative filename. + * Extends a context (usually config location) with a relative filename. * If the results is a local file, the path will be returned. Otherwise, it will be an url. * The results can be used as input for command line parameter or {@link IOUtils#resolveFileOrResource(String)}. + * * @return string with path or URL */ public static String resolve(URL context, String filename) { @@ -60,10 +279,11 @@ public static Path globFile(Path path, String pattern) { PathMatcher m = path.getFileSystem().getPathMatcher("glob:" + pattern); try { - return Files.list(path) - .filter(p -> m.matches(p.getFileName())) + try (Stream list = Files.list(path)) { + return list.filter(p -> m.matches(p.getFileName())) .findFirst() .orElseThrow(() -> new IllegalStateException("No " + pattern + " file found.")); + } } catch (IOException e) { throw new RuntimeException(e); } @@ -154,11 +374,19 @@ public static void checkCommand(Class command) { boolean input = false; boolean output = false; for (Field field : fields) { - if (field.getType().equals(InputOptions.class)) + if (field.getType().equals(InputOptions.class)) { input = true; + CommandLine.Mixin mixin = field.getAnnotation(CommandLine.Mixin.class); + if (mixin == null) + throw new IllegalArgumentException(String.format("The command %s has no @Mixin annotation for InputOptions %s.", command, field.getName())); + } - if (field.getType().equals(OutputOptions.class)) + if (field.getType().equals(OutputOptions.class)) { output = true; + CommandLine.Mixin mixin = field.getAnnotation(CommandLine.Mixin.class); + if (mixin == null) + throw new IllegalArgumentException(String.format("The command %s has no @Mixin annotation for OutputOptions %s.", command, field.getName())); + } } if (!input) { @@ -212,12 +440,17 @@ public static Path matchInput(String name, Path dir) { if (path.isPresent()) return path.get(); - // Match more general pattern at last - path = matchPattern( ".+\\.[a-zA-Z0-9]*_" + name + "\\..+", dir); + // Match more general pattern + path = matchPattern(".+\\.[a-zA-Z0-9\\-]*_" + name + "\\..+", dir); + if (path.isPresent()) + return path.get(); + + // Even more permissive pattern + path = matchPattern(".+[a-zA-Z0-9_.\\-]*(_|\\.)" + name + ".+", dir); if (path.isPresent()) return path.get(); - throw new IllegalArgumentException("Could not match input file: " + name); + throw new IllegalArgumentException("Could not match input file: %s (in %s)".formatted(name, dir)); } private static Optional matchSuffix(String suffix, Path dir) { diff --git a/contribs/application/src/main/java/org/matsim/application/CommandRunner.java b/contribs/application/src/main/java/org/matsim/application/CommandRunner.java index 56f4549b678..ea0af2e6dd2 100644 --- a/contribs/application/src/main/java/org/matsim/application/CommandRunner.java +++ b/contribs/application/src/main/java/org/matsim/application/CommandRunner.java @@ -108,7 +108,7 @@ private void runCommand(Class clazz, Path input) thr MATSimAppCommand command = clazz.getDeclaredConstructor().newInstance(); String[] args = this.args.get(clazz); args = ArrayUtils.addAll(args, createArgs(clazz, args, input)); - log.info("Running {} with arguments: {}", clazz, Arrays.toString(args)); + log.info("Running {} with arguments: {}", clazz, String.join(" ", args)); command.execute(args); } @@ -247,6 +247,22 @@ public Path getRequiredPath(Class command, String fi return buildPath(spec, command).resolve(file); } + /** + * Return the output of a command with a placeholder. + * @param file file name, which must contain a %s, which will be replaced by the placeholder + */ + public Path getRequiredPath(Class command, String file, String placeholder) { + CommandSpec spec = ApplicationUtils.getSpec(command); + if (!ArrayUtils.contains(spec.produces(), file)) + throw new IllegalArgumentException(String.format("Command %s does not declare output %s", command, file)); + if (!file.contains("%s")) + throw new IllegalArgumentException(String.format("File %s does not contain placeholder %%s", file)); + + file = String.format(file, placeholder); + + return buildPath(spec, command).resolve(file); + } + /** * Base path for the runner. */ @@ -279,8 +295,8 @@ public void add(Class command, String... args) { if (args.length != 0) { String[] existing = this.args.get(command); if (existing != null && existing.length > 0 && !Arrays.equals(existing, args)) { - throw new IllegalArgumentException(String.format("Command %s already registered with args %s, can not define different args as %s", - command.toString(), Arrays.toString(existing), Arrays.toString(args))); + throw new IllegalArgumentException(String.format("Command %s already registered with args %s, can not define different args as %s (name '%s').", + command.toString(), Arrays.toString(existing), Arrays.toString(args), name)); } } @@ -298,6 +314,22 @@ public void add(Class command, String... args) { } } + /** + * Insert args for an already existing command. If the command was not added, this does nothing. + */ + public void insertArgs(Class command, String... args) { + + if (!this.args.containsKey(command)) + return; + + String[] existing = this.args.get(command); + String[] newArgs = new String[existing.length + args.length]; + System.arraycopy(args, 0, newArgs, 0, args.length); + System.arraycopy(existing, 0, newArgs, args.length, existing.length); + + this.args.put(command, newArgs); + } + /** * Set specific shape file for certain command. */ 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 c1951c1b2a4..2425a0f1491 100644 --- a/contribs/application/src/main/java/org/matsim/application/MATSimApplication.java +++ b/contribs/application/src/main/java/org/matsim/application/MATSimApplication.java @@ -1,17 +1,10 @@ package org.matsim.application; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import com.google.common.collect.Lists; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; -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.ControllerConfigGroup; @@ -23,15 +16,12 @@ import picocli.CommandLine; import javax.annotation.Nullable; -import java.io.BufferedReader; import java.io.File; -import java.io.IOException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; -import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.concurrent.Callable; @@ -78,6 +68,8 @@ public abstract class MATSimApplication implements Callable, CommandLin private static final Logger log = LogManager.getLogger(MATSimApplication.class); + private static final String ARGS_DELIMITER = "§$"; + public static final String COLOR = "@|bold,fg(81) "; static final String DEFAULT_NAME = "MATSimApplication"; static final String HEADER = COLOR + @@ -161,7 +153,14 @@ public Integer call() throws Exception { // load config if not present yet. if (config == null) { - config = loadConfig(Objects.requireNonNull( configPath, "No default scenario location given" ).getAbsoluteFile().toString() ); + String path = Objects.requireNonNull( configPath, "No default scenario location given" ).getAbsoluteFile().toString(); + List customModules = getCustomModules(); + + final Config config1 = ConfigUtils.loadConfig(path, customModules.toArray(new ConfigGroup[0] ) ); + Config prepared = prepareConfig( config1 ); + + config = prepared != null ? prepared : config1; + // (The above lines of code come from inlining so maybe it happened there: I cannot see how prepared could be null but config1 not except if user code returns null which I would consider a bug. kai, aug'24) } else { Config tmp = prepareConfig(config); config = tmp != null ? tmp : config; @@ -170,7 +169,7 @@ public Integer call() throws Exception { Objects.requireNonNull(config); if (specs != null) - applySpecs(config, specs); + ApplicationUtils.applyConfigUpdate(config, specs); if (remainingArgs != null) { String[] args = remainingArgs.stream().map(s -> s.replace("-c:", "--config:")).toArray(String[]::new); @@ -210,99 +209,22 @@ public Integer call() throws Exception { } catch (Exception e) { log.error("Error running post-processing", e); } - } - } return 0; } - /** - * Apply given specs to config. - */ - private static void applySpecs(Config config, Path specs) { - - if (!Files.exists(specs)) { - throw new IllegalArgumentException("Desired run config does not exist:" + 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); - - Iterator> fields = node.fields(); - - while (fields.hasNext()) { - Map.Entry field = fields.next(); - String configGroupName = aliases.resolveAlias(field.getKey(), emptyStack); - ConfigGroup group = config.getModules().get(configGroupName); - if (group == null) { - log.warn("Config group not found: {}", configGroupName); - continue; - } - - applyNodeToConfigGroup(field.getValue(), group); - } - - } catch (IOException e) { - e.printStackTrace(); - } - + File getConfigPath() { + return configPath; } - /** - * Sets the json config into - */ - private static void applyNodeToConfigGroup(JsonNode node, ConfigGroup group) { - - Iterator> fields = node.fields(); - - while (fields.hasNext()) { - Map.Entry field = fields.next(); - - if (field.getValue().isArray()) { - - Collection params = group.getParameterSets(field.getKey()); - - // single node and entry merged directly - if (field.getValue().size() == 1 && params.size() == 1) { - applyNodeToConfigGroup(field.getValue().get(0), params.iterator().next()); - } else { - - for (JsonNode item : field.getValue()) { - - Map.Entry first = item.fields().next(); - Optional m = params.stream().filter(p -> p.getParams().get(first.getKey()).equals(first.getValue().textValue())).findFirst(); - if (m.isEmpty()) - throw new IllegalArgumentException("Could not find matching param by key" + first); - - applyNodeToConfigGroup(item, m.get()); - } - } - - } else { - - if (!field.getValue().isValueNode()) - throw new IllegalArgumentException("Received complex value type instead of primitive: " + field.getValue()); - - - if (field.getValue().isTextual()) - group.addParam(field.getKey(), field.getValue().textValue()); - else - group.addParam(field.getKey(), field.getValue().toString()); - } - } + @Nullable + String getDefaultScenario() { + return defaultScenario; } - /** * Custom module configs that will be added to the {@link Config} object. * @@ -391,15 +313,6 @@ protected final void addRunOption(Config config, String option) { addRunOption(config, option, ""); } - private Config loadConfig(String path) { - List customModules = getCustomModules(); - - final Config config = ConfigUtils.loadConfig(path, customModules.toArray(new ConfigGroup[0])); - Config prepared = prepareConfig(config); - - return prepared != null ? prepared : config; - } - @Override public String defaultValue(CommandLine.Model.ArgSpec argSpec) throws Exception { Object obj = argSpec.userObject(); @@ -429,6 +342,13 @@ public static void run(Class clazz, String... args) l.addAll(Arrays.asList(args)); args = l.toArray(new String[0]); + + // Pass stored args to the instance as well + if (System.getenv().containsKey("MATSIM_GUI_ARGS")) { + String[] guiArgs = System.getenv("MATSIM_GUI_ARGS").split(ARGS_DELIMITER); + if (guiArgs.length > 0) + args = ApplicationUtils.mergeArgs(args, guiArgs); + } } prepareArgs(args); @@ -451,6 +371,83 @@ public static void run(Class clazz, String... args) System.exit(code); } + /** + *

Convenience method to run a scenario from code or automatically with gui when desktop application is detected. + * This method may also be used to predefine some default arguments.

+ * + *

With respect to args it looks like arguments are treated in the following sequence (programmed in the run method): + *

    + *
  • ConfigUtils.loadConfig without args
  • + *
  • prepareConfig which is usually overwritten
  • + *
  • config options from some yaml file which can be provided as a command line option
  • + *
  • config options on command line
  • + *

+ * + *

defaultArgs could be used to provide defaults when calling this method here; they would go in addition to what is coming in from "upstream" which is typically the command line.

+ * + *

There are many execution paths that can be reached from this class, but a typical one for matsim-scenarios seems to be:

    + *
  • This method runs MATSimApplication.run( TheScenarioClass.class , args ).
  • + *
  • That run class will instantiate an instance of TheScenarioClass (*), then do some args consistenty checking, then call the piccoli execute method.
  • + *
  • The piccoli execute method will essentially call the "call" method of MATSimApplication.
  • + *
  • I think that in the described execution path, this.config in that call method will initially be null. (The ctor of MATSimApplication was called via reflection at (*); I think that it was called there without a config argument.)
  • + *
  • This call method then will do:
      + *
    • getCustomModules() (which is empty by default but can be overriden)
    • + *
    • ConfigUtils.loadConfig(...) _without_ passing on the args
    • + *
    • prepareConfig(...) (which is empty by default but is typically overridden, in this case in OpenBerlinScenario). In our case, this sets the typical scoring params and the typical replanning strategies. + *
    • next one can override the config from some yaml file provided as a commandline option + *
    • next args is parsed and set + *
    • then some standard CL options are detected and set + *
    • then createScenario(config) is called (which can be overwritten but is not) + *
    • then prepareScenario(scenario) is called (which can be overwritten but is not) + *
    • then a standard controler is created from scenario + *
    • then prepareControler is called which can be overwritten + *
    + *
+ *

+ * + * @param clazz class of the scenario to run + * @param args pass arguments from the main method + * @param defaultArgs predefined default arguments that will always be present + */ + public static void runWithDefaults(Class clazz, String[] args, String... defaultArgs) { + + if (ApplicationUtils.isRunFromDesktop() && args.length == 0) { + + System.setProperty("MATSIM_GUI_DESKTOP", "true"); + + if (defaultArgs.length > 0) { + String value = String.join(ARGS_DELIMITER, defaultArgs); + System.setProperty("MATSIM_GUI_ARGS", value); + } + + // args are empty when run from desktop and is not used + run(clazz, "gui"); + + } else { + // run if no other command is present + if (args.length > 0) { + // valid command is present + if (args[0].equals("run") || args[0].equals("prepare") || args[0].equals("analysis") || args[0].equals("gui") ){ + // If this is a run command, the default args can be applied + if (args[0].equals("run")) + args = ApplicationUtils.mergeArgs(args, defaultArgs); + + } else { + // Automatically add run command + String[] runArgs = ApplicationUtils.mergeArgs(new String[]{"run"}, defaultArgs); + args = ApplicationUtils.mergeArgs(runArgs, args); + } + + } else + // Automatically add run command + args = ApplicationUtils.mergeArgs(new String[]{"run"}, defaultArgs); + + log.info("Running {} with: {}", clazz.getSimpleName(), String.join(" ", args)); + + run(clazz, args); + } + } + /** * Calls an application class and forwards any exceptions. * @@ -512,7 +509,7 @@ public static Controler prepare(MATSimApplication app, Config config, String... config = tmp != null ? tmp : config; if (app.specs != null) { - applySpecs(config, app.specs); + ApplicationUtils.applyConfigUpdate(config, app.specs); } if (app.remainingArgs != null) { @@ -744,7 +741,7 @@ public Integer call() throws Exception { } /** - * Option to switch post processing behavour + * Option to switch post-processing behaviour */ public enum PostProcessOption { diff --git a/contribs/application/src/main/java/org/matsim/application/commands/RunScenario.java b/contribs/application/src/main/java/org/matsim/application/RunScenario.java similarity index 67% rename from contribs/application/src/main/java/org/matsim/application/commands/RunScenario.java rename to contribs/application/src/main/java/org/matsim/application/RunScenario.java index 3221069de95..460d5585ee5 100644 --- a/contribs/application/src/main/java/org/matsim/application/commands/RunScenario.java +++ b/contribs/application/src/main/java/org/matsim/application/RunScenario.java @@ -1,12 +1,11 @@ -package org.matsim.application.commands; +package org.matsim.application; -import org.matsim.application.MATSimApplication; import picocli.CommandLine; import java.util.concurrent.Callable; @CommandLine.Command(name = "run", description = "Run the scenario") -public class RunScenario implements Callable { +class RunScenario implements Callable { @CommandLine.ParentCommand private MATSimApplication app; diff --git a/contribs/application/src/main/java/org/matsim/application/commands/ShowGUI.java b/contribs/application/src/main/java/org/matsim/application/ShowGUI.java similarity index 51% rename from contribs/application/src/main/java/org/matsim/application/commands/ShowGUI.java rename to contribs/application/src/main/java/org/matsim/application/ShowGUI.java index 443f6a5cccb..6400262eb95 100644 --- a/contribs/application/src/main/java/org/matsim/application/commands/ShowGUI.java +++ b/contribs/application/src/main/java/org/matsim/application/ShowGUI.java @@ -1,14 +1,14 @@ -package org.matsim.application.commands; +package org.matsim.application; -import org.matsim.application.MATSimApplication; import org.matsim.run.gui.Gui; import picocli.CommandLine; +import java.io.File; import java.util.concurrent.Callable; import java.util.concurrent.Future; @CommandLine.Command(name = "gui", description = "Run the scenario through the MATSim GUI") -public class ShowGUI implements Callable { +class ShowGUI implements Callable { @CommandLine.ParentCommand private MATSimApplication parent; @@ -26,10 +26,27 @@ public Integer call() throws Exception { name = name.substring(MATSimApplication.COLOR.length(), name.length() - 4); } - Future f = Gui.show(name, parent.getClass()); + File configFile = null; + + // Try to load default config file + if (parent.getDefaultScenario() != null && new File(parent.getDefaultScenario()).exists()) + configFile = new File(parent.getDefaultScenario()); + + // override the default if present + if (parent.getConfigPath() != null && parent.getConfigPath().exists()) + configFile = parent.getConfigPath(); + + Future f = Gui.show(name, parent.getClass(), configFile); Gui gui = f.get(); + // Set the current working directory to be used in the gui, when run from the command line + // If the gui is run from desktop, the working directory is not overwritten + + // Assumption is that starting something from command line, the user expects that the working directory remains the same + if (!System.getProperty("MATSIM_GUI_DESKTOP", "false").equals("true")) + gui.setWorkingDirectory(new File("")); + while (gui.isShowing()) Thread.sleep(250); diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/LogFileAnalysis.java b/contribs/application/src/main/java/org/matsim/application/analysis/LogFileAnalysis.java index 36345aa2a79..5000c232482 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/LogFileAnalysis.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/LogFileAnalysis.java @@ -171,7 +171,6 @@ private void renderWarnings(BufferedWriter writer, Set warnings) throws } else { Map> grouped = warnings.stream().collect(Collectors.groupingBy(w -> w.module, Collectors.toList())); - writer.write(String.format("

Warnings found in %d module%s ❌

\n\n", grouped.size(), grouped.size() > 1 ? "s" : "")); for (Map.Entry> e : grouped.entrySet()) { @@ -188,9 +187,7 @@ private void renderWarnings(BufferedWriter writer, Set warnings) throws writer.write("""