From 1b79e20e24aa814a2d1dd2f708d99ee836fb0aa2 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Wed, 6 Mar 2024 19:08:58 +0100 Subject: [PATCH] add geopackage support to matsim gis --- .../accessibility/AccessibilityUtils.java | 4 +- .../contrib/accessibility/VoronoiExample.java | 16 +- .../accessibility/utils/GeoserverUpdater.java | 22 +- .../AccidentsNetworkModification.java | 100 +++--- .../analysis/christoph/TravelTimesWriter.java | 6 +- .../application/options/ShpOptions.java | 4 +- .../DetermineAverageTruckLoad.java | 4 +- .../dashboards/DrtAnalysisPostProcessing.java | 8 +- .../zonal/DrtZonalWaitTimesAnalyzer.java | 4 +- .../matsim/contrib/zone/io/ZoneShpReader.java | 4 +- .../matsim/contrib/zone/io/ZoneShpWriter.java | 2 +- .../minibus/schedule/CreatePStops.java | 68 ++-- ...JunctionApproachesAndBetweenJunctions.java | 130 +++---- .../parkingproxy/run/RunAreaAnalysis.java | 6 +- .../analysis/skims/CalculateSkimMatrices.java | 4 +- .../matsim/analysis/skims/MatricesToXY.java | 4 +- .../utils/WriteStationShapefile.java | 4 +- .../contrib/sumo/SumoNetworkConverter.java | 4 +- .../act2mode/ActivityToModeAnalysis.java | 30 +- .../networkAnalysis/NetworkAnalyzer.java | 330 +++++++++--------- .../utils/PtAccesShapeWriter.java | 38 +- .../utils/PtAccessMapShapeWriter.java | 40 +-- .../ptPaxVolumes/PtPaxVolumesAnalyzer.java | 20 +- .../TransitSchedule2Shp.java | 34 +- .../TransitVehicleVolumeAnalyzer.java | 4 +- .../vsp/analysis/utils/heatMap/HeatMap.java | 30 +- .../andreas/utils/ana/RouteAllModesAsCar.java | 50 +-- .../WorkHomeShapeCounter.java | 79 +++-- .../utils/pop/FilterPopulationByShape.java | 62 ++-- .../transitSchedule2shape/DaShapeWriter.java | 100 +++--- .../CORINELandCoverCoordsModifier.java | 10 +- .../corineLandcover/CorineLandCoverData.java | 4 +- .../CommuterGenerator.java | 36 +- .../DgLanduseReader.java | 24 +- .../DgPopulation2ShapeWriter.java | 20 +- .../demandde/pendlermatrix/GVPlanReader.java | 38 +- .../pendlermatrix/PendlerMatrixReader.java | 4 +- .../demandde/pendlermatrix/Verschmierer.java | 18 +- .../prognose2025/DemandMatrixReader.java | 4 +- .../cemdap/input/SynPopCreator.java | 130 +++---- .../cemdap/input/SynPopCreatorChildren.java | 34 +- .../cemdap/input/ZoneAndLOSGeneratorV2.java | 58 +-- .../CemdapOutput2MatsimPlansConverter.java | 36 +- matsim/pom.xml | 5 + .../pt/stop2stop/PtStop2StopAnalysis2Shp.java | 4 +- ...tworkTeleatlasAddManeuverRestrictions.java | 14 +- .../network/io/NetworkReaderTeleatlas.java | 26 +- ...hapeFileReader.java => GeoFileReader.java} | 70 ++-- ...hapeFileWriter.java => GeoFileWriter.java} | 36 +- .../matsim2esri/network/Links2ESRIShape.java | 4 +- .../matsim2esri/network/Nodes2ESRIShape.java | 8 +- .../plans/SelectedPlans2ESRIShape.java | 12 +- .../gis/shp2matsim/ShpGeometryUtils.java | 6 +- ...ReaderTest.java => GeoFileReaderTest.java} | 17 +- ...WriterTest.java => GeoFileWriterTest.java} | 82 ++++- .../network/Network2ESRIShapeTest.java | 12 +- .../plans/SelectedPlans2ESRIShapeTest.java | 6 +- .../GeoFileReaderTest/testGpkg/test+test.gpkg | Bin 0 -> 106496 bytes .../testShp}/test+test.dbf | Bin .../testShp}/test+test.prj | 0 .../testShp}/test+test.qpj | 0 .../testShp}/test+test.shp | Bin .../testShp}/test+test.shx | Bin .../testGeopackageFileWriter/test.gpkg | Bin 0 -> 106496 bytes .../testShapeFileWriter/test.dbf | Bin .../testShapeFileWriter/test.prj | 0 .../testShapeFileWriter/test.qix | Bin .../testShapeFileWriter/test.qpj | 0 .../testShapeFileWriter/test.shp | Bin .../testShapeFileWriter/test.shx | Bin 70 files changed, 1024 insertions(+), 905 deletions(-) rename matsim/src/main/java/org/matsim/core/utils/gis/{ShapeFileReader.java => GeoFileReader.java} (73%) rename matsim/src/main/java/org/matsim/core/utils/gis/{ShapeFileWriter.java => GeoFileWriter.java} (69%) rename matsim/src/test/java/org/matsim/core/utils/gis/{ShapeFileReaderTest.java => GeoFileReaderTest.java} (80%) rename matsim/src/test/java/org/matsim/core/utils/gis/{ShapeFileWriterTest.java => GeoFileWriterTest.java} (70%) create mode 100644 matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testGpkg/test+test.gpkg rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileReaderTest/testPlusInFilename => GeoFileReaderTest/testShp}/test+test.dbf (100%) rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileReaderTest/testPlusInFilename => GeoFileReaderTest/testShp}/test+test.prj (100%) rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileReaderTest/testPlusInFilename => GeoFileReaderTest/testShp}/test+test.qpj (100%) rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileReaderTest/testPlusInFilename => GeoFileReaderTest/testShp}/test+test.shp (100%) rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileReaderTest/testPlusInFilename => GeoFileReaderTest/testShp}/test+test.shx (100%) create mode 100644 matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testGeopackageFileWriter/test.gpkg rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileWriterTest => GeoFileWriterTest}/testShapeFileWriter/test.dbf (100%) rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileWriterTest => GeoFileWriterTest}/testShapeFileWriter/test.prj (100%) rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileWriterTest => GeoFileWriterTest}/testShapeFileWriter/test.qix (100%) rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileWriterTest => GeoFileWriterTest}/testShapeFileWriter/test.qpj (100%) rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileWriterTest => GeoFileWriterTest}/testShapeFileWriter/test.shp (100%) rename matsim/src/test/resources/test/input/org/matsim/core/utils/gis/{ShapeFileWriterTest => GeoFileWriterTest}/testShapeFileWriter/test.shx (100%) 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..43420197e8e 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 @@ -39,7 +39,7 @@ 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; @@ -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/VoronoiExample.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/VoronoiExample.java index 24544971132..382e13b68f7 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 @@ -28,17 +28,17 @@ 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.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; /** * @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/utils/GeoserverUpdater.java b/contribs/accessibility/src/main/java/org/matsim/contrib/accessibility/utils/GeoserverUpdater.java index 2f25f641a4c..a5799e30983 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 @@ -47,7 +47,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.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; @@ -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/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..7388ce718d5 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 @@ -44,7 +44,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.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; /** @@ -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/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..c1f1f9ea36e 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 @@ -41,7 +41,7 @@ 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; @@ -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/application/src/main/java/org/matsim/application/options/ShpOptions.java b/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java index da19b0439ef..ab40fd1f3c8 100644 --- a/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java +++ b/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java @@ -18,7 +18,7 @@ import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.geometry.transformations.IdentityTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.IOUtils; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; @@ -161,7 +161,7 @@ public List readFeatures() { if (shpCharset != null) ds.setCharset(shpCharset); - return ShapeFileReader.getSimpleFeatures(ds); + return GeoFileReader.getSimpleFeatures(ds); } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/contribs/application/src/main/java/org/matsim/application/prepare/freight/optimization/DetermineAverageTruckLoad.java b/contribs/application/src/main/java/org/matsim/application/prepare/freight/optimization/DetermineAverageTruckLoad.java index 8318bef7292..b89303a23bb 100644 --- a/contribs/application/src/main/java/org/matsim/application/prepare/freight/optimization/DetermineAverageTruckLoad.java +++ b/contribs/application/src/main/java/org/matsim/application/prepare/freight/optimization/DetermineAverageTruckLoad.java @@ -26,7 +26,7 @@ import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; import picocli.CommandLine; @@ -110,7 +110,7 @@ public Integer call() throws Exception { } // Read shape file // TODO this is acutally not needed. Just testing the functionality of reading shape file from URL. Delete afterwards!!! - List nutsFeatures = ShapeFileReader.getAllFeatures(URI.create(nutsPath).toURL()). + List nutsFeatures = GeoFileReader.getAllFeatures(URI.create(nutsPath).toURL()). stream().filter(f -> relevantNutsIds.contains(f.getAttribute("NUTS_ID").toString())). collect(Collectors.toList()); System.out.println("There are " + nutsFeatures.size() + " relevant NUTS regions"); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtAnalysisPostProcessing.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtAnalysisPostProcessing.java index 90eddf50abf..34ce02553dc 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtAnalysisPostProcessing.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtAnalysisPostProcessing.java @@ -30,8 +30,8 @@ import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; -import org.matsim.core.utils.gis.ShapeFileReader; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileReader; +import org.matsim.core.utils.gis.GeoFileWriter; import org.matsim.pt.transitSchedule.api.TransitScheduleReader; import org.matsim.pt.transitSchedule.api.TransitStopFacility; import org.opengis.feature.simple.SimpleFeature; @@ -207,9 +207,9 @@ public Integer call() throws Exception { if (areaFile != null) { // create copy of shp file so that it is accessible for sim wrapper - Collection allFeatures = ShapeFileReader.getAllFeatures(areaFile); + Collection allFeatures = GeoFileReader.getAllFeatures(areaFile); //do not convert coordinates! all MATSim output should be in the same CRS. if input was not in correct CRS, simulation would have crashed... - ShapeFileWriter.writeGeometries(allFeatures, output.getPath("serviceArea.shp").toString()); + GeoFileWriter.writeGeometries(allFeatures, output.getPath("serviceArea.shp").toString()); //needs to be a DoubleColumn because transposing later forces us to have the same column type for all (new) value columns tableSupplyKPI.addColumns(DoubleColumn.create("Number of areas", new Integer[]{allFeatures.size()})); } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/zonal/DrtZonalWaitTimesAnalyzer.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/zonal/DrtZonalWaitTimesAnalyzer.java index 40c885b5531..fd0fb66d20f 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/zonal/DrtZonalWaitTimesAnalyzer.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/zonal/DrtZonalWaitTimesAnalyzer.java @@ -49,7 +49,7 @@ import org.matsim.core.controler.listener.IterationEndsListener; import org.matsim.core.controler.listener.ShutdownListener; import org.matsim.core.utils.geometry.geotools.MGC; -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; @@ -162,7 +162,7 @@ public void notifyShutdown(ShutdownEvent event) { String fileName = event.getServices() .getControlerIO() .getOutputFilename("drt_waitStats" + "_" + drtCfg.getMode() + "_zonal.shp"); - ShapeFileWriter.writeGeometries(features, fileName); + GeoFileWriter.writeGeometries(features, fileName); } private Collection convertGeometriesToSimpleFeatures(String targetCoordinateSystem) { diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/zone/io/ZoneShpReader.java b/contribs/dvrp/src/main/java/org/matsim/contrib/zone/io/ZoneShpReader.java index 9913f890326..d47dac4c588 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/zone/io/ZoneShpReader.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/zone/io/ZoneShpReader.java @@ -26,7 +26,7 @@ import org.locationtech.jts.geom.MultiPolygon; import org.matsim.api.core.v01.Id; import org.matsim.contrib.zone.Zone; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; public class ZoneShpReader { @@ -41,7 +41,7 @@ public void readZones(URL url) { } public void readZones(URL url, String idHeader) { - Collection features = ShapeFileReader.getAllFeatures(url); + Collection features = GeoFileReader.getAllFeatures(url); if (features.size() != zones.size()) { throw new RuntimeException("Features#: " + features.size() + "; zones#: " + zones.size()); } diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/zone/io/ZoneShpWriter.java b/contribs/dvrp/src/main/java/org/matsim/contrib/zone/io/ZoneShpWriter.java index 1e3fde7b279..ba5bb104c9d 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/zone/io/ZoneShpWriter.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/zone/io/ZoneShpWriter.java @@ -51,6 +51,6 @@ public void write(String shpFile) { features.add(factory.createPolygon(z.getMultiPolygon(), new Object[] { id }, id)); } - ShapeFileWriter.writeGeometries(features, shpFile); + GeoFileWriter.writeGeometries(features, shpFile); } } diff --git a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/schedule/CreatePStops.java b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/schedule/CreatePStops.java index a9838bc4e12..52c5a6fe36d 100644 --- a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/schedule/CreatePStops.java +++ b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/schedule/CreatePStops.java @@ -44,7 +44,7 @@ import org.matsim.contrib.minibus.PConfigGroup; import org.matsim.core.network.algorithms.NetworkCalcTopoType; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.IOUtils; import org.matsim.pt.transitSchedule.TransitScheduleFactoryImpl; import org.matsim.pt.transitSchedule.api.TransitSchedule; @@ -53,14 +53,14 @@ /** * Create one TransitStopFacility for each car mode link of the network - * + * * @author aneumann, droeder * */ public final class CreatePStops{ - + private final static Logger log = LogManager.getLogger(CreatePStops.class); - + private final Network net; private final PConfigGroup pConfigGroup; private TransitSchedule transitSchedule; @@ -74,7 +74,7 @@ public final class CreatePStops{ private List topoTypesForStops = null; private NetworkCalcTopoType networkCalcTopoType; - + public static TransitSchedule createPStops(Network network, PConfigGroup pConfigGroup){ return createPStops(network, pConfigGroup, null); } @@ -84,14 +84,14 @@ public static TransitSchedule createPStops(Network network, PConfigGroup pConfig cS.run(); return cS.getTransitSchedule(); } - + /** * Creates PStops in two ways. First, if a serviceAreaFile is defined in the config and this file exists, the file is used. * Second, the (default) min/max-x/y-values are used. - * + * * Following FileTypes are supported: *
    - *
  • Shapefiles with polygons. If one ore more attributes are defined, the last one is parsed + *
  • Shapefiles with polygons. If one ore more attributes are defined, the last one is parsed * to Boolean and used to get include- and exclude-areas.
  • *
  • Textfile, containing a List of x/y-pairs per row, divided by semicolon. The first and the last coordinate should be equal * to get a closed and well defined Geometry.
  • @@ -104,13 +104,13 @@ private CreatePStops(Network net, PConfigGroup pConfigGroup, TransitSchedule rea this.net = net; this.pConfigGroup = pConfigGroup; this.factory = new GeometryFactory(); - + this.linkId2StopFacilityMap = new LinkedHashMap<>(); - + Set> stopsWithoutLinkIds = new TreeSet<>(); int warnCounter = 10; - + if (realTransitSchedule != null) { for (TransitStopFacility stopFacility : realTransitSchedule.getFacilities().values()) { if (stopFacility.getLinkId() != null) { @@ -131,7 +131,7 @@ private CreatePStops(Network net, PConfigGroup pConfigGroup, TransitSchedule rea } } } - + this.exclude = this.factory.buildGeometry(new ArrayList()); if(!new File(pConfigGroup.getServiceAreaFile()).exists()){ log.warn("file " + this.pConfigGroup.getServiceAreaFile() + " not found. Falling back to min/max serviceArea parameters."); @@ -140,7 +140,7 @@ private CreatePStops(Network net, PConfigGroup pConfigGroup, TransitSchedule rea log.warn("using " + this.pConfigGroup.getServiceAreaFile() + " for servicearea. x/y-values defined in the config are not used."); createServiceArea(pConfigGroup.getServiceAreaFile()); } - + if (stopsWithoutLinkIds.size() > 0) { log.warn("There are " + stopsWithoutLinkIds.size() + " stop facilities without a link id, namely: " + stopsWithoutLinkIds.toString()); } @@ -184,7 +184,7 @@ private void createServiceArea(String serviceAreaFile) { * @param serviceAreaFile */ private void createServiceAreaTxt(String serviceAreaFile) { - + List lines = new ArrayList<>(); String line; try { @@ -202,15 +202,15 @@ private void createServiceAreaTxt(String serviceAreaFile) { } catch (IOException e) { e.printStackTrace(); } - + if(lines.size() < 3){ log.warn("an area needs at least 3 points, to be defined. Falling back to simple (default) x/y-values..."); this.createServiceArea(pConfigGroup.getMinX(), pConfigGroup.getMaxX(), pConfigGroup.getMinY(), pConfigGroup.getMaxY()); - return; + return; } - + Coordinate[] c = new Coordinate[lines.size() + 1]; - + double x,y; for(int i = 0; i < lines.size(); i++){ x = Double.parseDouble(lines.get(i).split(";")[0]); @@ -226,10 +226,10 @@ private void createServiceAreaTxt(String serviceAreaFile) { * @param serviceAreaFile */ private void createServiceAreaShp(String serviceAreaFile) { - Collection features = new ShapeFileReader().readFileAndInitialize(serviceAreaFile); + Collection features = new GeoFileReader().readFileAndInitialize(serviceAreaFile); Collection include = new ArrayList<>(); Collection exclude = new ArrayList<>(); - + for(SimpleFeature f: features){ boolean incl = true; Geometry g = null; @@ -240,7 +240,7 @@ private void createServiceAreaShp(String serviceAreaFile) { g = (Geometry) o; } // TODO use a better way to get the attributes, maybe directly per index. - // Now the last attribute is used per default... + // Now the last attribute is used per default... else if (o instanceof String){ incl = Boolean.parseBoolean((String) o); } @@ -253,46 +253,46 @@ else if (o instanceof String){ } } } - this.include = this.factory.createGeometryCollection( + this.include = this.factory.createGeometryCollection( include.toArray(new Geometry[include.size()])).buffer(0); - this.exclude = this.factory.createGeometryCollection( + this.exclude = this.factory.createGeometryCollection( exclude.toArray(new Geometry[exclude.size()])).buffer(0); } private void run(){ this.transitSchedule = new TransitScheduleFactoryImpl().createTransitSchedule(); int stopsAdded = 0; - + for (Link link : this.net.getLinks().values()) { if(link.getAllowedModes().contains(TransportMode.car)){ stopsAdded += addStopOnLink(link); } } - + log.info("Added " + stopsAdded + " additional stops for paratransit services"); } - + private int addStopOnLink(Link link) { if(link == null){ return 0; } - + if(!linkToNodeInServiceArea(link)){ return 0; } - + if (linkHasAlreadyAFormalPTStopFromTheGivenSchedule(link)) { return 0; } - + if(!topoTypeAllowed(link)){ return 0; } - + if (link.getFreespeed() >= this.pConfigGroup.getSpeedLimitForStops()) { return 0; } - + if (link.getCapacity() < this.pConfigGroup.getMinCapacityForStops()) { return 0; } @@ -301,12 +301,12 @@ private int addStopOnLink(Link link) { log.warn("Link " + link.getId() + " has already a stop. This should not happen. Check code."); return 0; } - + Id stopId = Id.create(this.pConfigGroup.getPIdentifier() + link.getId(), TransitStopFacility.class); TransitStopFacility stop = this.transitSchedule.getFactory().createTransitStopFacility(stopId, link.getToNode().getCoord(), false); stop.setLinkId(link.getId()); this.transitSchedule.addStopFacility(stop); - return 1; + return 1; } private boolean topoTypeAllowed(Link link) { @@ -316,7 +316,7 @@ private boolean topoTypeAllowed(Link link) { } Integer topoType = this.networkCalcTopoType.getTopoType(link.getToNode()); return this.topoTypesForStops.contains(topoType); - } + } private boolean linkToNodeInServiceArea(Link link) { Point p = factory.createPoint(MGC.coord2Coordinate(link.getToNode().getCoord())); diff --git a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/schedule/CreatePStopsOnJunctionApproachesAndBetweenJunctions.java b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/schedule/CreatePStopsOnJunctionApproachesAndBetweenJunctions.java index c8f6676e835..f2303896615 100644 --- a/contribs/minibus/src/main/java/org/matsim/contrib/minibus/schedule/CreatePStopsOnJunctionApproachesAndBetweenJunctions.java +++ b/contribs/minibus/src/main/java/org/matsim/contrib/minibus/schedule/CreatePStopsOnJunctionApproachesAndBetweenJunctions.java @@ -55,7 +55,7 @@ import org.matsim.core.network.filter.NetworkFilterManager; import org.matsim.core.network.filter.NetworkLinkFilter; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.IOUtils; import org.matsim.pt.transitSchedule.TransitScheduleFactoryImpl; import org.matsim.pt.transitSchedule.api.TransitSchedule; @@ -64,14 +64,14 @@ /** * Create one TransitStopFacility for each car mode link of the network - * + * * @author aneumann, droeder, gleich * */ public final class CreatePStopsOnJunctionApproachesAndBetweenJunctions{ - + private final static Logger log = LogManager.getLogger(CreatePStopsOnJunctionApproachesAndBetweenJunctions.class); - + private final Network net; private final Network intersectionSimplifiedRoadNetwork; private final PConfigGroup pConfigGroup; @@ -89,7 +89,7 @@ public final class CreatePStopsOnJunctionApproachesAndBetweenJunctions{ private final double stopDistance; private NetworkCalcTopoType networkCalcTopoType; - + public static TransitSchedule createPStops(Network network, PConfigGroup pConfigGroup, NetworkConfigGroup networkConfigGroup) { return createPStops(network, pConfigGroup, null, networkConfigGroup); } @@ -99,14 +99,14 @@ public static TransitSchedule createPStops(Network network, PConfigGroup pConfig cS.run(); return cS.getTransitSchedule(); } - + /** * Creates PStops in two ways. First, if a serviceAreaFile is defined in the config and this file exists, the file is used. * Second, the (default) min/max-x/y-values are used. - * + * * Following FileTypes are supported: *
      - *
    • Shapefiles with polygons. If one ore more attributes are defined, the last one is parsed + *
    • Shapefiles with polygons. If one ore more attributes are defined, the last one is parsed * to Boolean and used to get include- and exclude-areas.
    • *
    • Textfile, containing a List of x/y-pairs per row, divided by semicolon. The first and the last coordinate should be equal * to get a closed and well defined Geometry.
    • @@ -120,13 +120,13 @@ private CreatePStopsOnJunctionApproachesAndBetweenJunctions(Network net, PConfig this.pConfigGroup = pConfigGroup; this.networkConfigGroup = networkConfigGroup; this.factory = new GeometryFactory(); - + this.linkId2StopFacilityMap = new LinkedHashMap<>(); - + Set> stopsWithoutLinkIds = new TreeSet<>(); int warnCounter = 10; - + if (realTransitSchedule != null) { for (TransitStopFacility stopFacility : realTransitSchedule.getFacilities().values()) { if (stopFacility.getLinkId() != null) { @@ -147,7 +147,7 @@ private CreatePStopsOnJunctionApproachesAndBetweenJunctions(Network net, PConfig } } } - + this.exclude = this.factory.buildGeometry(new ArrayList()); if(!new File(pConfigGroup.getServiceAreaFile()).exists()){ log.warn("file " + this.pConfigGroup.getServiceAreaFile() + " not found. Falling back to min/max serviceArea parameters."); @@ -156,14 +156,14 @@ private CreatePStopsOnJunctionApproachesAndBetweenJunctions(Network net, PConfig log.warn("using " + this.pConfigGroup.getServiceAreaFile() + " for servicearea. x/y-values defined in the config are not used."); createServiceArea(pConfigGroup.getServiceAreaFile()); } - + if (stopsWithoutLinkIds.size() > 0) { log.warn("There are " + stopsWithoutLinkIds.size() + " stop facilities without a link id, namely: " + stopsWithoutLinkIds.toString()); } this.topoTypesForStops = this.pConfigGroup.getTopoTypesForStops(); this.networkCalcTopoType = new NetworkCalcTopoType(); this.networkCalcTopoType.run(net); - + // parse StopLocationSelectorParameter from config String[] stopLocationSelectorParameter = pConfigGroup.getStopLocationSelectorParameter().split(","); if (stopLocationSelectorParameter.length != 3) { @@ -178,7 +178,7 @@ private CreatePStopsOnJunctionApproachesAndBetweenJunctions(Network net, PConfig } else { stopDistance = Double.parseDouble(stopLocationSelectorParameter[2]); } - + intersectionSimplifiedRoadNetwork = generateIntersectionSimplifiedNetwork(pmin, epsilon); } @@ -216,7 +216,7 @@ private void createServiceArea(String serviceAreaFile) { * @param serviceAreaFile */ private void createServiceAreaTxt(String serviceAreaFile) { - + List lines = new ArrayList<>(); String line; try { @@ -234,15 +234,15 @@ private void createServiceAreaTxt(String serviceAreaFile) { } catch (IOException e) { e.printStackTrace(); } - + if(lines.size() < 3){ log.warn("an area needs at least 3 points, to be defined. Falling back to simple (default) x/y-values..."); this.createServiceArea(pConfigGroup.getMinX(), pConfigGroup.getMaxX(), pConfigGroup.getMinY(), pConfigGroup.getMaxY()); - return; + return; } - + Coordinate[] c = new Coordinate[lines.size() + 1]; - + double x,y; for(int i = 0; i < lines.size(); i++){ x = Double.parseDouble(lines.get(i).split(";")[0]); @@ -258,10 +258,10 @@ private void createServiceAreaTxt(String serviceAreaFile) { * @param serviceAreaFile */ private void createServiceAreaShp(String serviceAreaFile) { - Collection features = new ShapeFileReader().readFileAndInitialize(serviceAreaFile); + Collection features = new GeoFileReader().readFileAndInitialize(serviceAreaFile); Collection include = new ArrayList<>(); Collection exclude = new ArrayList<>(); - + for(SimpleFeature f: features){ boolean incl = true; Geometry g = null; @@ -272,7 +272,7 @@ private void createServiceAreaShp(String serviceAreaFile) { g = (Geometry) o; } // TODO use a better way to get the attributes, maybe directly per index. - // Now the last attribute is used per default... + // Now the last attribute is used per default... else if (o instanceof String){ incl = Boolean.parseBoolean((String) o); } @@ -285,18 +285,18 @@ else if (o instanceof String){ } } } - this.include = this.factory.createGeometryCollection( + this.include = this.factory.createGeometryCollection( include.toArray(new Geometry[include.size()])).buffer(0); - this.exclude = this.factory.createGeometryCollection( + this.exclude = this.factory.createGeometryCollection( exclude.toArray(new Geometry[exclude.size()])).buffer(0); } - + /* Generate a simplified network to determine stop locations (the simplified network will not be used in simulation) */ private Network generateIntersectionSimplifiedNetwork(double pmin, int epsilon) { // Extract road network NetworkFilterManager nfmCar = new NetworkFilterManager(net, networkConfigGroup); nfmCar.addLinkFilter(new NetworkLinkFilter() { - + @Override public boolean judgeLink(Link l) { if (l.getAllowedModes().contains("car")) return true; @@ -304,11 +304,11 @@ public boolean judgeLink(Link l) { } }); Network roadNetwork = nfmCar.applyFilters(); - + // Remove low capacity links NetworkFilterManager nfm = new NetworkFilterManager(roadNetwork, networkConfigGroup); nfm.addLinkFilter(new NetworkLinkFilter() { - + @Override public boolean judgeLink(Link l) { if (l.getCapacity() >= pConfigGroup.getMinCapacityForStops()) return true; @@ -317,58 +317,58 @@ public boolean judgeLink(Link l) { }); Network newRoadNetwork = nfm.applyFilters(); new NetworkCleaner().run(newRoadNetwork); - + // Run Johan's intersection clustering algorithm IntersectionSimplifier ns = new IntersectionSimplifier(pmin, epsilon); Network newClusteredIntersectionsRoadNetwork = ns.simplify(newRoadNetwork); new NetworkCleaner().run(newClusteredIntersectionsRoadNetwork); - + // intersection clustering leaves some duplicate links (same start and end node), merge them NetworkMergeDoubleLinks mergeDoubleLinks = new NetworkMergeDoubleLinks(MergeType.MAXIMUM, LogInfoLevel.NOINFO); mergeDoubleLinks.run(newClusteredIntersectionsRoadNetwork); - + // Merge all links between two junctions NetworkSimplifier simplifier = new NetworkSimplifier(); // Merge links with different attributes, because we will not use the output network for simulation simplifier.setMergeLinkStats(true); simplifier.run(newClusteredIntersectionsRoadNetwork); new NetworkCleaner().run(newClusteredIntersectionsRoadNetwork); - + return(newClusteredIntersectionsRoadNetwork); } private void run(){ this.transitSchedule = new TransitScheduleFactoryImpl().createTransitSchedule(); int stopsAdded = 0; - + /* handle all (merged) links between junction */ for (Link link : this.intersectionSimplifiedRoadNetwork.getLinks().values()) { if(link.getAllowedModes().contains(TransportMode.car)){ stopsAdded += addStopForSimplifiedNetworkLink(link); } } - + log.info("Added " + stopsAdded + " additional stops for paratransit services"); } - + private int addStopForSimplifiedNetworkLink(Link simplifiedNetworkLink) { int numberOfStopsCreated = 0; String[] originalIdsMergedLink = simplifiedNetworkLink.getId().toString().split("-"); /* Bus stops should be placed on approaches to road junctions, and not inside junction - * areas. - * The Intersection simplifier creates a network where most junction nodes are merged into + * areas. + * The Intersection simplifier creates a network where most junction nodes are merged into * one node per junction. By merging two neighbouring nodes, all links in between are removed. * So, initially no links are modified, but most links located inside a junction area are - * removed. Than the NetworkSimplifier merges short links between intersections, thereby + * removed. Than the NetworkSimplifier merges short links between intersections, thereby * creating a network where between two junctions there is at most one link per direction. * Given that simplified network the corresponding stop locations are looked up on the * original network using the link ids remaining in the simplified network. - * + * * First add stops at links approaching junction areas: - * Start from last part of the merged link and move forward until the first intersection + * Start from last part of the merged link and move forward until the first intersection * (>=2 outlinks) is reached. This should be in most cases the begin of the junction area. * - * It could be that the original network already had "-" in link ids, + * It could be that the original network already had "-" in link ids, * so the link would not be found here. Add previous id parts of the merged link. * Go from the last link id backwards, because we want to find the last link. */ @@ -384,33 +384,33 @@ private int addStopForSimplifiedNetworkLink(Link simplifiedNetworkLink) { reappendedlinkIds = originalIdsMergedLink[indexOfNextLinkIdToBeAppended] + "-" + reappendedlinkIds; lastPartOfMergedLink = net.getLinks().get(Id.createLinkId(reappendedlinkIds)); } - + /* Get node ids of all nodes merged into the clustered node where the merged link ends */ Set> originalNodeIdsBeforeClustering = new HashSet<>(); String[] clusteredNodeIdSplit = simplifiedNetworkLink.getToNode().getId().toString().split("-"); for (String originalNodeId : clusteredNodeIdSplit) { originalNodeIdsBeforeClustering.add(Id.createNodeId(originalNodeId)); } - - while (lastPartOfMergedLink.getToNode().getOutLinks().size() <= 1 && + + while (lastPartOfMergedLink.getToNode().getOutLinks().size() <= 1 && ! originalNodeIdsBeforeClustering.contains(lastPartOfMergedLink.getToNode().getId())) { lastPartOfMergedLink = lastPartOfMergedLink.getToNode().getOutLinks().values().iterator().next(); } - + numberOfStopsCreated += addStopOnLink(lastPartOfMergedLink); - + /* Go backward from junction approach and add infill stops to create a proper bus stop spacing between junctions. */ double distanceFromLastStop = lastPartOfMergedLink.getLength(); if (numberOfStopsCreated == 0) { - /* No stop was created on link approaching the junction (due to link characteristics excluded + /* No stop was created on link approaching the junction (due to link characteristics excluded in pConfigGroup, see {@link addStopOnLink(Link link)}), so make the algorithm add one on the next suitable link */ distanceFromLastStop = stopDistance; } - + Link currentLink = lastPartOfMergedLink; reappendedlinkIds = ""; - + /* Stop if the previous junction area is reached */ while (indexOfNextLinkIdToBeAppended > 0) { indexOfNextLinkIdToBeAppended--; @@ -418,9 +418,9 @@ private int addStopForSimplifiedNetworkLink(Link simplifiedNetworkLink) { reappendedlinkIds = originalIdsMergedLink[indexOfNextLinkIdToBeAppended]; } else { reappendedlinkIds = originalIdsMergedLink[indexOfNextLinkIdToBeAppended] + "-" + reappendedlinkIds; - } + } Link tryLinkId = net.getLinks().get(Id.createLinkId(reappendedlinkIds)); - + if (tryLinkId == null) { /* Next backward link could not be found, because it's id already contains "-", e.g. because */ continue; @@ -428,11 +428,11 @@ private int addStopForSimplifiedNetworkLink(Link simplifiedNetworkLink) { distanceFromLastStop += currentLink.getLength(); currentLink = tryLinkId; reappendedlinkIds = ""; - + if (distanceFromLastStop >= stopDistance) { /* Try to add a new stop on current link */ int stopCreated = addStopOnLink(currentLink); - + // TODO: Add check of distance to next junction further backward if (stopCreated > 0) { /* If stop was added, reset distanceFromLastStop */ @@ -442,31 +442,31 @@ private int addStopForSimplifiedNetworkLink(Link simplifiedNetworkLink) { } } } - + return numberOfStopsCreated; } - + private int addStopOnLink(Link link) { if(link == null){ return 0; } - + if(!linkToNodeInServiceArea(link)){ return 0; } - + if (linkHasAlreadyAFormalPTStopFromTheGivenSchedule(link)) { return 0; } - + if(!topoTypeAllowed(link)){ return 0; } - + if (link.getFreespeed() >= this.pConfigGroup.getSpeedLimitForStops()) { return 0; } - + if (link.getCapacity() < this.pConfigGroup.getMinCapacityForStops()) { return 0; } @@ -475,17 +475,17 @@ private int addStopOnLink(Link link) { log.warn("Link " + link.getId() + " has already a stop in the given (non-paratransit) TransitSchedule. This should not happen. Check code."); return 0; } - + if (this.transitSchedule.getFacilities().get(Id.create(pConfigGroup.getPIdentifier() + link.getId().toString(), TransitStopFacility.class)) != null) { log.warn("Link " + link.getId() + " has already a stop. This should not happen. Check code."); return 0; } - + Id stopId = Id.create(this.pConfigGroup.getPIdentifier() + link.getId(), TransitStopFacility.class); TransitStopFacility stop = this.transitSchedule.getFactory().createTransitStopFacility(stopId, link.getToNode().getCoord(), false); stop.setLinkId(link.getId()); this.transitSchedule.addStopFacility(stop); - return 1; + return 1; } private boolean topoTypeAllowed(Link link) { @@ -495,7 +495,7 @@ private boolean topoTypeAllowed(Link link) { } Integer topoType = this.networkCalcTopoType.getTopoType(link.getToNode()); return this.topoTypesForStops.contains(topoType); - } + } private boolean linkToNodeInServiceArea(Link link) { Point p = factory.createPoint(MGC.coord2Coordinate(link.getToNode().getCoord())); diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingproxy/run/RunAreaAnalysis.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingproxy/run/RunAreaAnalysis.java index 270cb77fa09..7643b4ea3b4 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingproxy/run/RunAreaAnalysis.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingproxy/run/RunAreaAnalysis.java @@ -28,7 +28,7 @@ import org.matsim.core.config.ConfigUtils; import org.matsim.core.population.io.StreamingPopulationReader; import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; public class RunAreaAnalysis { @@ -38,8 +38,8 @@ public static void main(String[] args) { Path experiencedPlansPath = Paths.get(args[1]); Path networkFile = Paths.get(args[2]); - Collection features = ShapeFileReader.getAllFeatures(shapefile.toString()); - + Collection features = GeoFileReader.getAllFeatures(shapefile.toString()); + Config conf = ConfigUtils.createConfig(); conf.network().setInputFile(networkFile.toString()); RegionModeshareAnalyzer modeshares = new RegionModeshareAnalyzer(features); diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java index c3ba439a7c7..2684832db0a 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java @@ -70,7 +70,7 @@ import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; import org.matsim.core.trafficmonitoring.TravelTimeCalculator; import org.matsim.core.utils.collections.CollectionUtils; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.IOUtils; import org.matsim.core.utils.misc.Counter; import org.matsim.core.utils.misc.StringUtils; @@ -233,7 +233,7 @@ public final void calculateSamplingPointsPerZoneFromNetwork(String networkFilena public final void selectSamplingPoints(List locations, int numberOfPointsPerZone, String zonesShapeFilename, String zonesIdAttributeName, Random r) throws IOException { log.info("loading zones from " + zonesShapeFilename); - Collection zones = new ShapeFileReader().readFileAndInitialize(zonesShapeFilename); + Collection zones = new GeoFileReader().readFileAndInitialize(zonesShapeFilename); SpatialIndex zonesQt = new Quadtree(); for (SimpleFeature zone : zones) { Envelope envelope = ((Geometry) (zone.getDefaultGeometry())).getEnvelopeInternal(); diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/MatricesToXY.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/MatricesToXY.java index 1facd37be1e..405cdb0be00 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/MatricesToXY.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/MatricesToXY.java @@ -29,7 +29,7 @@ import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.IOUtils; import org.opengis.feature.simple.SimpleFeature; @@ -52,7 +52,7 @@ public static void main(String[] args) throws IOException { String xyCsvOutputFilename = args[3]; // path to the csv-file to be written, e.g. /path/to/skim-data.csv log.info("loading zones from " + zonesShapeFilename); - Collection zones = new ShapeFileReader().readFileAndInitialize(zonesShapeFilename); + Collection zones = new GeoFileReader().readFileAndInitialize(zonesShapeFilename); Map zonesById = new HashMap<>(); for (SimpleFeature zone : zones) { String zoneId = zone.getAttribute(zonesIdAttributeName).toString(); diff --git a/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/utils/WriteStationShapefile.java b/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/utils/WriteStationShapefile.java index 9a870c93a3b..5edcf65eb29 100644 --- a/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/utils/WriteStationShapefile.java +++ b/contribs/shared_mobility/src/main/java/org/matsim/contrib/shared_mobility/utils/WriteStationShapefile.java @@ -16,7 +16,7 @@ import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.gis.PointFeatureFactory; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -57,6 +57,6 @@ static public void main(String[] args) throws ConfigurationException { null)); } - ShapeFileWriter.writeGeometries(features, cmd.getOptionStrict("output-path")); + GeoFileWriter.writeGeometries(features, cmd.getOptionStrict("output-path")); } } diff --git a/contribs/sumo/src/main/java/org/matsim/contrib/sumo/SumoNetworkConverter.java b/contribs/sumo/src/main/java/org/matsim/contrib/sumo/SumoNetworkConverter.java index e6522716ed4..ec30ee33eb3 100644 --- a/contribs/sumo/src/main/java/org/matsim/contrib/sumo/SumoNetworkConverter.java +++ b/contribs/sumo/src/main/java/org/matsim/contrib/sumo/SumoNetworkConverter.java @@ -18,7 +18,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.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.IOUtils; import org.matsim.lanes.*; import org.xml.sax.SAXException; @@ -121,7 +121,7 @@ public static void main(String[] args) { */ private static Geometry calculateNetworkArea(Path shapeFile) { // only the first feature is used - return ((Geometry) ShapeFileReader.getAllFeatures(shapeFile.toString()).iterator().next().getDefaultGeometry()); + return ((Geometry) GeoFileReader.getAllFeatures(shapeFile.toString()).iterator().next().getDefaultGeometry()); } /** diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/act2mode/ActivityToModeAnalysis.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/act2mode/ActivityToModeAnalysis.java index 3c0e2d1c2d6..12055885daa 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/act2mode/ActivityToModeAnalysis.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/act2mode/ActivityToModeAnalysis.java @@ -35,14 +35,14 @@ import org.matsim.core.events.handler.EventHandler; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.gis.PointFeatureFactory; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; import playground.vsp.analysis.modules.AbstractAnalysisModule; /** * @author droeder - * + * * writeResultsPlanCoords() added by gleich * */ @@ -65,7 +65,7 @@ public class ActivityToModeAnalysis extends AbstractAnalysisModule { * @param sc, the scenario (it has to contain facilities!!!) * @param personsOfInterest, might be null, than all persons are processed * @param slotSize, timeSlotSize in seconds - * + * * output using Activity Coordinates from the plans instead of departure * and arrival links with writeResultsPlanCoords() */ @@ -100,24 +100,24 @@ public void postProcessData() { addAttribute("ActType", String.class). addAttribute("Mode", String.class). create(); - + //create features for departure this.departureSlotFeatures = new HashMap>(); for(ActivityToMode atm : this.handler.getDepartures()){ createFeatureAndAdd(atm, this.departureSlotFeatures, factory); } - + this.departureSlotFeaturesPlanCoord = new HashMap>(); for(ActivityToMode atm : this.handlerPlanCoord.getDepartures()){ createFeatureAndAdd(atm, this.departureSlotFeaturesPlanCoord, factory); } - + //create features for arrivals this.arrivalSlotFeatures = new HashMap>(); for(ActivityToMode atm : this.handler.getArrivals()){ createFeatureAndAdd(atm, this.arrivalSlotFeatures, factory); } - + this.arrivalSlotFeaturesPlanCoord = new HashMap>(); for(ActivityToMode atm : this.handlerPlanCoord.getArrivals()){ createFeatureAndAdd(atm, this.arrivalSlotFeaturesPlanCoord, factory); @@ -128,9 +128,9 @@ public void postProcessData() { /** * @param atm * @param departureSlotFeatures2 - * @param featureType + * @param featureType */ - private void createFeatureAndAdd(ActivityToMode atm, + private void createFeatureAndAdd(ActivityToMode atm, HashMap> slotFeatures, PointFeatureFactory factory) { Integer slice = (int) (atm.getTime() / this.slotSize); Set temp = slotFeatures.get(slice); @@ -149,22 +149,22 @@ private void createFeatureAndAdd(ActivityToMode atm, @Override public void writeResults(String outputFolder) { for(Entry> e: this.departureSlotFeatures.entrySet()){ - ShapeFileWriter.writeGeometries(e.getValue(), outputFolder + "departure_" + e.getKey().toString() + ".shp"); + GeoFileWriter.writeGeometries(e.getValue(), outputFolder + "departure_" + e.getKey().toString() + ".shp"); } for(Entry> e: this.departureSlotFeaturesPlanCoord.entrySet()){ - ShapeFileWriter.writeGeometries(e.getValue(), outputFolder + "departure_" + e.getKey().toString() + ".shp"); + GeoFileWriter.writeGeometries(e.getValue(), outputFolder + "departure_" + e.getKey().toString() + ".shp"); } for(Entry> e: this.arrivalSlotFeatures.entrySet()){ - ShapeFileWriter.writeGeometries(e.getValue(), outputFolder + "arrival_" + e.getKey().toString() + ".shp"); + GeoFileWriter.writeGeometries(e.getValue(), outputFolder + "arrival_" + e.getKey().toString() + ".shp"); } } - + public void writeResultsPlanCoords(String outputFolder) { for(Entry> e: this.departureSlotFeaturesPlanCoord.entrySet()){ - ShapeFileWriter.writeGeometries(e.getValue(), outputFolder + "departure_" + e.getKey().toString() + ".shp"); + GeoFileWriter.writeGeometries(e.getValue(), outputFolder + "departure_" + e.getKey().toString() + ".shp"); } for(Entry> e: this.arrivalSlotFeaturesPlanCoord.entrySet()){ - ShapeFileWriter.writeGeometries(e.getValue(), outputFolder + "arrival_" + e.getKey().toString() + ".shp"); + GeoFileWriter.writeGeometries(e.getValue(), outputFolder + "arrival_" + e.getKey().toString() + ".shp"); } } } diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/networkAnalysis/NetworkAnalyzer.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/networkAnalysis/NetworkAnalyzer.java index 7f036c0b858..4e41f3ae95f 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/networkAnalysis/NetworkAnalyzer.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/networkAnalysis/NetworkAnalyzer.java @@ -43,7 +43,7 @@ import org.matsim.core.scenario.MutableScenario; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; import playground.vsp.analysis.modules.AbstractAnalysisModule; @@ -58,66 +58,66 @@ * (ii) types (redundant, dead end, exit road) * (2) link statistics * (3) accessibility computation (depending on walk travel time to the network) - * + * * @author dhosse - * + * */ public class NetworkAnalyzer extends AbstractAnalysisModule{ private Logger log = LogManager.getLogger(NetworkAnalyzer.class); - + private Scenario scenario; private Network network; - + private Map> nodeTypes; private Map geometricLengths; - + private List nodesWithHighDegrees; private List lengthBelowStorageCapacity; private Map smallClusterLinks; - + private Map> filesForExportInQGisProject; - + private double totalLength = 0; private double totalGLength = 0; - + private SimpleFeatureBuilder builder; - + private Geometry envelope; - + private final String deadEnd = "deadEnd"; private final String exit = "exit"; private final String redundant = "redundant"; - + private final String TXTfile = ".txt"; private final String QGSfile = ".qgs"; private final String SHPfile = ".shp"; - + private String targetCoordinateSystem; - + private boolean nodesChecked = false; private boolean linksChecked = false; - + private SpatialGrid freeSpeedGrid = null; - + /** * Creates a new analyzer for properties of a given network file. - * + * * @param networkInputFile The MATSim-Network file to analyse. * @param targetCoordinateSystem The coordinate system your network data is transformed to. */ public NetworkAnalyzer(String networkInputFile, String targetCoordinateSystem) { - + super(NetworkAnalyzer.class.getSimpleName()); this.scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); this.targetCoordinateSystem = targetCoordinateSystem; - + if(networkInputFile!=null){ new MatsimNetworkReader(this.scenario.getNetwork()).readFile(networkInputFile); this.network = this.scenario.getNetwork(); } - + } @Override @@ -132,29 +132,29 @@ public void preProcessData() { @Override public void postProcessData() { - + this.nodeTypes = new TreeMap>(); this.geometricLengths = new HashMap(); this.nodesWithHighDegrees = new ArrayList(); this.filesForExportInQGisProject = new HashMap>(); this.lengthBelowStorageCapacity = new ArrayList(); this.smallClusterLinks = new TreeMap(); - + this.envelope = new BoundingPolygon(network, 200).returnPolygon(); this.filesForExportInQGisProject.put("envelope", Polygon.class); - + if(isRoutable()){ continueWithRoutableNetwork(); - + log.info("total length of all network links: " + this.totalLength + " m"); log.info("total geometric length of all network links: " + this.totalGLength+ " m"); } - + } @Override public void writeResults(String outputFolder) { - + try { exportEnvelopeToShape(outputFolder); writeNodesFiles(outputFolder); @@ -164,28 +164,28 @@ public void writeResults(String outputFolder) { } catch (IOException e) { e.printStackTrace(); } - + } - + private void exportEnvelopeToShape(String outputFolder) { SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder(); typeBuilder.setName("shape"); typeBuilder.add("envelope",Polygon.class); typeBuilder.add("area",Double.class); - + this.builder = new SimpleFeatureBuilder(typeBuilder.buildFeatureType()); - + ArrayList features = new ArrayList(); - + SimpleFeature feature = this.builder.buildFeature(null, new Object[]{ this.envelope, this.envelope.getArea() }); - + features.add(feature); - ShapeFileWriter.writeGeometries(features, outputFolder+"envelope"+this.SHPfile); + GeoFileWriter.writeGeometries(features, outputFolder+"envelope"+this.SHPfile); } @@ -194,18 +194,18 @@ private void exportEnvelopeToShape(String outputFolder) { * @return True if the given network contains of only one cluster and false, if there is more than one. */ private boolean isRoutable(){ - + //the nodes that have already been inspected final Map visitedNodes = new TreeMap(); //a map to store the biggest cluster of the network Map biggestCluster = new TreeMap(); - + boolean stillSearching = true; Iterator iter = this.network.getNodes().values().iterator(); - + log.info(" checking " + this.network.getNodes().size() + " nodes and " + this.network.getLinks().size() + " links for dead-ends..."); - + //run as long as there are still unvisited nodes while (iter.hasNext() && stillSearching) { Node startNode = iter.next(); @@ -225,9 +225,9 @@ private boolean isRoutable(){ } } } - + for(Id nodeId : this.network.getNodes().keySet()){ - + if(!biggestCluster.containsKey(nodeId)){ Node node = this.network.getNodes().get(nodeId); for(Link l : node.getOutLinks().values()){ @@ -236,69 +236,69 @@ private boolean isRoutable(){ } } } - + } - + return false; - + } - + /** * If the network is routable, the analysis methods are running over the network. */ private void continueWithRoutableNetwork() { - + checkNodeAttributes(); checkLinkAttributes(); - + //create a bounding box for accessibility computation BoundingBox bbox = BoundingBox.createBoundingBox(this.scenario.getNetwork()); - + double resolution = 100; - + //set measuring points from which the accessibility is measured ZoneLayer> measuringPoints = NetworkAnalyzer.createGridLayerByGridSizeByNetwork(resolution, bbox.getBoundingBox()); //initialize grid that stores the accessibility values this.freeSpeedGrid = new SpatialGrid(bbox.getXMin(),bbox.getYMin(),bbox.getXMax(),bbox.getYMax(), resolution, Double.NaN); MutableScenario sc = (MutableScenario) this.scenario; - + //run accessibility computation new AccessibilityCalc(measuringPoints, freeSpeedGrid, sc,envelope).runAccessibilityComputation(); - + } - + /** * Parses all network nodes and classifies them into either exit road, dead end or redundant nodes. * Currently only for nodes with degree = 1. */ private void checkNodeAttributes() { - + log.info("analysing network nodes..."); - + int exit=0,red=0,de=0; - + this.nodeTypes.put(this.exit, new ArrayList()); this.nodeTypes.put(this.deadEnd, new ArrayList()); this.nodeTypes.put(this.redundant, new ArrayList()); - + //iterate over all network nodes for(Node node : this.network.getNodes().values()){ //if the node has any ingoing and outgoing links (at least one of a kind) investigate the node if(node.getInLinks().size()>0&&node.getOutLinks().size()>0){ - + //catches nodes with high degrees (here: more than five in- or outgoing links) if(node.getInLinks().size()>5||node.getOutLinks().size()>5) this.nodesWithHighDegrees.add(node.getId()); - + //if the node's degree equals 1, then classify it if(node.getInLinks().size()==1&&node.getOutLinks().size()==1){ //get the in- and the outgoing link of the node Link inLink = node.getInLinks().values().iterator().next(); Link outLink = node.getOutLinks().values().iterator().next(); - + //if the only possible moving direction from this node is backwards //(to the node you came from) and it lies outside the bounding polygon //then it's a node of an exit road @@ -312,7 +312,7 @@ private void checkNodeAttributes() { //if it's inside the polygon, it's a node of a dead end road this.nodeTypes.get(this.deadEnd).add(node.getId()); de++; - + } else{ //if all attributes of the ingoing link are equal to the //attributes of the outgoing link, then the node is redundant @@ -327,37 +327,37 @@ private void checkNodeAttributes() { } } } - + log.info("found " + exit + " exit road nodes, " + de + " dead end nodes and " + red + " redundant nodes..."); log.info("...done"); - + this.nodesChecked = true; - + } - + /** *Parses all network links to compute their geometric length (fromNode to toNode) and check if their storage capacity is sufficient for - *storing at least one vehicle (link length >= effektiveCellSize). + *storing at least one vehicle (link length >= effektiveCellSize). */ private void checkLinkAttributes() { - + log.info("analyzing network links..."); - + //the space needed to store a vehicle (+ additional space for the gaps to the vehicle ahead and the one following double cellWidth = ((Network)this.network).getEffectiveCellSize(); int writerIndex = 0; - + //iterate over all links for(Link link : this.network.getLinks().values()){ //compute geometric length (distance between from and to node) - double geometricLength = + double geometricLength = Math.sqrt(Math.pow(link.getToNode().getCoord().getX() - link.getFromNode().getCoord().getX(),2) + Math.pow(link.getToNode().getCoord().getY() - link.getFromNode().getCoord().getY(), 2)); - + this.geometricLengths.put(link.getId(), geometricLength); - + this.totalLength += link.getLength(); this.totalGLength += geometricLength; //if the length of the link is less than the effectiveCellSize then store the link and write a warning about that later @@ -370,7 +370,7 @@ private void checkLinkAttributes() { log.info("...done"); this.linksChecked = true; } - + private Map findCluster(final Node startNode, final Network network) { final Map nodeRoles = new HashMap(network.getNodes().size()); @@ -418,7 +418,7 @@ private Map findCluster(final Node startNode, final Network network) { return clusterNodes; } - + private static DoubleFlagRole getDoubleFlag(final Node n, final Map nodeRoles) { DoubleFlagRole r = nodeRoles.get(n); if (null == r) { @@ -427,56 +427,56 @@ private static DoubleFlagRole getDoubleFlag(final Node n, final Map> createGridLayerByGridSizeByNetwork(double gridSize, double [] boundingBox) { - + // log.info("Setting starting points for accessibility measure ..."); int skippedPoints = 0; int setPoints = 0; - + GeometryFactory factory = new GeometryFactory(); - + Set>> zones = new HashSet<>(); double xmin = boundingBox[0]; double ymin = boundingBox[1]; double xmax = boundingBox[2]; double ymax = boundingBox[3]; - - + + ProgressBar bar = new ProgressBar( (xmax-xmin)/gridSize ); - + // goes step by step from the min x and y coordinate to max x and y coordinate for(double x = xmin; x = xmin && + if (center_X <= xmax && center_X >= xmin && center_Y <= ymax && center_Y >= ymin) { - + Point point = factory.createPoint(new Coordinate(x, y)); - + Coordinate[] coords = new Coordinate[5]; coords[0] = point.getCoordinate(); coords[1] = new Coordinate(x, y + gridSize); @@ -487,11 +487,11 @@ public static ZoneLayer> createGridLayerByGridSizeByNetwork(double grid LinearRing linearRing = factory.createLinearRing(coords); Polygon polygon = factory.createPolygon(linearRing, null); // polygon.setSRID( srid ); // tnicolai: this is not needed to match the grid layer with locations / facilities from UrbanSim - + Zone> zone = new Zone>(polygon); zone.setAttribute( Id.create( setPoints, Zone.class ) ); zones.add(zone); - + setPoints++; } else skippedPoints++; @@ -500,24 +500,24 @@ public static ZoneLayer> createGridLayerByGridSizeByNetwork(double grid // log.info("Having " + setPoints + " inside the shape file boundary (and " + skippedPoints + " outside)."); // log.info("Done with setting starting points!"); - + ZoneLayer> layer = new ZoneLayer<>(zones); return layer; } - + /** * Calls the writing methods for node statistics after the analysis and classification - * - * @param outputFolder + * + * @param outputFolder * @throws IOException */ private void writeNodesFiles(String outputFolder) throws IOException { - + if(this.nodesChecked){ writeNodeStatisticsFile(outputFolder); exportNodesToShape(outputFolder); } - + } /** @@ -528,25 +528,25 @@ private void writeNodesFiles(String outputFolder) throws IOException { private void writeNodeStatisticsFile(String outputFolder) throws IOException { File file = new File(outputFolder+"nodeStatistics"+this.TXTfile); FileWriter writer = new FileWriter(file);; - + writer.write("ID\tinDegree\toutDegree"); - + for(Node n : this.network.getNodes().values()){ - + writer.write("\n"+n.getId()+"\t"+n.getInLinks().size()+"\t"+n.getOutLinks().size()); - + } writer.flush(); writer.close(); } - + /** * Writes the classified nodes to a shape file for visualisation in QGis. - * + * * @param outputFolder */ private void exportNodesToShape(String outputFolder){ - + SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder(); typeBuilder.setName("node"); typeBuilder.add("location",Point.class); @@ -554,32 +554,32 @@ private void exportNodesToShape(String outputFolder){ typeBuilder.add("type",String.class); typeBuilder.setCRS(MGC.getCRS(this.targetCoordinateSystem)); this.builder = new SimpleFeatureBuilder(typeBuilder.buildFeatureType()); - + Collection features = new ArrayList(); - + for(String nodeType : this.nodeTypes.keySet()){ for(Id nodeId : this.nodeTypes.get(nodeType)){ Point p = MGC.coord2Point(this.network.getNodes().get(nodeId).getCoord()); features.add(this.builder.buildFeature(null, new Object[]{p,nodeId.toString(),nodeType})); - + } - + } - + String destination = ""; - + if(features.size() > 0){ destination = "nodeTypes"; - + this.filesForExportInQGisProject.put(destination,Point.class); - - ShapeFileWriter.writeGeometries(features, outputFolder+destination+this.SHPfile); + + GeoFileWriter.writeGeometries(features, outputFolder+destination+this.SHPfile); } - + if(!(this.nodesWithHighDegrees.size() < 1)){ features.clear(); - + typeBuilder.setName("node"); typeBuilder.add("location",Point.class); typeBuilder.add("ID",String.class); @@ -587,42 +587,42 @@ private void exportNodesToShape(String outputFolder){ typeBuilder.add("out-degree",Integer.class); typeBuilder.setCRS(MGC.getCRS(this.targetCoordinateSystem)); this.builder = new SimpleFeatureBuilder(typeBuilder.buildFeatureType()); - + for(Id nodeId : this.nodesWithHighDegrees){ - + Point p = MGC.coord2Point(this.network.getNodes().get(nodeId).getCoord()); features.add(this.builder.buildFeature(null, new Object[]{p,nodeId.toString(), this.network.getNodes().get(nodeId).getInLinks().size(), this.network.getNodes().get(nodeId).getOutLinks().size()})); } - + destination = "highDegreeNodes"; - + this.filesForExportInQGisProject.put(destination, Point.class); - ShapeFileWriter.writeGeometries(features, outputFolder+destination+this.SHPfile); + GeoFileWriter.writeGeometries(features, outputFolder+destination+this.SHPfile); } - + } /** * Calls the writing methods for link statistics after analysis. - * + * * @param outputFolder * @throws IOException */ private void writeLinkFiles(String outputFolder) throws IOException { - + if(this.linksChecked){ writeLinkStatisticsFile(outputFolder); writeStorageCapacityWarningFile(outputFolder); } writeClustersAndNetwork2ESRIShape(outputFolder); - + } /** - * Writes a logfile with all warnings about links with insufficient storage capacity (link length < effectiveCellSize). - * + * Writes a logfile with all warnings about links with insufficient storage capacity (link length < effectiveCellSize). + * * @param outputFolder * @throws IOException */ @@ -631,7 +631,7 @@ private void writeStorageCapacityWarningFile(String outputFolder) throws IOExcep FileWriter writer; double cellWidth = ((Network)this.network).getEffectiveCellSize(); - + writer = new FileWriter(file); for(Link link : this.lengthBelowStorageCapacity){ writer.write("length of link " + link.getId() + " below min length for storage capacity of one vehicle (" + @@ -640,42 +640,42 @@ private void writeStorageCapacityWarningFile(String outputFolder) throws IOExcep writer.flush(); writer.close(); } - + /** * Writes the link statistics (length, geometric length, number of lanes, capacity) to a plain text file. - * + * * @param outputFolder * @throws IOException */ private void writeLinkStatisticsFile(String outputFolder) throws IOException{ - + File file = new File(outputFolder+"linkStatistics"+this.TXTfile); - - + + FileWriter writer = new FileWriter(file); - + writer.write("ID \t length \t geometricLength \t nlanes \t capacity"); - + for(Link l : this.network.getLinks().values()){ - + writer.write("\n"+ l.getId() + "\t"+l.getLength() + "\t" + this.geometricLengths.get(l.getId()) + "\t" + l.getNumberOfLanes() + "\t" + l.getCapacity()); - + } writer.flush(); writer.close(); - + } - + /** * Exports the network links and (if existing) the links contained in small clusters to an ESRI shapefile. * @param outputFolder */ private void writeClustersAndNetwork2ESRIShape(String outputFolder) { - + SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder(); typeBuilder.setName("shape"); typeBuilder.add("link",LineString.class); @@ -686,11 +686,11 @@ private void writeClustersAndNetwork2ESRIShape(String outputFolder) { typeBuilder.add("nlanes", String.class); typeBuilder.setCRS(MGC.getCRS(this.targetCoordinateSystem)); this.builder = new SimpleFeatureBuilder(typeBuilder.buildFeatureType()); - + ArrayList features = new ArrayList(); - + for(Link link : this.network.getLinks().values()){ - + SimpleFeature feature = this.builder.buildFeature(null, new Object[]{ new GeometryFactory().createLineString(new Coordinate[]{ new Coordinate(link.getFromNode().getCoord().getX(),link.getFromNode().getCoord().getY()), @@ -701,25 +701,25 @@ private void writeClustersAndNetwork2ESRIShape(String outputFolder) { link.getFreespeed(), link.getCapacity(), link.getNumberOfLanes() - + }); - + features.add(feature); - + } - + String destination = "network"; - + this.filesForExportInQGisProject.put(destination,LineString.class); - - ShapeFileWriter.writeGeometries(features, outputFolder+destination+this.SHPfile); - + + GeoFileWriter.writeGeometries(features, outputFolder+destination+this.SHPfile); + if(this.smallClusterLinks.size()>0){ - + features.clear(); - + for(Link link : this.smallClusterLinks.values()){ - + SimpleFeature feature = this.builder.buildFeature(null, new Object[]{ new GeometryFactory().createLineString(new Coordinate[]{ new Coordinate(link.getFromNode().getCoord().getX(),link.getFromNode().getCoord().getY()), @@ -731,31 +731,31 @@ private void writeClustersAndNetwork2ESRIShape(String outputFolder) { link.getCapacity(), link.getNumberOfLanes() }); - + features.add(feature); - + } - + destination = "smallClusters"; - + this.filesForExportInQGisProject.put(destination,LineString.class); - - ShapeFileWriter.writeGeometries(features, outputFolder+destination+this.SHPfile); - + + GeoFileWriter.writeGeometries(features, outputFolder+destination+this.SHPfile); + } } - + private void writeAccessibilityMap(String outputFolder){ - + try{ BufferedWriter writer = new BufferedWriter(new FileWriter(outputFolder+"/freeSpeedAccessibility.txt")); - + for(double x = this.freeSpeedGrid.getXmin(); x <= this.freeSpeedGrid.getXmax(); x += this.freeSpeedGrid.getResolution()) { writer.write(SpatialGridTableWriter.separator); writer.write(String.valueOf(x)); } writer.newLine(); - + for(double y = this.freeSpeedGrid.getYmin(); y <= this.freeSpeedGrid.getYmax() ; y += this.freeSpeedGrid.getResolution()) { writer.write(String.valueOf(y)); for(double x = this.freeSpeedGrid.getXmin(); x <= this.freeSpeedGrid.getXmax(); x += this.freeSpeedGrid.getResolution()) { @@ -774,7 +774,7 @@ private void writeAccessibilityMap(String outputFolder){ catch(IOException e){ e.printStackTrace(); } - + } - + } diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/ptAccessibility/utils/PtAccesShapeWriter.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/ptAccessibility/utils/PtAccesShapeWriter.java index e4c6db96362..f21e092ba84 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/ptAccessibility/utils/PtAccesShapeWriter.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/ptAccessibility/utils/PtAccesShapeWriter.java @@ -34,7 +34,7 @@ import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.gis.PointFeatureFactory; import org.matsim.core.utils.gis.PolygonFeatureFactory; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; import playground.vsp.analysis.modules.ptAccessibility.activity.ActivityLocation; @@ -44,7 +44,7 @@ /** * @author droeder, aneumann * - * just a helper-class + * just a helper-class */ public class PtAccesShapeWriter { @@ -60,16 +60,16 @@ public static void writeMultiPolygons(Map mps, String file addAttribute("name", String.class). create(); Collection features = new ArrayList(); - + Object[] featureAttribs; for(Entry e: mps.entrySet()){ featureAttribs = new Object[1]; featureAttribs[0] = e.getKey(); features.add(factory.createPolygon(e.getValue(), featureAttribs, null)); } - ShapeFileWriter.writeGeometries(features, filename); + GeoFileWriter.writeGeometries(features, filename); } - + public static void writeActivityLocations(LocationMap locationMap, String outputFolder, String name, String targetCoordinateSystem, double gridSize){ PointFeatureFactory featureFactory = new PointFeatureFactory.Builder(). setCrs(MGC.getCRS(targetCoordinateSystem)). @@ -77,13 +77,13 @@ public static void writeActivityLocations(LocationMap locationMap, String output addAttribute("name", String.class). addAttribute("type", String.class). create(); - + PointFeatureFactory clusterFeatureFactory = new PointFeatureFactory.Builder(). setCrs(MGC.getCRS(targetCoordinateSystem)). setName(name). addAttribute("count", Integer.class). create(); - + for(Entry> type2LocationEntry: locationMap.getType2Locations().entrySet()){ if (!type2LocationEntry.getValue().isEmpty()) { try { @@ -94,44 +94,44 @@ public static void writeActivityLocations(LocationMap locationMap, String output type2LocationEntry.getKey() }, null)); } - - ShapeFileWriter.writeGeometries(features, outputFolder + "activityLocations_" + type2LocationEntry.getKey() + ".shp"); + + GeoFileWriter.writeGeometries(features, outputFolder + "activityLocations_" + type2LocationEntry.getKey() + ".shp"); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch(ServiceConfigurationError e){ e.printStackTrace(); } - + // cluster first write then - + try { Collection features = new ArrayList(); - + HashMap gridNodeId2GridNode = new HashMap(); - + // go through all acts of this type for(int i = 0; i < type2LocationEntry.getValue().size(); i++){ Coord coord = new Coord(type2LocationEntry.getValue().get(i).getCoord().x, type2LocationEntry.getValue().get(i).getCoord().y); String gridNodeId = GridNode.getGridNodeIdForCoord(coord, gridSize); - + if (gridNodeId2GridNode.get(gridNodeId) == null) { gridNodeId2GridNode.put(gridNodeId, new GridNode(gridNodeId)); } - + gridNodeId2GridNode.get(gridNodeId).addPoint(type2LocationEntry.getKey(), coord); } - + for (GridNode gridNode : gridNodeId2GridNode.values()) { features.add(clusterFeatureFactory.createPoint(new Coordinate(gridNode.getX(), gridNode.getY()), new Object[] {gridNode.getCountForType(type2LocationEntry.getKey())}, null)); } - - ShapeFileWriter.writeGeometries(features, outputFolder + "activityLocations_clustered_" + type2LocationEntry.getKey() + ".shp"); + + GeoFileWriter.writeGeometries(features, outputFolder + "activityLocations_clustered_" + type2LocationEntry.getKey() + ".shp"); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch(ServiceConfigurationError e){ e.printStackTrace(); } - + } else { log.info("No activities found for cluster " + type2LocationEntry.getKey()); } diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/ptAccessibility/utils/PtAccessMapShapeWriter.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/ptAccessibility/utils/PtAccessMapShapeWriter.java index 6605af703cc..615512e0fe6 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/ptAccessibility/utils/PtAccessMapShapeWriter.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/ptAccessibility/utils/PtAccessMapShapeWriter.java @@ -31,20 +31,20 @@ import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.MultiPolygon; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; import playground.vsp.analysis.modules.ptAccessibility.stops.PtStopMap; /** * Calculates and writes buffers to shapes - * + * * @author aneumann */ public class PtAccessMapShapeWriter { private PtAccessMapShapeWriter() { - + } public static void writeAccessMap(Map> cluster2mode2area, int quadrantSegments, String outputFolder, String targetCoordinateSystem) { @@ -56,11 +56,11 @@ public static void writeAccessMap(Map> cluster Collections.sort(distancesSmallestFirst); HashMap> distance2mode2buffer = new HashMap>(); - + // Calculate buffer for all Multipolygons HashMap mode2buffer = null; int lastDistance = 0; - + for (Integer distance : distancesSmallestFirst) { if (mode2buffer == null) { // it's the frist and smallest one @@ -77,29 +77,29 @@ public static void writeAccessMap(Map> cluster mode2buffer = tempBuffers; lastDistance = distance.intValue(); } - + distance2mode2buffer.put(distance, mode2buffer); } - + writeGeometries(outputFolder + PtStopMap.FILESUFFIX + "_buffer", distance2mode2buffer, targetCoordinateSystem); - - - + + + // resort distances - largest first ArrayList distancesLargestFirst = new ArrayList(); for (Integer distance : distancesSmallestFirst) { distancesLargestFirst.add(0, distance); } - + HashMap> distance2mode2diffBuffer = new HashMap>(); HashMap lastMode2Buffer = null; Integer lastDist = null; - + // calculate Diff for all buffers for (Integer distance : distancesLargestFirst) { distance2mode2diffBuffer.put(distance, new HashMap()); - + if (lastMode2Buffer == null) { lastMode2Buffer = distance2mode2buffer.get(distance); lastDist = distance; @@ -113,12 +113,12 @@ public static void writeAccessMap(Map> cluster lastDist = distance; } } - + // add last (smallest) one as well for (Entry mode2BufferEntry : lastMode2Buffer.entrySet()) { distance2mode2diffBuffer.get(lastDist).put(mode2BufferEntry.getKey(), mode2BufferEntry.getValue()); } - + writeGeometries(outputFolder + PtStopMap.FILESUFFIX + "_diffBuffer", distance2mode2diffBuffer, targetCoordinateSystem); } @@ -130,10 +130,10 @@ private static void writeGeometries(String outputFolderAndFileName, HashMap bufferFeatures; Object[] bufferFeatureAttribs; - + for (Entry> distance2mode2bufferEntry : distance2mode2buffer.entrySet()) { bufferFeatures = new ArrayList(); HashMap mode2buffer = distance2mode2bufferEntry.getValue(); @@ -148,13 +148,13 @@ private static void writeGeometries(String outputFolderAndFileName, HashMap getAll(String targetCoordinateSystem) { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.setCRS(MGC.getCRS(targetCoordinateSystem)); @@ -93,9 +93,9 @@ private Collection getAll(String targetCoordinateSystem) { b.add("pax_" + String.valueOf(i), Double.class); } SimpleFeatureBuilder builder = new SimpleFeatureBuilder(b.buildFeatureType()); - + Collection features = new ArrayList(); - + Object[] featureAttribs; for(Link link: this.sc.getNetwork().getLinks().values()){ featureAttribs = getFeatureAll(link,new Object[4 + this.handler.getMaxInterval()]); @@ -116,7 +116,7 @@ private Object[] getFeatureAll(Link link, Object[] objects) { Coordinate[] coord = new Coordinate[2]; coord[0] = new Coordinate(link.getFromNode().getCoord().getX(), link.getFromNode().getCoord().getY(), 0.); coord[1] = new Coordinate(link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY(), 0.); - + objects[0] = new GeometryFactory().createLineString(coord); objects[1] = "all"; objects[2] = link.getId().toString(); @@ -138,11 +138,11 @@ private Collection getTransitLineFeatures(TransitLine l, String t for (int i = 0; i < this.handler.getMaxInterval(); i++){ b.add("pax_" + String.valueOf(i), Double.class); } - + SimpleFeatureBuilder builder = new SimpleFeatureBuilder(b.buildFeatureType()); - + Collection features = new ArrayList(); - + Object[] featureAttribs; for(Link link: this.sc.getNetwork().getLinks().values()){ featureAttribs = getLinkFeatureAttribs(link,l.getId(), new Object[4 + this.handler.getMaxInterval()]); @@ -169,7 +169,7 @@ private Object[] getLinkFeatureAttribs(Link link, Id lineId, Object Coordinate[] coord = new Coordinate[2]; coord[0] = new Coordinate(link.getFromNode().getCoord().getX(), link.getFromNode().getCoord().getY(), 0.); coord[1] = new Coordinate(link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY(), 0.); - + objects[0] = new GeometryFactory().createLineString(coord); objects[1] = lineId.toString(); objects[2] = link.getId().toString(); @@ -185,7 +185,7 @@ public void writeResults(String outputFolder) { for(Entry, Collection> ee: this.lineId2features.entrySet()){ try{ if(ee.getValue().size() <= 0) continue; - ShapeFileWriter.writeGeometries(ee.getValue(), outputFolder + ee.getKey().toString()+ ".shp"); + GeoFileWriter.writeGeometries(ee.getValue(), outputFolder + ee.getKey().toString()+ ".shp"); }catch(ServiceConfigurationError e){ e.printStackTrace(); } diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/transitSchedule2Shp/TransitSchedule2Shp.java b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/transitSchedule2Shp/TransitSchedule2Shp.java index 94f8a049b8a..8423b07bc67 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/modules/transitSchedule2Shp/TransitSchedule2Shp.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/modules/transitSchedule2Shp/TransitSchedule2Shp.java @@ -38,7 +38,7 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.core.events.handler.EventHandler; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.matsim.core.utils.misc.Time; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; @@ -51,9 +51,9 @@ * @author aneumann, droeder */ public class TransitSchedule2Shp extends AbstractAnalysisModule{ - + private static final Logger log = LogManager.getLogger(TransitSchedule2Shp.class); - + private Network network; private TransitSchedule schedule; private final String targetCoordinateSystem; @@ -72,12 +72,12 @@ public List getEventHandler() { @Override public void preProcessData() { - + } @Override public void postProcessData() { - + } @Override @@ -92,23 +92,23 @@ public void writeResults(String outputFolder) { Collection temp = getTransitLineFeatures(transitLine, this.targetCoordinateSystem); features.addAll(temp); try{ - ShapeFileWriter.writeGeometries(temp, outputFolder + transitLine.getId().toString() + ".shp"); + GeoFileWriter.writeGeometries(temp, outputFolder + transitLine.getId().toString() + ".shp"); }catch(ServiceConfigurationError e){ e.printStackTrace(); } } - // write a complete shape + // write a complete shape if(features.isEmpty()){ log.error("the transitschedule seems to be empty. No features are created, thus no shapefile will be written..."); return; } try{ - ShapeFileWriter.writeGeometries(features, outputFolder + "allLines.shp"); + GeoFileWriter.writeGeometries(features, outputFolder + "allLines.shp"); }catch(ServiceConfigurationError e){ e.printStackTrace(); } } - + private Collection getTransitLineFeatures(TransitLine transitLine, String targetCoordinateSystem) { SimpleFeatureTypeBuilder simpleFeatureBuilder = new SimpleFeatureTypeBuilder(); simpleFeatureBuilder.setCRS(MGC.getCRS(targetCoordinateSystem)); @@ -131,9 +131,9 @@ private Collection getTransitLineFeatures(TransitLine transitLine simpleFeatureBuilder.add("lastDep", String.class); simpleFeatureBuilder.add("timeOper", String.class); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeatureBuilder.buildFeatureType()); - + Collection features = new ArrayList(); - + Object[] routeFeatureAttributes; for(TransitRoute transitRoute: transitLine.getRoutes().values()){ routeFeatureAttributes = getRouteFeatureAttribs(transitRoute, transitLine.getId(), new Object[17]); @@ -147,25 +147,25 @@ private Collection getTransitLineFeatures(TransitLine transitLine } private Object[] getRouteFeatureAttribs(TransitRoute transitRoute, Id lineId, Object[] routeFeatureAttributes ) { - + List coords = new ArrayList(); // Create the polyline (lineString) - + // add the startLink Coord toNode = this.network.getLinks().get(transitRoute.getRoute().getStartLinkId()).getToNode().getCoord(); coords.add(new Coordinate(toNode.getX(), toNode.getY(), 0.)); - + // add the routeLinks for(Id linkId : transitRoute.getRoute().getLinkIds()){ toNode = this.network.getLinks().get(linkId).getToNode().getCoord(); coords.add(new Coordinate(toNode.getX(), toNode.getY(), 0.)); } - + //add the endlink toNode = this.network.getLinks().get(transitRoute.getRoute().getEndLinkId()).getToNode().getCoord(); coords.add(new Coordinate(toNode.getX(), toNode.getY(), 0.)); - + // create an array Coordinate[] coord = new Coordinate[coords.size()]; coord = coords.toArray(coord); @@ -173,7 +173,7 @@ private Object[] getRouteFeatureAttribs(TransitRoute transitRoute, Id counts, Map mo } } try{ - ShapeFileWriter.writeGeometries(features, file); + GeoFileWriter.writeGeometries(features, file); }catch(ServiceConfigurationError e){ e.printStackTrace(); } catch (UncheckedIOException e) { diff --git a/contribs/vsp/src/main/java/playground/vsp/analysis/utils/heatMap/HeatMap.java b/contribs/vsp/src/main/java/playground/vsp/analysis/utils/heatMap/HeatMap.java index 6bbf5bbb7ce..f8441de40be 100644 --- a/contribs/vsp/src/main/java/playground/vsp/analysis/utils/heatMap/HeatMap.java +++ b/contribs/vsp/src/main/java/playground/vsp/analysis/utils/heatMap/HeatMap.java @@ -35,7 +35,7 @@ import org.matsim.core.utils.collections.QuadTree; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; /** @@ -52,9 +52,9 @@ public class HeatMap { private double maxY = -Double.MAX_VALUE; private QuadTree tiles; private Integer gridSize; - + private class Tile{ - + private Polygon area; private Double value; @@ -78,34 +78,34 @@ public Tile(double minX, double maxX, double minY, double maxY) { this.area = factory.createPolygon(factory.createLinearRing(c), null); this.value = 0.; } - + public Coord getCentroid(){ return MGC.point2Coord(this.area.getCentroid()); } - + public Polygon getGeometry(){ return this.area; } - + public void add(Double d){ this.value += d; } - + public double getValue(){ return this.value; } } - + /** * a class to create a simple HeatMap from coordinates and corresponding values. - * + * * @param gridSize, the number of tiles of the HeatMap */ public HeatMap(Integer gridSize) { this.gridSize = gridSize; this.values = new ArrayList>(); } - + public void addValue(Coord coord, Double value){ this.values.add(new Tuple(coord, value)); findMinMax(coord); @@ -128,7 +128,7 @@ private void findMinMax(Coord coord) { this.minY = coord.getY(); } } - + public void createHeatMap(){ this.tiles = new QuadTree(minX, minY, maxX, maxY); Double dx, dy, inc; @@ -171,7 +171,7 @@ public void createHeatMap(){ t.add(v.getSecond()); } } - + private Collection getTiles() { return this.tiles.values(); } @@ -184,9 +184,9 @@ public static void writeHeatMapShape(String name, HeatMap heatmap, String file, b.add("name", String.class); b.add("count", Double.class); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(b.buildFeatureType()); - + Collection features = new ArrayList(); - + Object[] featureAttribs; int i = 0; for(Tile t: heatmap.getTiles()){ @@ -205,7 +205,7 @@ public static void writeHeatMapShape(String name, HeatMap heatmap, String file, log.info("There are no tiles for " + name); } else { try{ - ShapeFileWriter.writeGeometries(features, file); + GeoFileWriter.writeGeometries(features, file); }catch(ServiceConfigurationError e){ e.printStackTrace(); } diff --git a/contribs/vsp/src/main/java/playground/vsp/andreas/utils/ana/RouteAllModesAsCar.java b/contribs/vsp/src/main/java/playground/vsp/andreas/utils/ana/RouteAllModesAsCar.java index e003b97fc9f..28ddbf7ab00 100644 --- a/contribs/vsp/src/main/java/playground/vsp/andreas/utils/ana/RouteAllModesAsCar.java +++ b/contribs/vsp/src/main/java/playground/vsp/andreas/utils/ana/RouteAllModesAsCar.java @@ -54,19 +54,19 @@ import org.matsim.core.router.util.LeastCostPathCalculator.Path; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.matsim.pt.PtConstants; import org.opengis.feature.simple.SimpleFeature; /** * Routes all modes of transport (except for transit_walk) as car modes and counts the number of trips per link. * Output as Shape - * + * * @author aneumann * */ public class RouteAllModesAsCar extends AbstractPersonFilter { - + private final static Logger log = LogManager.getLogger(RouteAllModesAsCar.class); private final Scenario sc; @@ -74,16 +74,16 @@ public class RouteAllModesAsCar extends AbstractPersonFilter { private HashMap link2totals = new HashMap(); private HashMap> mode2link2totals = new HashMap>(); - + public RouteAllModesAsCar(String networkFilename) { Gbl.startMeasurement(); Gbl.printMemoryUsage(); - + // read input data this.sc = ScenarioUtils.createScenario(ConfigUtils.createConfig()); this.sc.getConfig().network().setInputFile(networkFilename); ScenarioUtils.loadScenario(this.sc); - + FreespeedTravelTimeAndDisutility tC = new FreespeedTravelTimeAndDisutility(-6.0, 0.0, 0.0); this.routingAlgo = new DijkstraFactory().createPathCalculator(this.sc.getNetwork(), tC, tC); @SuppressWarnings("serial") @@ -99,7 +99,7 @@ public static void main(String[] args) { String networkFilename = args[1]; String popFilename = args[2]; String targetCoordinateSystem = args[3]; - + RouteAllModesAsCar routeAllModesAsCar = new RouteAllModesAsCar(networkFilename); routeAllModesAsCar.run(popFilename); routeAllModesAsCar.writeAsShape(outputDir, targetCoordinateSystem); @@ -115,15 +115,15 @@ private void writeAsShape(String outputDir, String targetCoordinateSystem) { for (String mode : this.mode2link2totals.keySet()) { typeBuilder.add("count " + mode, Double.class); } - + SimpleFeatureBuilder builder = new SimpleFeatureBuilder(typeBuilder.buildFeatureType()); - + Collection features = new ArrayList(); - + Object[] featureAttribs; - + for(Link link: this.sc.getNetwork().getLinks().values()){ - + featureAttribs = createLinkFeatureAttribs(link, new Object[3 + this.mode2link2totals.keySet().size()]); // skip links without count @@ -137,25 +137,25 @@ private void writeAsShape(String outputDir, String targetCoordinateSystem) { e1.printStackTrace(); } } - - ShapeFileWriter.writeGeometries(features, outputDir + "routeAllModesAsCar.shp"); + + GeoFileWriter.writeGeometries(features, outputDir + "routeAllModesAsCar.shp"); } private Object[] createLinkFeatureAttribs(Link link, Object[] objects) { if(this.link2totals.get(link) == null) { return null; } - + int total = this.link2totals.get(link).intValue(); - + Coordinate[] coord = new Coordinate[2]; coord[0] = new Coordinate(link.getFromNode().getCoord().getX(), link.getFromNode().getCoord().getY(), 0.); coord[1] = new Coordinate(link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY(), 0.); - + objects[0] = new GeometryFactory().createLineString(coord); objects[1] = link.getId().toString(); objects[2] = total; - + int index = 3; for(String mode : this.mode2link2totals.keySet()){ if (this.mode2link2totals.get(mode).get(link) == null) { @@ -195,27 +195,27 @@ public void run(Person person) { count(); Activity lastAct = null; String currentMode = null; - + for (PlanElement planElement : person.getSelectedPlan().getPlanElements()) { if (planElement instanceof Activity) { Activity act = (Activity) planElement; - + if (act.getType().equalsIgnoreCase(PtConstants.TRANSIT_ACTIVITY_TYPE)) { continue; } - + if (lastAct == null) { lastAct = act; } else { Link lastLink = this.sc.getNetwork().getLinks().get(lastAct.getLinkId()); Link currentLink = this.sc.getNetwork().getLinks().get(act.getLinkId()); - + Path path = this.routingAlgo.calcLeastCostPath(lastLink.getToNode(), currentLink.getFromNode(), 0.0, null, null); this.storeLinks(currentMode, path.links); lastAct = act; } } - + if (planElement instanceof Leg) { Leg leg = (Leg) planElement; if (!leg.getMode().equalsIgnoreCase(TransportMode.transit_walk)) { @@ -228,11 +228,11 @@ public void run(Person person) { private void storeLinks(String currentMode, List links) { for (Link link : links) { this.addOne(this.link2totals, link); - + if (this.mode2link2totals.get(currentMode) == null) { this.mode2link2totals.put(currentMode, new HashMap()); } - + this.addOne(this.mode2link2totals.get(currentMode), link); } } diff --git a/contribs/vsp/src/main/java/playground/vsp/andreas/utils/ana/filterActsPerShape/WorkHomeShapeCounter.java b/contribs/vsp/src/main/java/playground/vsp/andreas/utils/ana/filterActsPerShape/WorkHomeShapeCounter.java index e32cc258ad3..c7489566966 100644 --- a/contribs/vsp/src/main/java/playground/vsp/andreas/utils/ana/filterActsPerShape/WorkHomeShapeCounter.java +++ b/contribs/vsp/src/main/java/playground/vsp/andreas/utils/ana/filterActsPerShape/WorkHomeShapeCounter.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.util.HashMap; -import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.geotools.data.simple.SimpleFeatureIterator; @@ -40,74 +39,74 @@ import org.matsim.core.population.PersonUtils; import org.matsim.core.population.algorithms.AbstractPersonAlgorithm; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; public class WorkHomeShapeCounter extends AbstractPersonAlgorithm{ - + private static final Logger log = LogManager.getLogger(WorkHomeShapeCounter.class); private final Coord minXY; private final Coord maxXY; private String actTypeOne; private String actTypeTwo; - + private boolean initDone = false; private String shapeFile; private SimpleFeatureSource featureSource; private HashMap polygonCountMap = new HashMap(); private HashMap polyNameMap = new HashMap(); - + @Override public void run(Person person) { - + if(!this.initDone){ init(); } - + int nofPlans = person.getPlans().size(); - + for (int planId = 0; planId < nofPlans; planId++) { Plan plan = person.getPlans().get(planId); - + // search selected plan if (PersonUtils.isSelected(plan)) { - - // do something + + // do something for (PlanElement pEOne : plan.getPlanElements()) { if(pEOne instanceof Activity){ - - // check - actTypeOne in search area? - Activity actOne = (Activity) pEOne; + + // check - actTypeOne in search area? + Activity actOne = (Activity) pEOne; if(actOne.getType().equalsIgnoreCase(this.actTypeOne)){ // it is of type actTypeOne -> check coords - + if(actIsSituatedInGivenSearchArea(actOne)){ // act one ok, check type two; - + for (PlanElement pETwo : plan.getPlanElements()) { if(pETwo instanceof Activity){ - - Activity actTwo = (Activity) pETwo; + + Activity actTwo = (Activity) pETwo; if(actTwo.getType().equalsIgnoreCase(this.actTypeTwo)){ - - // act two ok - search corresponding shape + + // act two ok - search corresponding shape searchCorrespondingShape(actTwo); break; } - - } - } + + } + } break; - } - - } - + } + + } + } } - + } - } + } } public WorkHomeShapeCounter(Coord minXY, Coord maxXY, String actTypeOne, String actTypeTwo, String shapeFile){ @@ -130,14 +129,14 @@ public String toString() { } return strB.toString(); } - + public void toFile(String filename){ - + int numberOfActs = 0; for (Polygon poly : this.polygonCountMap.keySet()) { numberOfActs += this.polygonCountMap.get(poly).intValue(); } - + try { BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filename))); writer.write("#Results with " + this.actTypeOne + " act in minXY " + this.minXY + " maxXY " + this.maxXY + " and " + this.actTypeTwo + " act located in"); writer.newLine(); @@ -159,10 +158,10 @@ public void toFile(String filename){ * Put all polygon in an iterable list */ private void init() { - + try { - this.featureSource = ShapeFileReader.readDataFile(this.shapeFile); - + this.featureSource = GeoFileReader.readDataFile(this.shapeFile); + SimpleFeatureIterator fIt = this.featureSource.getFeatures().features(); while (fIt.hasNext()) { SimpleFeature ft = fIt.next(); @@ -174,13 +173,13 @@ private void init() { this.polyNameMap.put(poly, (String) ft.getAttribute("Bezirk")); } } - } - + } + } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - + this.initDone = true; } @@ -189,8 +188,8 @@ private boolean actIsSituatedInGivenSearchArea(Activity act) { if(this.minXY.getY() > act.getCoord().getY()){ return false;} if(this.maxXY.getX() < act.getCoord().getX()){ return false;} if(this.maxXY.getY() < act.getCoord().getY()){ return false;} - - return true; + + return true; } private void searchCorrespondingShape(Activity actTwo) { diff --git a/contribs/vsp/src/main/java/playground/vsp/andreas/utils/pop/FilterPopulationByShape.java b/contribs/vsp/src/main/java/playground/vsp/andreas/utils/pop/FilterPopulationByShape.java index 5b4ada222e5..63fede8cee6 100644 --- a/contribs/vsp/src/main/java/playground/vsp/andreas/utils/pop/FilterPopulationByShape.java +++ b/contribs/vsp/src/main/java/playground/vsp/andreas/utils/pop/FilterPopulationByShape.java @@ -52,53 +52,53 @@ import org.matsim.core.population.io.StreamingPopulationWriter; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; /** * Filters a given Population by a given shape - includes all routed modes - * + * * @author aneumann * */ public class FilterPopulationByShape implements LinkEnterEventHandler, PersonEntersVehicleEventHandler, PersonLeavesVehicleEventHandler{ - + private final static Logger log = LogManager.getLogger(FilterPopulationByShape.class); private GeometryFactory factory; private Geometry areaToExclude; private Geometry areaToInclude; private TreeSet includeLinks; private TreeSet agentsToKeep; - + private HashMap> vehId2AgentIdsMap; - + public FilterPopulationByShape(String netFile, String popInFile, String eventsFile, String areaShapeFile, String popOutFile){ Gbl.startMeasurement(); Gbl.printMemoryUsage(); - + log.info("Network: " + netFile); log.info("Population: " + popInFile); log.info("Events: " + eventsFile); log.info("Shape: " + areaShapeFile); log.info("Population out: " + popOutFile); - + Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig()); sc.getConfig().network().setInputFile(netFile); ScenarioUtils.loadScenario(sc); - + this.factory = new GeometryFactory(); this.areaToExclude = this.factory.buildGeometry(new ArrayList()); this.createServiceAreaShp(areaShapeFile); this.includeLinks = new TreeSet(); - - log.info(sc.getNetwork().getLinks().values().size() + " links in given network"); + + log.info(sc.getNetwork().getLinks().values().size() + " links in given network"); for (Link link : sc.getNetwork().getLinks().values()) { if (this.linkToNodeInServiceArea(link)) { this.includeLinks.add(link.getId().toString()); } - } + } log.info(this.includeLinks.size() + " links in area of interest"); - + this.agentsToKeep = new TreeSet(); this.vehId2AgentIdsMap = new HashMap>(); EventsManager eventsManager = EventsUtils.createEventsManager(); @@ -108,17 +108,17 @@ public FilterPopulationByShape(String netFile, String popInFile, String eventsFi log.info("Found " + this.agentsToKeep.size() + " agent ids to keep."); Gbl.printMemoryUsage(); Gbl.printElapsedTime(); - + sc.getConfig().plans().setInputFile(popInFile); Population pop = (Population) sc.getPopulation(); StreamingDeprecated.setIsStreaming(pop, true); PopulationReader popReader = new PopulationReader(sc); StreamingPopulationWriter popWriter = new StreamingPopulationWriter(); popWriter.startStreaming(popOutFile); - + StreamingDeprecated.addAlgorithm(pop, new PersonIdFilter(this.agentsToKeep, popWriter)); Gbl.printMemoryUsage(); - + popReader.readFile(popInFile); PopulationUtils.printPlansCount(pop) ; popWriter.closeStreaming(); @@ -129,7 +129,7 @@ public FilterPopulationByShape(String netFile, String popInFile, String eventsFi @Override public void reset(int iteration) { // TODO Auto-generated method stub - + } @Override @@ -138,7 +138,7 @@ public void handleEvent(LinkEnterEvent event) { // link not of interest return; } - + if (this.vehId2AgentIdsMap.get(event.getVehicleId()) == null) { // it's a private car this.agentsToKeep.add(event.getDriverId()); @@ -150,7 +150,7 @@ public void handleEvent(LinkEnterEvent event) { @Override public void handleEvent(PersonLeavesVehicleEvent event) { - this.vehId2AgentIdsMap.get(event.getVehicleId()).remove(event.getPersonId()); + this.vehId2AgentIdsMap.get(event.getVehicleId()).remove(event.getPersonId()); } @Override @@ -158,8 +158,8 @@ public void handleEvent(PersonEntersVehicleEvent event) { if (this.vehId2AgentIdsMap.get(event.getVehicleId()) == null) { this.vehId2AgentIdsMap.put(event.getVehicleId(), new TreeSet()); } - - this.vehId2AgentIdsMap.get(event.getVehicleId()).add(event.getPersonId()); + + this.vehId2AgentIdsMap.get(event.getVehicleId()).add(event.getPersonId()); } private boolean linkToNodeInServiceArea(Link link) { @@ -172,12 +172,12 @@ private boolean linkToNodeInServiceArea(Link link) { } return false; } - + private void createServiceAreaShp(String serviceAreaFile) { - Collection features = ShapeFileReader.getAllFeatures(serviceAreaFile); + Collection features = GeoFileReader.getAllFeatures(serviceAreaFile); Collection include = new ArrayList(); Collection exclude = new ArrayList(); - + for (SimpleFeature f: features) { boolean incl = true; Geometry g = null; @@ -188,7 +188,7 @@ private void createServiceAreaShp(String serviceAreaFile) { g = (Geometry) o; } // TODO use a better way to get the attributes, maybe directly per index. - // Now the last attribute is used per default... + // Now the last attribute is used per default... else if (o instanceof String){ incl = Boolean.parseBoolean((String) o); } @@ -201,12 +201,12 @@ else if (o instanceof String){ } } } - this.areaToInclude = this.factory.createGeometryCollection( + this.areaToInclude = this.factory.createGeometryCollection( include.toArray(new Geometry[include.size()])).buffer(0); - this.areaToExclude = this.factory.createGeometryCollection( + this.areaToExclude = this.factory.createGeometryCollection( exclude.toArray(new Geometry[exclude.size()])).buffer(0); } - + public static void main(String[] args) { // Charlottenburg // String netFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/network.final.xml.gz"; @@ -214,22 +214,22 @@ public static void main(String[] args) { // String eventsFile = "e:/berlin-bvg09_runs/bvg.run189.10pct/ITERS/it.100/bvg.run189.10pct.100.events.xml.gz"; // String areaShapeFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/area/simulated_area.shp"; // String popOutFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/plans/bvg.run189.10pct.100.plans.selected_movedToTXL_diluted.xml.gz"; - + // Spandau // String netFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/network.final.xml.gz"; // String popInFile = "e:/berlin-bvg09_runs/bvg.run192.100pct/ITERS/it.100/bvg.run192.100pct.100.plans.selected.xml.gz"; // String eventsFile = "e:/berlin-bvg09_runs/bvg.run192.100pct/ITERS/it.100/bvg.run192.100pct.100.events.xml.gz"; // String areaShapeFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/area/spandau_area.shp"; // String popOutFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/plans/bvg.run192.100pct.100.plans.selected_spandau.xml.gz"; - + // Spandau neu String netFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/network.final.xml.gz"; String popInFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/plans/bvg.run189.10pct.100.plans.selected_movedToTXL.xml.gz"; String eventsFile = "e:/berlin-bvg09_runs/bvg.run189.10pct/ITERS/it.100/bvg.run189.10pct.100.events.xml.gz"; String areaShapeFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/area/spandau_area.shp"; String popOutFile = "e:/_shared-svn/andreas/paratransit/input/trb_2012/plans/bvg.run189.10pct.100.plans.selected_movedToTXL_spandau.xml.gz"; - + FilterPopulationByShape filter = new FilterPopulationByShape(netFile, popInFile, eventsFile, areaShapeFile, popOutFile); } - + } diff --git a/contribs/vsp/src/main/java/playground/vsp/andreas/utils/pt/transitSchedule2shape/DaShapeWriter.java b/contribs/vsp/src/main/java/playground/vsp/andreas/utils/pt/transitSchedule2shape/DaShapeWriter.java index 0a8aa167350..600ff620232 100644 --- a/contribs/vsp/src/main/java/playground/vsp/andreas/utils/pt/transitSchedule2shape/DaShapeWriter.java +++ b/contribs/vsp/src/main/java/playground/vsp/andreas/utils/pt/transitSchedule2shape/DaShapeWriter.java @@ -43,7 +43,7 @@ import org.matsim.api.core.v01.network.Node; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.pt.transitSchedule.api.TransitRouteStop; @@ -52,7 +52,7 @@ import org.opengis.feature.simple.SimpleFeature; /** - * + * * @author droeder * */ @@ -60,9 +60,9 @@ public class DaShapeWriter { private static final Logger log = LogManager.getLogger(DaShapeWriter.class); private static SimpleFeatureBuilder builder; - + private static GeometryFactory geometryFactory = new GeometryFactory(); - + public static void writeLinks2Shape(String fileName, Map links, Map> attributes, String targetCoordinateSystem){ if(attributes == null){ initLineFeatureType("links", null, true, targetCoordinateSystem); @@ -75,12 +75,12 @@ public static void writeLinks2Shape(String fileName, Map lin write(createLinkFeatures(links, attributes), fileName); } - + public static void writeNodes2Shape(String fileName, Map nodes, String targetCoordinateSystem){ initPointFeatureType("nodes", null, targetCoordinateSystem); write(createNodeFeatures(nodes), fileName); } - + public static void writeDefaultPoints2Shape(String fileName, String name, Map points, Map> attributes, String targetCoordinateSystem){ if(attributes == null){ initPointFeatureType(name, null, targetCoordinateSystem); @@ -92,10 +92,10 @@ public static void writeDefaultPoints2Shape(String fileName, String name, Map> points, Map> attributes, String targetCoordinateSystem){ for (SortedMap m : attributes.values()){ initLineFeatureType("distance", m, targetCoordinateSystem); break; } - + write(createPointDistanceFeatures(points,attributes), fileName); } /** @@ -140,7 +140,7 @@ public static void writePointDist2Shape (String fileName, Map> lineStrings, Map> attributes, String targetCoordinateSystem){ - + if(attributes == null){ initLineFeatureType(name, null, targetCoordinateSystem); }else{ @@ -149,10 +149,10 @@ public static void writeDefaultLineString2Shape(String fileName, String name, M break; } } - + write(createDefaultLineStringFeature(lineStrings, attributes), fileName); } - + public static void writeDefaultLineStrings2Shape(String fileName, String name, Map> lineStrings, String targetCoordinateSystem){ Map> map = new HashMap>(); SortedMap ls; @@ -165,20 +165,20 @@ public static void writeDefaultLineStrings2Shape(String fileName, String name, M } writeDefaultLineString2Shape(fileName, name, map, null, targetCoordinateSystem); } - + private static void write(Collection features, String shapeFileOutName){ if(features.isEmpty()){ log.error("can not write " + shapeFileOutName + ", because featurelist is empty..."); }else{ - ShapeFileWriter.writeGeometries(features, shapeFileOutName); - log.info(shapeFileOutName + " written!"); + GeoFileWriter.writeGeometries(features, shapeFileOutName); + log.info(shapeFileOutName + " written!"); } } - + private static void initLineFeatureType(String name, SortedMap attributes, String targetCoordinateSystem){ initLineFeatureType(name, attributes, false, targetCoordinateSystem); } - + private static void initLineFeatureType(String name, SortedMap attributes, boolean links, String targetCoordinateSystem) { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.setName(name); @@ -198,7 +198,7 @@ private static void initLineFeatureType(String name, SortedMap a builder = new SimpleFeatureBuilder(b.buildFeatureType()); } - + private static void initPointFeatureType(String name, SortedMap attributes, String targetCoordinateSystem){ SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); b.setName(name); @@ -210,15 +210,15 @@ private static void initPointFeatureType(String name, SortedMap b.add(e.getKey(), e.getValue().getClass()); } } - + builder = new SimpleFeatureBuilder(b.buildFeatureType()); } - + private static Collection createRouteFeatures(TransitSchedule schedule, Collection lines2write, Map> attributes){ Collection features = new ArrayList(); SimpleFeature feature; Coordinate[] coord; - + for (TransitLine line : schedule.getTransitLines().values()){ if( (lines2write == null) || lines2write.contains(line.getId())){ for(TransitRoute route : line.getRoutes().values()){ @@ -239,7 +239,7 @@ private static Collection createRouteFeatures(TransitSchedule sch } return features; } - + private static Collection createLinkFeatures(Map links, Map> attributes) { Collection features = new ArrayList(); SimpleFeature feature; @@ -261,12 +261,12 @@ private static Collection createLinkFeatures(Map createPointDistanceFeatures(Map> points, Map> attributes){ Collection features = new ArrayList(); SimpleFeature feature; Coordinate[] coord; - + for(Entry> e : points.entrySet()) { coord = new Coordinate[2]; coord[0] = MGC.coord2Coordinate(e.getValue().getFirst()); @@ -274,14 +274,14 @@ private static Collection createPointDistanceFeatures(Map createStopFeatures(Map stops, Collection stops2write){ Collection features = new ArrayList(); SimpleFeature feature; - + for(TransitStopFacility stop : stops.values()){ if((stops2write == null) || stops2write.contains(stop.getId())){ feature = getPointFeature(stop.getCoord(), stop.getId().toString(), null); @@ -290,22 +290,22 @@ private static Collection createStopFeatures(Map createNodeFeatures(Map nodes){ Collection features = new ArrayList(); SimpleFeature feature; - + for(Node n : nodes.values()){ feature = getPointFeature(n.getCoord(), n.getId().toString(), null); features.add(feature); } return features; } - + private static Collection createDefaultPointFeature(Map points, Map> attributes){ Collection features = new ArrayList(); SimpleFeature feature; - + for(Entry e: points.entrySet()){ if(attributes == null){ feature = getPointFeature(e.getValue(), e.getKey(), null); @@ -314,15 +314,15 @@ private static Collection createDefaultPointFeature(Map createDefaultLineStringFeature(Map> lineStrings, Map> attributes) { Collection features = new ArrayList(); SimpleFeature feature; Coordinate[] coord; - + for(Entry> points : lineStrings.entrySet()){ if (points.getValue().size()<2){ log.error(points.getKey() + ": not enough points for a lineString. Need at least 2 points!"); @@ -336,20 +336,20 @@ private static Collection createDefaultLineStringFeature(Map attributes) { LineString s = geometryFactory.createLineString(c); Object[] attribs ; @@ -361,21 +361,21 @@ private static SimpleFeature getLineStringFeature(CoordinateArraySequence c, Str attribs[0] = s; attribs[1] = name; Integer count = 2; - + if(!(attributes == null)){ for(Object o : attributes.values()){ attribs[count] = o; count++; } } - + try { return builder.buildFeature(name, attribs); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } } - + private static SimpleFeature getPointFeature(Coord coord, String id, SortedMap attributes) { Point p = geometryFactory.createPoint(MGC.coord2Coordinate(coord)); Object [] attribs ; @@ -387,7 +387,7 @@ private static SimpleFeature getPointFeature(Coord coord, String id, SortedMap sha for (String shapeFile : shapeFileToFeatureKey.keySet()) { String key = shapeFileToFeatureKey.get(shapeFile); LOG.info("Processing zone file " + shapeFile + " with feature key " + key); - Collection features = ShapeFileReader.getAllFeatures(shapeFile); + Collection features = GeoFileReader.getAllFeatures(shapeFile); for (SimpleFeature feature : features) { Geometry geometry = (Geometry) feature.getDefaultGeometry(); String shapeId = Cemdap2MatsimUtils.removeLeadingZeroFromString((String) feature.getAttribute(key)); @@ -105,7 +105,7 @@ public CORINELandCoverCoordsModifier(String matsimPlans, Map sha this.sameHomeActivity = sameHomeActivity; if (this.sameHomeActivity) LOG.info("Home activities for a person will be at the same location."); - + this.homeActivityPrefix = homeActivityPrefix; } @@ -157,7 +157,7 @@ public static void main(String[] args) { public void process() { LOG.info("Start processing, this may take a while ... "); - + int personCounter = 0; for (Person person : population.getPersons().values()) { Coord homeLocationCoord = null; @@ -166,7 +166,7 @@ public void process() { if (personCounter%1000 == 0) { LOG.info("Person #" + personCounter); } - + for (Plan plan : person.getPlans()) { for (PlanElement planElement : plan.getPlanElements()) { if (planElement instanceof Activity) { diff --git a/contribs/vsp/src/main/java/playground/vsp/corineLandcover/CorineLandCoverData.java b/contribs/vsp/src/main/java/playground/vsp/corineLandcover/CorineLandCoverData.java index f9f10f9bcae..d8b0584a210 100644 --- a/contribs/vsp/src/main/java/playground/vsp/corineLandcover/CorineLandCoverData.java +++ b/contribs/vsp/src/main/java/playground/vsp/corineLandcover/CorineLandCoverData.java @@ -31,7 +31,7 @@ import org.locationtech.jts.geom.Point; import org.matsim.api.core.v01.Coord; import org.matsim.core.gbl.Gbl; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; /** @@ -57,7 +57,7 @@ public class CorineLandCoverData { public CorineLandCoverData( String corineLandCoverShapeFile, boolean simplifyGeometries, boolean combiningGeom) { LOGGER.info("Reading CORINE landcover shape file . . ."); - Collection landCoverFeatures = ShapeFileReader.getAllFeatures(corineLandCoverShapeFile); + Collection landCoverFeatures = GeoFileReader.getAllFeatures(corineLandCoverShapeFile); this.simplifyGeometries = simplifyGeometries; if (this.simplifyGeometries) LOGGER.warn("Geometries will be simplified such that number of vertices in each geometry is less than 1000. " + diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/CommuterGenerator.java b/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/CommuterGenerator.java index 675e4edaf88..41c2466c84d 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/CommuterGenerator.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/CommuterGenerator.java @@ -33,7 +33,7 @@ import org.matsim.core.utils.collections.Tuple; 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.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -42,11 +42,11 @@ * @author dgrether */ public class CommuterGenerator { - + private static final Logger log = LogManager.getLogger(CommuterGenerator.class); - + public static void main(String[] args) throws Exception { - + String baseDir = "../../../shared-svn/projects/cottbus/data/scenarios/cottbus_scenario/"; String networkFile = baseDir + "network_wgs84_utm33n.xml.gz"; boolean useLanduse = true; @@ -54,7 +54,7 @@ public static void main(String[] args) throws Exception { // String shapesOutputDirectory = populationOutputDirectory + "shapes_all_modes/"; String shapesOutputDirectory = populationOutputDirectory + "shapes/"; - + // String populationOutputFile = populationOutputDirectory + "commuter_population_wgs84_utm33n.xml.gz"; String populationOutputFile = populationOutputDirectory + "commuter_population_wgs84_utm33n_car_only.xml.gz"; OutputDirectoryLogging.initLoggingWithOutputDirectory(populationOutputDirectory); @@ -63,24 +63,24 @@ public static void main(String[] args) throws Exception { if (! shapes.exists() ) { shapes.mkdir(); } - + Config config1 = ConfigUtils.createConfig(); config1.network().setInputFile(networkFile); Scenario sc = ScenarioUtils.loadScenario(config1); - + CommuterDataReader cdr = new CommuterDataReader(); cdr.addFilterRange(12071000); cdr.addFilter("12052000"); //12052000 == cottbus stadt cdr.readFile("../../../shared-svn/studies/countries/de/pendler_nach_gemeinden/brandenburg_einpendler.csv"); // cdr.getCommuterRelations().add(new CommuterDataElement("12052000", "12052000", 1000)); - + String gemeindenBrandenburgShapeFile = "../../../shared-svn/studies/countries/de/brandenburg_gemeinde_kreisgrenzen/gemeinden/dlm_gemeinden.shp"; - ShapeFileReader gemeindenReader = new ShapeFileReader(); + GeoFileReader gemeindenReader = new GeoFileReader(); Collection gemeindenFeatures = gemeindenReader.readFileAndInitialize(gemeindenBrandenburgShapeFile); - - - - CommuterDemandWriter cdw = new CommuterDemandWriter(gemeindenFeatures, gemeindenReader.getCoordinateSystem(), + + + + CommuterDemandWriter cdw = new CommuterDemandWriter(gemeindenFeatures, gemeindenReader.getCoordinateSystem(), cdr.getCommuterRelations(), MGC.getCRS(TransformationFactory.WGS84_UTM33N)); //landuse if (useLanduse){ @@ -90,31 +90,31 @@ public static void main(String[] args) throws Exception { cdw.addLanduse("home", homeLanduse); cdw.addLanduse("work", workLanduse); } -// +// // cdw.setScalefactor(1.0); // all modes cdw.setScalefactor(0.55); //car mode share // cdw.setScalefactor(0.1); //testing - + cdw.computeDemand(sc); PopulationWriter populationWriter = new PopulationWriter(sc.getPopulation(), sc.getNetwork()); populationWriter.write(populationOutputFile); log.info("population written to " + populationOutputFile); - + //write some test output Config config = ConfigUtils.createConfig(); config.network().setInputFile(networkFile); config.plans().setInputFile(populationOutputFile); Scenario baseScenario = ScenarioUtils.loadScenario(config); - + String shapeFilename = shapesOutputDirectory + "commuter_population_home.shp"; new DgPopulation2ShapeWriter(baseScenario.getPopulation(), MGC.getCRS(TransformationFactory.WGS84_UTM33N)) .write("home", shapeFilename, MGC.getCRS(TransformationFactory.WGS84_UTM33N)); shapeFilename = shapesOutputDirectory + "commuter_population_work.shp"; new DgPopulation2ShapeWriter(baseScenario.getPopulation(), MGC.getCRS(TransformationFactory.WGS84_UTM33N)) .write("work", shapeFilename, MGC.getCRS(TransformationFactory.WGS84_UTM33N)); - + log.info("done!"); OutputDirectoryLogging.closeOutputDirLogging(); } diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/DgLanduseReader.java b/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/DgLanduseReader.java index c500ee81af4..6a7b47969d3 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/DgLanduseReader.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/DgLanduseReader.java @@ -23,7 +23,7 @@ import java.util.HashSet; import org.matsim.core.utils.collections.Tuple; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -33,9 +33,9 @@ * */ public class DgLanduseReader { - + public static final String BASE_DIR = "../../../shared-svn/studies/countries/de/berlin_brandenburg_corine_landcover/shapefiles/"; - + private static final String STADTGEFUEGE_KONTINUIERLICH = BASE_DIR + "clc06_c111.shp"; private static final String STADTGEFUEGE_NICHT_KONTINUIERLICH = BASE_DIR + "clc06_c112.shp"; private static final String INDUSTRIE_GEWERBEGEBIETE = BASE_DIR + "clc06_c121.shp"; @@ -45,33 +45,33 @@ public class DgLanduseReader { // private static final String MINERALE_ABBAUSTAETTEN = BASE_DIR + "clc06_c131.shp"; private static final String DEPONIEN = BASE_DIR + "clc06_c132.shp"; private static final String BAUSTELLEN = BASE_DIR + "clc06_c133.shp"; - - + + private static final String[] landuse_files_home = {STADTGEFUEGE_KONTINUIERLICH, STADTGEFUEGE_NICHT_KONTINUIERLICH}; // private static final String[] landuse_files_home = {STADTGEFUEGE_NICHT_KONTINUIERLICH}; - - private static final String[] landuse_files_work = {STADTGEFUEGE_KONTINUIERLICH, + + private static final String[] landuse_files_work = {STADTGEFUEGE_KONTINUIERLICH, STADTGEFUEGE_NICHT_KONTINUIERLICH, INDUSTRIE_GEWERBEGEBIETE, STRASSEN_SCHIENENNETZE_GEBAUEDE, HAFENGEBIET, FLUGHAEFEN, DEPONIEN, BAUSTELLEN - /* skip mines because they cause disproportional many work places and, thus, to much traffic in their region */ + /* skip mines because they cause disproportional many work places and, thus, to much traffic in their region */ // , MINERALE_ABBAUSTAETTEN }; // private static final String[] landuse_files_work = {INDUSTRIE_GEWERBEGEBIETE}; - + public Tuple,CoordinateReferenceSystem> readLanduseDataHome(){ return this.readLanduseData(landuse_files_home); } - + public Tuple,CoordinateReferenceSystem> readLanduseDataWork(){ return this.readLanduseData(landuse_files_work); } - + private Tuple, CoordinateReferenceSystem> readLanduseData(String[] shapefiles){ - ShapeFileReader shapeReader = new ShapeFileReader(); + GeoFileReader shapeReader = new GeoFileReader(); Collection allFeatures = new HashSet(); Collection currentFeatures = null; for (String filename : shapefiles){ diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/DgPopulation2ShapeWriter.java b/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/DgPopulation2ShapeWriter.java index 9c8609b2540..943f51c177f 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/DgPopulation2ShapeWriter.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/commuterDemandCottbus/DgPopulation2ShapeWriter.java @@ -32,7 +32,7 @@ import org.matsim.api.core.v01.population.Population; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.gis.PointFeatureFactory; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; @@ -44,7 +44,7 @@ */ public class DgPopulation2ShapeWriter { - + private Population pop; private CoordinateReferenceSystem popCrs; @@ -53,7 +53,7 @@ public DgPopulation2ShapeWriter(Population pop, CoordinateReferenceSystem crs){ this.pop = pop; this.popCrs = crs; } - + public void write(String activityType, String filename, CoordinateReferenceSystem targetCrs){ try { MathTransform transformation = CRS.findMathTransform(this.popCrs, targetCrs, true); @@ -66,7 +66,7 @@ public void write(String activityType, String filename, CoordinateReferenceSyste addAttribute("start_time", Double.class). addAttribute("end_time", Double.class). create(); - + List features = new ArrayList(); SimpleFeature f = null; for (Person p : this.pop.getPersons().values()){ @@ -75,7 +75,7 @@ public void write(String activityType, String filename, CoordinateReferenceSyste if (pe instanceof Activity){ Activity activity = (Activity) pe; if (activity.getType().compareTo(activityType) == 0){ - + String id = p.getId().toString(); String type = activity.getType(); Double startTime = activity.getStartTime().seconds(); @@ -83,20 +83,20 @@ public void write(String activityType, String filename, CoordinateReferenceSyste Coordinate actCoordinate = MGC.coord2Coordinate(activity.getCoord()); actCoordinate = JTS.transform(actCoordinate, actCoordinate, transformation); - + f = factory.createPoint(actCoordinate, new Object[] {id, type, startTime, endTime}, null); features.add(f); } } } } - - ShapeFileWriter.writeGeometries(features, filename); + + GeoFileWriter.writeGeometries(features, filename); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } - + } - + } diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/GVPlanReader.java b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/GVPlanReader.java index 9f162db4bd3..113c347994a 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/GVPlanReader.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/GVPlanReader.java @@ -32,25 +32,25 @@ import org.matsim.core.scenario.MutableScenario; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.transformations.TransformationFactory; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; import playground.vsp.pipeline.PopulationReaderTask; import playground.vsp.pipeline.PopulationWriterTask; public class GVPlanReader { - - + + private static final String GV_NETWORK_FILENAME = "/Users/michaelzilske/workspace/prognose_2025/demand/network_cleaned_wgs84.xml.gz"; - + private static final String NETWORK_FILENAME = "/Users/michaelzilske/osm/motorway_germany.xml"; - + private static final String GV_PLANS = "/Users/michaelzilske/workspace/run1061/1061.output_plans.xml.gz"; - + private static final String FILTER_FILENAME = "/Users/michaelzilske/workspace/prognose_2025/demand/filter.shp"; - + private static final String LANDKREISE = "/Users/michaelzilske/workspace/prognose_2025/osm_zellen/landkreise.shp"; - + private static boolean isCoordInShape(Coord linkCoord, Collection features, GeometryFactory factory) { boolean found = false; Geometry geo = factory.createPoint(new Coordinate(linkCoord.getX(), linkCoord.getY())); @@ -62,21 +62,21 @@ private static boolean isCoordInShape(Coord linkCoord, Collection } return found; } - + public static void main(String[] args) { Scenario gvNetwork = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); new MatsimNetworkReader(gvNetwork.getNetwork()).readFile(GV_NETWORK_FILENAME); Scenario osmNetwork = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); new MatsimNetworkReader(osmNetwork.getNetwork()).readFile(NETWORK_FILENAME); Collection featuresInShape; - featuresInShape = new ShapeFileReader().readFileAndInitialize(FILTER_FILENAME); - + featuresInShape = new GeoFileReader().readFileAndInitialize(FILTER_FILENAME); + PopulationReaderTask populationReaderTask = new PopulationReaderTask(GV_PLANS, gvNetwork.getNetwork()); - + PersonDereferencerTask personDereferencerTask = new PersonDereferencerTask(); - + PersonGeoTransformatorTask personGeoTransformatorTask = new PersonGeoTransformatorTask(TransformationFactory.WGS84, TransformationFactory.DHDN_GK4); - + PersonRouterFilter personRouterFilter = new PersonRouterFilter(osmNetwork.getNetwork()); GeometryFactory factory = new GeometryFactory(); for (Node node : osmNetwork.getNetwork().getNodes().values()) { @@ -84,18 +84,18 @@ public static void main(String[] args) { personRouterFilter.getInterestingNodeIds().add(node.getId()); } } - + PersonVerschmiererTask personVerschmiererTask = new PersonVerschmiererTask(LANDKREISE); - + PopulationWriterTask populationWriterTask = new PopulationWriterTask("/Users/michaelzilske/workspace/prognose_2025/demand/naechster_versuch_gv.xml", gvNetwork.getNetwork()); - + populationReaderTask.setSink(personDereferencerTask); personDereferencerTask.setSink(personGeoTransformatorTask); personGeoTransformatorTask.setSink(personRouterFilter); personRouterFilter.setSink(personVerschmiererTask); personVerschmiererTask.setSink(populationWriterTask); - + populationReaderTask.run(); } - + } diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/PendlerMatrixReader.java b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/PendlerMatrixReader.java index 20126b4a8ed..1d53d1a7aa4 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/PendlerMatrixReader.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/PendlerMatrixReader.java @@ -37,7 +37,7 @@ import org.matsim.core.scenario.MutableScenario; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.tabularFileParser.TabularFileHandler; import org.matsim.core.utils.io.tabularFileParser.TabularFileParser; import org.matsim.core.utils.io.tabularFileParser.TabularFileParserConfig; @@ -80,7 +80,7 @@ public void run() { } private void readShape() { - Collection landkreise = ShapeFileReader.getAllFeatures(this.shapeFile); + Collection landkreise = GeoFileReader.getAllFeatures(this.shapeFile); ActivityFacilitiesFactory factory = ((MutableScenario)this.sc).getActivityFacilities().getFactory(); for (SimpleFeature landkreis : landkreise) { Integer gemeindeschluessel = Integer.parseInt((String) landkreis.getAttribute("gemeindesc")); diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/Verschmierer.java b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/Verschmierer.java index 183e69f3e48..4ccba3644f7 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/Verschmierer.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/pendlermatrix/Verschmierer.java @@ -29,25 +29,25 @@ import org.locationtech.jts.geom.Point; import org.matsim.api.core.v01.Coord; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; public class Verschmierer { - + private String filename; - + private Map zones = new HashMap(); private Random random = new Random(); - + public Verschmierer(String filename) { this.filename = filename; readShape(); } private void readShape() { - for (SimpleFeature landkreis : ShapeFileReader.getAllFeatures(filename)) { + for (SimpleFeature landkreis : GeoFileReader.getAllFeatures(filename)) { Integer gemeindeschluessel = Integer.parseInt((String) landkreis.getAttribute("gemeindesc")); zones.put(gemeindeschluessel, (Geometry) landkreis.getDefaultGeometry()); } @@ -72,7 +72,7 @@ public Coord shootIntoSameZoneOrLeaveInPlace(Coord coord) { return coord; } } - + private static Point getRandomPointInFeature(Random rnd, Geometry g) { Point p = null; double x, y; @@ -83,13 +83,13 @@ private static Point getRandomPointInFeature(Random rnd, Geometry g) { } while (!g.contains(p)); return p; } - + private Coord doShoot(Geometry zone) { Coord coord; Point point = getRandomPointInFeature(this.random , zone); coord = new Coord(point.getX(), point.getY()); return coord; } - - + + } diff --git a/contribs/vsp/src/main/java/playground/vsp/demandde/prognose2025/DemandMatrixReader.java b/contribs/vsp/src/main/java/playground/vsp/demandde/prognose2025/DemandMatrixReader.java index a59404b6d23..ba6cd54148d 100644 --- a/contribs/vsp/src/main/java/playground/vsp/demandde/prognose2025/DemandMatrixReader.java +++ b/contribs/vsp/src/main/java/playground/vsp/demandde/prognose2025/DemandMatrixReader.java @@ -41,7 +41,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.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.tabularFileParser.TabularFileHandler; import org.matsim.core.utils.io.tabularFileParser.TabularFileParser; import org.matsim.core.utils.io.tabularFileParser.TabularFileParserConfig; @@ -157,7 +157,7 @@ public void startRow(String[] row) { } private void readShape() { - Collection landkreise = ShapeFileReader.getAllFeatures(this.shapeFile); + Collection landkreise = GeoFileReader.getAllFeatures(this.shapeFile); final ActivityFacilitiesFactory factory = ((MutableScenario)this.sc).getActivityFacilities().getFactory(); for (SimpleFeature landkreis : landkreise) { Integer gemeindeschluessel = Integer.parseInt((String) landkreis.getAttribute("gemeindesc")); diff --git a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/SynPopCreator.java b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/SynPopCreator.java index bc8819bbdc9..3ec676d187d 100644 --- a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/SynPopCreator.java +++ b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/SynPopCreator.java @@ -39,7 +39,7 @@ import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.population.PopulationUtils; import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.IOUtils; import org.matsim.households.Household; import org.matsim.households.HouseholdImpl; @@ -53,12 +53,12 @@ /** * This class creates a full population of a study region (in Germany) based on the Zensus and the Pendlerstatistik. People are assigned * places or residence and with demographic attributes based on the Zensus and with commuter relations based on the Pendlerstatistik. - * + * * @author dziemke */ public class SynPopCreator { private static final Logger LOG = LogManager.getLogger(SynPopCreator.class); - + private static final Random random = MatsimRandom.getLocalInstance(); // Make sure that stream of random variables is reproducible. // Storage objects @@ -71,7 +71,7 @@ public class SynPopCreator { // Optional (links municipality ID to LOR/PLZ IDs in that municipality) private final Map> spatialRefinementZoneIds = new HashMap<>(); private List idsOfMunicipalitiesForSpatialRefinement; - + // Parameters private String outputBase; private List idsOfFederalStatesIncluded; @@ -93,7 +93,7 @@ public class SynPopCreator { private int allEmployees = 0; private int allPersons = 0; private int allStudents = 0; - + public static void main(String[] args) { // Input and output files @@ -104,11 +104,11 @@ public static void main(String[] args) { String[] commuterFilesOutgoing = {commuterFileOutgoing1, commuterFileOutgoing2, commuterFileOutgoing3, commuterFileOutgoing4}; String censusFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/input/zensus_2011/bevoelkerung/csv_Bevoelkerung/Zensus11_Datensatz_Bevoelkerung_BE_BB.csv"; String outputBase = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/cemdap_input/505/"; - + // Parameters int numberOfPlansPerPerson = 10; // Note: Set this higher to a value higher than 1 if spatial refinement is used. List idsOfFederalStatesIncluded = Arrays.asList("11", "12"); // 11=Berlin, 12=Brandenburg - + // Default ratios are used for cases where information is missing, which is the case for smaller municipalities. double defaultAdultsToEmployeesRatio = 1.23; // Calibrated based on sum value from Zensus 2011. double defaultCensusEmployeesToCommutersRatio = 2.5; // This is an assumption, oriented on observed values, deliberately chosen slightly too high. @@ -126,14 +126,14 @@ public static void main(String[] args) { demandGeneratorCensus.generateDemand(); } - - public SynPopCreator(String[] commuterFilesOutgoing, String censusFile, String outputBase, int numberOfPlansPerPerson, + + public SynPopCreator(String[] commuterFilesOutgoing, String censusFile, String outputBase, int numberOfPlansPerPerson, List idsOfFederalStatesIncluded, double defaultAdultsToEmployeesRatio, double defaultEmployeesToCommutersRatio) { LogToOutputSaver.setOutputDirectory(outputBase); - + this.outputBase = outputBase; this.numberOfPlansPerPerson = numberOfPlansPerPerson; - + this.idsOfFederalStatesIncluded = idsOfFederalStatesIncluded; this.idsOfFederalStatesIncluded.stream().forEach(e -> { if (e.length()!=2) throw new IllegalArgumentException("Length of the id for each federal state must be equal to 2. This is not the case for "+ e); @@ -141,7 +141,7 @@ public SynPopCreator(String[] commuterFilesOutgoing, String censusFile, String o this.defaultAdultsToEmployeesRatio = defaultAdultsToEmployeesRatio; this.defaultEmployeesToCommutersRatio = defaultEmployeesToCommutersRatio; - + this.population = ScenarioUtils.createScenario(ConfigUtils.createConfig()).getPopulation(); this.households = new HashMap<>(); @@ -158,7 +158,7 @@ public SynPopCreator(String[] commuterFilesOutgoing, String censusFile, String o } } - + public void generateDemand() { if (this.shapeFileForSpatialRefinement != null && this.refinementFeatureKeyInShapefile != null ) { this.idsOfMunicipalitiesForSpatialRefinement.stream().forEach(e->spatialRefinementZoneIds.put(e, new ArrayList<>())); @@ -173,7 +173,7 @@ public void generateDemand() { } int counter = 1; - + for (String munId : relationsMap.keySet()) { // Loop over municipalities from commuter file Map relationsFromMunicipality = relationsMap.get(munId); @@ -300,7 +300,7 @@ public void generateDemand() { LOG.warn("Total number of employees: " + this.allEmployees); LOG.warn("Total population: " + this.allPersons); LOG.warn("Total number of students: " + this.allStudents); - + // Write output files if (this.writeCemdapInputFiles) { writeCemdapHouseholdsFile(this.households, this.outputBase + "households.dat.gz"); @@ -318,8 +318,8 @@ public void generateDemand() { } } } - - + + private Population clonePopulationAndAdjustLocations(Population inputPopulation){ Population clonedPopulation = ScenarioUtils.createScenario(ConfigUtils.createConfig()).getPopulation(); for (Person person : inputPopulation.getPersons().values()) { @@ -334,7 +334,7 @@ private Population clonePopulationAndAdjustLocations(Population inputPopulation) for(CEMDAPPersonAttributes attributeKey : CEMDAPPersonAttributes.values()){ clonedPerson.getAttributes().putAttribute(attributeKey.toString(), person.getAttributes().getAttribute(attributeKey.toString())); } - + // change locations or use spatially refined location if ((boolean) person.getAttributes().getAttribute(CEMDAPPersonAttributes.employed.toString())) { String locationOfWork = (String) person.getAttributes().getAttribute(CEMDAPPersonAttributes.locationOfWork.toString()); @@ -363,7 +363,7 @@ private Population clonePopulationAndAdjustLocations(Population inputPopulation) } - private void createHouseholdsAndPersons(int counter, String municipalityId, int numberOfPersons, Gender gender, int lowerAgeBound, int upperAgeBound, + private void createHouseholdsAndPersons(int counter, String municipalityId, int numberOfPersons, Gender gender, int lowerAgeBound, int upperAgeBound, double adultsToEmployeesRatio, List commuterRelationList) { for (int i = 0; i < numberOfPersons; i++) { this.allPersons++; @@ -375,7 +375,7 @@ private void createHouseholdsAndPersons(int counter, String municipalityId, int household.getAttributes().putAttribute(CEMDAPHouseholdAttributes.homeTSZLocation.toString(), getExactLocation(municipalityId)); household.getAttributes().putAttribute(CEMDAPHouseholdAttributes.numberOfChildren.toString(), 0); // None, ignore them in this version household.getAttributes().putAttribute(CEMDAPHouseholdAttributes.householdStructure.toString(), 1); // 1 = single, no children - + Id personId = Id.create(householdId + "01", Person.class); // TODO Currently only singel-person households Person person = this.population.getFactory().createPerson(personId); @@ -385,14 +385,14 @@ private void createHouseholdsAndPersons(int counter, String municipalityId, int employed = getEmployed(adultsToEmployeesRatio); } person.getAttributes().putAttribute(CEMDAPPersonAttributes.employed.toString(), employed); - + boolean student = false; if (lowerAgeBound < 30 && upperAgeBound > 17 && !employed) { // Younger and older people are never a student, employed people neither student = true; // TODO quite simplistic assumption, which may be improved later allStudents++; - } + } person.getAttributes().putAttribute(CEMDAPPersonAttributes.student.toString(), student); - + if (employed) { allEmployees++; if (commuterRelationList.size() == 0) { // No relations left in list, which employee could choose from @@ -419,22 +419,22 @@ private void createHouseholdsAndPersons(int counter, String municipalityId, int } else { person.getAttributes().putAttribute(CEMDAPPersonAttributes.locationOfSchool.toString(), "-99"); } - + person.getAttributes().putAttribute(CEMDAPPersonAttributes.hasLicense.toString(), true); // for CEMDAP's "driversLicence" variable person.getAttributes().putAttribute(CEMDAPPersonAttributes.gender.toString(), gender.name()); // for CEMDAP's "female" variable person.getAttributes().putAttribute(CEMDAPPersonAttributes.age.toString(), getAgeInBounds(lowerAgeBound, upperAgeBound)); person.getAttributes().putAttribute(CEMDAPPersonAttributes.parent.toString(), false); - + this.population.addPerson(person); - + List> personIds = new ArrayList<>(); // Does in current implementation (only 1 p/hh) not make much sense personIds.add(personId); household.setMemberIds(personIds); this.households.put(householdId, household); } - } - - + } + + private static void scaleRelations(Map relationsFromMunicipality, int employeesMale, int employeesFemale, double defaultEmployeesToCommutersRatio) { // Count all commuters starting in the given municipality @@ -460,7 +460,7 @@ private static void scaleRelations(Map relationsFrom } commutersFemale += relation.getTripsFemale(); } - + // Compute ratios double employeesToCommutersMaleRatio; double employeesToCommutersFemaleRatio; @@ -474,7 +474,7 @@ private static void scaleRelations(Map relationsFrom } else { employeesToCommutersFemaleRatio = defaultEmployeesToCommutersRatio; } - + // Scale for (CommuterRelationV2 relation : relationsFromMunicipality.values()) { relation.setTripsMale((int) Math.ceil(relation.getTripsMale() * employeesToCommutersMaleRatio)); @@ -532,15 +532,15 @@ private String getSpatiallyRefinedZone(String municipalityId) { private static boolean getEmployed(double adultsToEmployeesRatio) { return random.nextDouble() * adultsToEmployeesRatio < 1; } - - + + private static int getAgeInBounds(int lowerBound, int upperBound) { return (int) (lowerBound + random.nextDouble() * (upperBound - lowerBound + 1)); } private Map> readShapeForSpatialRefinement() { - Collection features = ShapeFileReader.getAllFeatures(this.shapeFileForSpatialRefinement); + Collection features = GeoFileReader.getAllFeatures(this.shapeFileForSpatialRefinement); for (SimpleFeature feature : features) { String municipality; @@ -554,14 +554,14 @@ private Map> readShapeForSpatialRefinement() { } return spatialRefinementZoneIds; } - - + + private void writeCemdapHouseholdsFile(Map, Household> households, String fileName) { BufferedWriter bufferedWriterHouseholds = null; try { bufferedWriterHouseholds = IOUtils.getBufferedWriter(fileName); - + for (Household household : households.values()) { int householdId = Integer.parseInt(household.getId().toString()); int numberOfAdults = (Integer) household.getAttributes().getAttribute(CEMDAPHouseholdAttributes.numberOfAdults.toString()); @@ -579,7 +579,7 @@ private void writeCemdapHouseholdsFile(Map, Household> households, + "\t" + 0); bufferedWriterHouseholds.newLine(); } - + } catch (IOException ex) { ex.printStackTrace(); } finally { @@ -594,43 +594,43 @@ private void writeCemdapHouseholdsFile(Map, Household> households, } LOG.info("Households file " + fileName + " written."); } - - + + private void writeCemdapPersonsFile(Population population, String fileName) { BufferedWriter bufferedWriterPersons = null; try { bufferedWriterPersons = IOUtils.getBufferedWriter(fileName); - + for (Person person : population.getPersons().values()) { Attributes attr = person.getAttributes(); int householdId = Integer.parseInt(attr.getAttribute(CEMDAPPersonAttributes.householdId.toString()).toString()); int personId = Integer.parseInt(person.getId().toString()); - + int employed; if ((boolean) attr.getAttribute(CEMDAPPersonAttributes.employed.toString())) { employed = 1; } else { employed = 0; } - + int student; if ((boolean) attr.getAttribute(CEMDAPPersonAttributes.student.toString())) { student = 1; } else { student = 0; } - + int driversLicence; if ((boolean) attr.getAttribute(CEMDAPPersonAttributes.hasLicense.toString())) { driversLicence = 1; } else { driversLicence = 0; } - + int locationOfWork = Integer.parseInt(attr.getAttribute(CEMDAPPersonAttributes.locationOfWork.toString()).toString()); int locationOfSchool = Integer.parseInt(attr.getAttribute(CEMDAPPersonAttributes.locationOfSchool.toString()).toString()); - + int female; if (Gender.valueOf((String) attr.getAttribute(CEMDAPPersonAttributes.gender.toString())) == Gender.male) { female = 0; @@ -639,25 +639,25 @@ private void writeCemdapPersonsFile(Population population, String fileName) { } else { throw new IllegalArgumentException("Gender must either be male or female."); } - + int age = (Integer) attr.getAttribute(CEMDAPPersonAttributes.age.toString()); - + int parent; if ((boolean) attr.getAttribute(CEMDAPPersonAttributes.parent.toString())) { parent = 1; } else { parent = 0; } - + // Altogether this creates 59 columns = number in query file bufferedWriterPersons.write(householdId + "\t" + personId + "\t" + employed + "\t" + student + "\t" + driversLicence + "\t" + locationOfWork + "\t" + locationOfSchool - + "\t" + female + "\t" + age + "\t" + parent + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 - + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 - + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 - + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 - + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 - + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + + "\t" + female + "\t" + age + "\t" + parent + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 ); bufferedWriterPersons.newLine(); } @@ -676,26 +676,26 @@ private void writeCemdapPersonsFile(Population population, String fileName) { LOG.info("Persons file " + fileName + " written."); } - + private static void writeMatsimPlansFile(Population population, String fileName) { PopulationWriter popWriter = new PopulationWriter(population); popWriter.write(fileName); } - - + + // Getters and setters public Population getPopulation() { return this.population; } - + public void setShapeFileForSpatialRefinement(String shapeFileForSpatialRefinement) { this.shapeFileForSpatialRefinement = shapeFileForSpatialRefinement; } - + public void setIdsOfMunicipalitiesForSpatialRefinement(List idsOfMunicipalitiesForSpatialRefinement) { this.idsOfMunicipalitiesForSpatialRefinement = idsOfMunicipalitiesForSpatialRefinement; } - + public void setRefinementFeatureKeyInShapefile(String refinementFeatureKeyInShapefile) { this.refinementFeatureKeyInShapefile = refinementFeatureKeyInShapefile; } @@ -703,7 +703,7 @@ public void setRefinementFeatureKeyInShapefile(String refinementFeatureKeyInShap public void setMunicipalityFeatureKeyInShapefile(String municipalityFeatureKeyInShapefile) { this.municipalityFeatureKeyInShapefile = municipalityFeatureKeyInShapefile; } - + public void setWriteCemdapInputFiles(boolean writeCemdapInputFiles) { this.writeCemdapInputFiles = writeCemdapInputFiles; } @@ -715,15 +715,15 @@ public void setWriteMatsimPlanFiles(boolean writeMatsimPlanFiles) { public void setIncludeChildren(boolean includeChildren) { this.includeChildren = includeChildren; } - + public List getAllPopulations() { if (!memorizeAllPopulations) { throw new RuntimeException("The corresponding container object has not been filles. 'memorizeAllPopulations' needs to be activated."); } return this.allPopulations; } - + public void setMemorizeAllPopulations(boolean memorizeAllPopulations) { this.memorizeAllPopulations = memorizeAllPopulations; } -} \ No newline at end of file +} diff --git a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/SynPopCreatorChildren.java b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/SynPopCreatorChildren.java index 9e4d748ddf8..71cec77ea8a 100644 --- a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/SynPopCreatorChildren.java +++ b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/SynPopCreatorChildren.java @@ -29,7 +29,7 @@ import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.population.PopulationUtils; import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.utils.objectattributes.ObjectAttributes; import org.opengis.feature.simple.SimpleFeature; import playground.vsp.openberlinscenario.Gender; @@ -40,7 +40,7 @@ /** * This class creates a children-only population of a study region (in Germany) based on the Zensus and the Pendlerstatistik. * Only meant as as supplement ot an already existing adults-only population. - * + * * @author dziemke */ public class SynPopCreatorChildren { @@ -91,14 +91,14 @@ public static void main(String[] args) { public SynPopCreatorChildren(String censusFile, String outputBase, List idsOfFederalStatesIncluded) { LogToOutputSaver.setOutputDirectory(outputBase); - + this.outputBase = outputBase; this.idsOfFederalStatesIncluded = idsOfFederalStatesIncluded; this.idsOfFederalStatesIncluded.stream().forEach(e -> { if (e.length()!=2) throw new IllegalArgumentException("Length of the id for each federal state must be equal to 2. This is not the case for "+ e); }); - + this.population = ScenarioUtils.createScenario(ConfigUtils.createConfig()).getPopulation(); // Read census @@ -107,7 +107,7 @@ public SynPopCreatorChildren(String censusFile, String outputBase, List this.municipalityList = censusReader.getMunicipalityList(); } - + public void generateDemand() { if (this.shapeFileForSpatialRefinement != null && this.refinementFeatureKeyInShapefile != null ) { this.idsOfMunicipalitiesForSpatialRefinement.stream().forEach(e->spatialRefinementZoneIds.put(e, new ArrayList<>())); @@ -122,7 +122,7 @@ public void generateDemand() { } int counter = counterInit; - + for (String munId : municipalityList) { int pop0_2Male = (int) this.municipalities.getAttribute(munId, CensusAttributes.pop0_2Male.toString()); int pop3_5Male = (int) this.municipalities.getAttribute(munId, CensusAttributes.pop3_5Male.toString()); @@ -159,8 +159,8 @@ public void generateDemand() { Population adjustedPopulation = clonePopulationAndAdjustLocations(this.population); writeMatsimPlansFile(adjustedPopulation, this.outputBase + "plans_children.xml.gz"); } - - + + private Population clonePopulationAndAdjustLocations(Population inputPopulation){ Population clonedPopulation = ScenarioUtils.createScenario(ConfigUtils.createConfig()).getPopulation(); for (Person person : inputPopulation.getPersons().values()) { @@ -217,15 +217,15 @@ private String getSpatiallyRefinedZone(String municipalityId) { List spatiallyRefinedZones = this.spatialRefinementZoneIds.get(municipalityId); return spatiallyRefinedZones.get(random.nextInt(spatiallyRefinedZones.size())); } - - + + private static int getAgeInBounds(int lowerBound, int upperBound) { return (int) (lowerBound + random.nextDouble() * (upperBound - lowerBound + 1)); } private Map> readShapeForSpatialRefinement() { - Collection features = ShapeFileReader.getAllFeatures(this.shapeFileForSpatialRefinement); + Collection features = GeoFileReader.getAllFeatures(this.shapeFileForSpatialRefinement); for (SimpleFeature feature : features) { String municipality; @@ -245,21 +245,21 @@ private static void writeMatsimPlansFile(Population population, String fileName) PopulationWriter popWriter = new PopulationWriter(population); popWriter.write(fileName); } - - + + // Getters and setters public Population getPopulation() { return this.population; } - + public void setShapeFileForSpatialRefinement(String shapeFileForSpatialRefinement) { this.shapeFileForSpatialRefinement = shapeFileForSpatialRefinement; } - + public void setIdsOfMunicipalitiesForSpatialRefinement(List idsOfMunicipalitiesForSpatialRefinement) { this.idsOfMunicipalitiesForSpatialRefinement = idsOfMunicipalitiesForSpatialRefinement; } - + public void setRefinementFeatureKeyInShapefile(String refinementFeatureKeyInShapefile) { this.refinementFeatureKeyInShapefile = refinementFeatureKeyInShapefile; } @@ -271,4 +271,4 @@ public void setMunicipalityFeatureKeyInShapefile(String municipalityFeatureKeyIn public void setWriteMatsimPlanFiles(boolean writeMatsimPlanFiles) { this.writeMatsimPlanFiles = writeMatsimPlanFiles; } -} \ No newline at end of file +} diff --git a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/ZoneAndLOSGeneratorV2.java b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/ZoneAndLOSGeneratorV2.java index 3949dadde8f..c97a9b2cbf6 100644 --- a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/ZoneAndLOSGeneratorV2.java +++ b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/input/ZoneAndLOSGeneratorV2.java @@ -35,7 +35,7 @@ import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Geometry; import org.matsim.api.core.v01.Coord; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.IOUtils; import org.opengis.feature.simple.SimpleFeature; @@ -56,7 +56,7 @@ public class ZoneAndLOSGeneratorV2 { private final Map> zone2ZoneDistanceMap = new HashMap<>(); private final Map> zone2ZoneAdjacencyMap = new HashMap<>(); private final String outputBase; - + // Parameters // private double defaultIntraZoneDistance = 1.72; // in miles; equals 2.76km. private double defaultIntraZoneDistance = 1.; // new, lower value @@ -72,7 +72,7 @@ public class ZoneAndLOSGeneratorV2 { // spatial refinement. Amit Nov'17 private List zoneIdsForSpatialRefinement; // this is filled if shape file for spatial refinement is provided. private double defaultIntraZoneDistanceForSpatialRefinement = Double.NaN; - + public static void main(String[] args) { // Input and output String commuterFileBase = "../../shared-svn/studies/countries/de/open_berlin_scenario/input/pendlerstatistik_2009/"; @@ -86,7 +86,7 @@ public static void main(String[] args) { // Parameters String featureKeyInShapefile = "ID"; - + ZoneAndLOSGeneratorV2 zoneAndLOSGeneratorV2 = new ZoneAndLOSGeneratorV2(commuterFilesOutgoing, shapeFile, outputBase, featureKeyInShapefile); zoneAndLOSGeneratorV2.generateSupply(); } @@ -99,7 +99,7 @@ public ZoneAndLOSGeneratorV2(String[] commuterFilesOutgoing, String shapeFile, S readMunicipalities(commuterFilesOutgoing); readShape(shapeFile, featureKeyInShapefile); } - + public void generateSupply() { compareIdsInShapefileAndCommuterFiles(); computeAndStoreZone2ZoneDistances(); @@ -108,7 +108,7 @@ public void generateSupply() { writeLOSFile("losoffpkam", false); writeLOSFile("lospeakam", true); } - + private void readMunicipalities(String[] commuterFilesOutgoing) { for (String commuterFileOutgoing : commuterFilesOutgoing) { CommuterFileReaderV2 commuterFileReader = new CommuterFileReaderV2(commuterFileOutgoing, "\t"); @@ -118,7 +118,7 @@ private void readMunicipalities(String[] commuterFilesOutgoing) { } private void readShape(String shapeFile, String featureKeyInShapeFile) { - Collection features = ShapeFileReader.getAllFeatures(shapeFile); + Collection features = GeoFileReader.getAllFeatures(shapeFile); for (SimpleFeature feature : features) { String id = (String) feature.getAttribute(featureKeyInShapeFile); Geometry geometry = (Geometry) feature.getDefaultGeometry(); @@ -126,7 +126,7 @@ private void readShape(String shapeFile, String featureKeyInShapeFile) { this.zoneMap.put(id, geometry); } } - + private void compareIdsInShapefileAndCommuterFiles() { LOG.info("Municipality set has " + municipalities.size() + " elements."); LOG.info("Zones set has " + zones.size() + " elements."); @@ -141,7 +141,7 @@ private void compareIdsInShapefileAndCommuterFiles() { } } } - + private void computeAndStoreZone2ZoneDistances() { LOG.info("Start distance and adjacency computations."); LOG.info(this.zones.size() * this.zones.size() + " computations will be performed."); @@ -159,23 +159,23 @@ private void computeAndStoreZone2ZoneDistances() { int adjacent; double distance_mi; double temp = 0.; - + if (originId.equals(destinationId)) { // internal traffic inside zone distance_mi = getIntraZonalDistance(originId) * beelineDistanceFactor; adjacent = 0; } else { Geometry originGeometry = this.zoneMap.get(originId); Coord originCoord = new Coord(originGeometry.getCentroid().getCoordinate().x, originGeometry.getCentroid().getCoordinate().y); - + Geometry destinationGeometry = this.zoneMap.get(destinationId); Coord destinationCoord = new Coord(destinationGeometry.getCentroid().getCoordinate().x, destinationGeometry.getCentroid().getCoordinate().y); - + double distanceX_m = Math.abs(originCoord.getX() - destinationCoord.getX()); double distanceY_m = Math.abs(originCoord.getY() - destinationCoord.getY()); double distance_m = Math.sqrt(distanceX_m * distanceX_m + distanceY_m * distanceY_m); - + distance_mi = distance_m / 1609.344 * beelineDistanceFactor; // Convert from meters to miles - + if (originGeometry.touches(destinationGeometry)) { adjacent = 1; } else { @@ -192,7 +192,7 @@ private void computeAndStoreZone2ZoneDistances() { } LOG.info("Finised distance and adjacency computations."); } - + private void writeZone2ZoneFile() { BufferedWriter bufferedWriterZone2Zone = null; try { @@ -201,7 +201,7 @@ private void writeZone2ZoneFile() { for (String destinationId : this.zones) { double distance_mi = this.zone2ZoneDistanceMap.get(originId).get(destinationId); int adjacent = this.zone2ZoneAdjacencyMap.get(originId).get(destinationId); - + // 4 columns bufferedWriterZone2Zone.write(originId + "\t" + destinationId + "\t" + adjacent + "\t" + distance_mi); bufferedWriterZone2Zone.newLine(); @@ -223,7 +223,7 @@ private void writeZone2ZoneFile() { } System.out.println("Zone2Zone file written."); } - + private void writeZonesFile() { BufferedWriter bufferedWriterZones = null; try { @@ -232,7 +232,7 @@ private void writeZonesFile() { // 45 columns bufferedWriterZones.write(Integer.parseInt(zoneId) + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 - + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0); @@ -254,7 +254,7 @@ private void writeZonesFile() { } System.out.println("Zones file written."); } - + private void writeLOSFile(String filename, boolean isPeak) { BufferedWriter bufferedWriterLos = null; try { @@ -262,15 +262,15 @@ private void writeLOSFile(String filename, boolean isPeak) { double temp = 0.0; for (String originId : this.zones) { for (String destinationId : this.zones) { - + int inSameZone = 0; if (originId.equals(destinationId)) { inSameZone = 1; } - + double distance_mi = this.zone2ZoneDistanceMap.get(originId).get(destinationId); int adjacent = this.zone2ZoneAdjacencyMap.get(originId).get(destinationId); - + double driveAloneIVTT_min; if (isPeak) { driveAloneIVTT_min = distance_mi * durantionDistancePeakRatio_min_mile; @@ -279,13 +279,13 @@ private void writeLOSFile(String filename, boolean isPeak) { } temp = Math.round(driveAloneIVTT_min * 100); // Round to two decimal places driveAloneIVTT_min = temp / 100; - + double driveAloneCost_USD = distance_mi * costDistanceRatio_USD_mile; temp = Math.round(driveAloneCost_USD * 100); // Round to two decimal places driveAloneCost_USD = temp / 100; - + // 14 columns - bufferedWriterLos.write(Integer.parseInt(originId) + "\t" + Integer.parseInt(destinationId) + + bufferedWriterLos.write(Integer.parseInt(originId) + "\t" + Integer.parseInt(destinationId) + "\t" + inSameZone + "\t" + adjacent + "\t" + distance_mi + "\t" + driveAloneIVTT_min + "\t" + 3.1 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + 0 + "\t" + driveAloneCost_USD + "\t" + driveAloneIVTT_min + "\t" + driveAloneCost_USD); @@ -334,22 +334,22 @@ public void setDefaultIntraZoneDistanceForSpatialRefinement(double defaultIntraZ public void setBeelineDistanceFactor(double beelineDistanceFactor) { this.beelineDistanceFactor = beelineDistanceFactor; } - + public void setDurantionDistanceOffPeakRatio_min_mile(double durantionDistanceOffPeakRatio_min_mile) { this.durantionDistanceOffPeakRatio_min_mile = durantionDistanceOffPeakRatio_min_mile; } - + public void setDurantionDistancePeakRatio_min_mile(double durantionDistancePeakRatio_min_mile) { this.durantionDistancePeakRatio_min_mile = durantionDistancePeakRatio_min_mile; } - + public void setCostDistanceRatio_USD_mile(double costDistanceRatio_USD_mile) { this.costDistanceRatio_USD_mile = costDistanceRatio_USD_mile; } public void setShapeFileForRefinement(String shapeFileForSpatialRefinement, String featureKeyInShapeFileForRefinement){ LOG.info("Using spatial refinement..."); - this.zoneIdsForSpatialRefinement = ShapeFileReader + this.zoneIdsForSpatialRefinement = GeoFileReader .getAllFeatures(shapeFileForSpatialRefinement) .stream() .map(feature -> feature.getAttribute(featureKeyInShapeFileForRefinement).toString()) diff --git a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/output/CemdapOutput2MatsimPlansConverter.java b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/output/CemdapOutput2MatsimPlansConverter.java index 52ebcdd4f33..b8be4c3a3a8 100644 --- a/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/output/CemdapOutput2MatsimPlansConverter.java +++ b/contribs/vsp/src/main/java/playground/vsp/openberlinscenario/cemdap/output/CemdapOutput2MatsimPlansConverter.java @@ -40,7 +40,7 @@ import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.core.config.ConfigUtils; import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.utils.objectattributes.ObjectAttributes; import org.opengis.feature.simple.SimpleFeature; @@ -55,7 +55,7 @@ public class CemdapOutput2MatsimPlansConverter { public static final String activityZoneId_attributeKey = "zoneId"; private static final Logger LOG = LogManager.getLogger(CemdapOutput2MatsimPlansConverter.class); - + public static void main(String[] args) throws IOException { // Local use @@ -84,7 +84,7 @@ public static void main(String[] args) throws IOException { boolean assignCoordinatesToActivities = true; // if set to false, the zone id will be attached to activity types and a fake coordinate will be given. boolean combiningGeoms = true; int activityDurationThreshold_s = Integer.MIN_VALUE; - + // Server use if (args.length != 0) { numberOfFirstCemdapOutputFile = Integer.parseInt(args[0]); @@ -106,14 +106,14 @@ public static void main(String[] args) throws IOException { Map shapeFileToFeatureKey = new HashMap<>(); shapeFileToFeatureKey.put(zonalShapeFile, zoneIdTag); - + convert(cemdapDataRoot, numberOfFirstCemdapOutputFile, numberOfPlans, outputDirectory, shapeFileToFeatureKey, allowVariousWorkAndEducationLocations, addStayHomePlan, useLandCoverData, landCoverFile, stopFile, activityFile, simplifyGeometries, combiningGeoms, assignCoordinatesToActivities, activityDurationThreshold_s); } - + public static void convert(String cemdapDataRoot, int numberOfFirstCemdapOutputFile, int numberOfPlans, String outputDirectory, Map shapeFileToFeatureKey, // ensures, unique shape files with same or different featureKey. Amit Nov'17 boolean allowVariousWorkAndEducationLocations, boolean addStayHomePlan, @@ -127,9 +127,9 @@ public static void convert(String cemdapDataRoot, int numberOfFirstCemdapOutputF } LogToOutputSaver.setOutputDirectory(outputDirectory); - + Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); - + // Find respective stops file Map cemdapStopsFilesMap = new HashMap<>(); for (int planNumber = 0; planNumber < numberOfPlans; planNumber++) { @@ -137,20 +137,20 @@ public static void convert(String cemdapDataRoot, int numberOfFirstCemdapOutputF String cemdapStopsFile = cemdapDataRoot + numberOfCurrentInputFile + "/" + stopFile; cemdapStopsFilesMap.put(planNumber, cemdapStopsFile); } - + // Create ObjectAttributes for each agent and each plan Map personZoneAttributesMap = new HashMap<>(); for (int planNumber = 0; planNumber < numberOfPlans; planNumber++) { ObjectAttributes personZoneAttributes = new ObjectAttributes(); personZoneAttributesMap.put(planNumber, personZoneAttributes); } - + Map, Coord> homeZones = new HashMap<>(); - + // Write all (geographic) features of planning area to a map Map zones = new HashMap<>(); for (Map.Entry entry : shapeFileToFeatureKey.entrySet()) { - for (SimpleFeature feature : ShapeFileReader.getAllFeatures(entry.getKey())) { + for (SimpleFeature feature : GeoFileReader.getAllFeatures(entry.getKey())) { Geometry geometry = (Geometry)feature.getDefaultGeometry(); String shapeId = Cemdap2MatsimUtils.removeLeadingZeroFromString((String) feature.getAttribute(entry.getValue())); // TODO check if removal of leading zero is always valid @@ -164,7 +164,7 @@ public static void convert(String cemdapDataRoot, int numberOfFirstCemdapOutputF } } } - + // Get all persons from activity file // List> personsIds = new LinkedList<>(); Map, String> personHomeMap = new HashMap<>(); @@ -175,14 +175,14 @@ public static void convert(String cemdapDataRoot, int numberOfFirstCemdapOutputF // cemdapPersonParser.parse(cemdapDataRoot + numberOfFirstCemdapOutputFile + "/" + cemdapChildrenFilename, personsIds); CemdapActivityParser cemdapActivityParser = new CemdapActivityParser(); cemdapActivityParser.parse(cemdapDataRoot + numberOfFirstCemdapOutputFile + "/" + activityFile, personHomeMap); - + Population population = scenario.getPopulation(); - + for (int planNumber = 0; planNumber < numberOfPlans; planNumber++) { CemdapStopsParser cemdapStopsParser = new CemdapStopsParser(); cemdapStopsParser.setActivityDurationThreshold_s(activityDurationThreshold_s); cemdapStopsParser.parse(cemdapStopsFilesMap.get(planNumber), planNumber, population, personZoneAttributesMap.get(planNumber), outputDirectory); - + // Commenting this for the time being; it does not do anything if the activity file is not considered on top of the stops file, dz,aa, sep'17 // Add a stay-home plan for those people who have no stops (i.e. no travel) in current stop file // Following is required to add persons who just stays at home. Such persons does not appear in the Stops.out file. dz, aa Oct'17 @@ -247,7 +247,7 @@ public static void convert(String cemdapDataRoot, int numberOfFirstCemdapOutputF // If applicable, add a stay-home plan for everybody if (addStayHomePlan) { numberOfPlans++; - + for (Person person : population.getPersons().values()) { Plan firstPlan = person.getPlans().get(0); // Get first (i.e. presumably "home") activity from agent's first plan @@ -261,7 +261,7 @@ public static void convert(String cemdapDataRoot, int numberOfFirstCemdapOutputF person.addPlan(stayHomePlan); } } - + // Check if number of plans that each agent has is correct for (Person person : scenario.getPopulation().getPersons().values()) { if (person.getPlans().size() < numberOfPlans) { @@ -271,7 +271,7 @@ public static void convert(String cemdapDataRoot, int numberOfFirstCemdapOutputF LOG.warn("Person with ID " + person.getId() + " has more than " + numberOfPlans + " plans"); } } - + // Write population file new File(outputDirectory).mkdir(); new PopulationWriter(scenario.getPopulation(), null).write(outputDirectory + "plans.xml.gz"); diff --git a/matsim/pom.xml b/matsim/pom.xml index b68ff2934eb..e5716bead27 100644 --- a/matsim/pom.xml +++ b/matsim/pom.xml @@ -144,6 +144,11 @@ gt-shapefile ${geotools.version} + + org.geotools + gt-geopkg + ${geotools.version} + org.geotools gt-epsg-hsql diff --git a/matsim/src/main/java/org/matsim/analysis/pt/stop2stop/PtStop2StopAnalysis2Shp.java b/matsim/src/main/java/org/matsim/analysis/pt/stop2stop/PtStop2StopAnalysis2Shp.java index 6c5516a6a42..99eeb4c0b20 100644 --- a/matsim/src/main/java/org/matsim/analysis/pt/stop2stop/PtStop2StopAnalysis2Shp.java +++ b/matsim/src/main/java/org/matsim/analysis/pt/stop2stop/PtStop2StopAnalysis2Shp.java @@ -32,7 +32,7 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.matsim.core.utils.io.IOUtils; import org.matsim.pt.transitSchedule.api.TransitLine; import org.opengis.feature.simple.SimpleFeature; @@ -104,7 +104,7 @@ public static void writePtStop2StopAnalysisByTransitLine2ShpFile( } // TODO: add stops? - ShapeFileWriter.writeGeometries(features, shpFileName); + GeoFileWriter.writeGeometries(features, shpFileName); } public static void writePtStop2StopAnalysisByTransitLine2CsvFile( diff --git a/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkTeleatlasAddManeuverRestrictions.java b/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkTeleatlasAddManeuverRestrictions.java index 0eef20da019..b88e16c0a2b 100644 --- a/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkTeleatlasAddManeuverRestrictions.java +++ b/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkTeleatlasAddManeuverRestrictions.java @@ -39,7 +39,7 @@ import org.matsim.core.network.algorithms.NetworkExpandNode.TurnInfo; import org.matsim.core.network.io.NetworkReaderTeleatlas; import org.matsim.core.utils.collections.Tuple; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.core.utils.io.IOUtils; import org.opengis.feature.simple.SimpleFeature; @@ -171,7 +171,7 @@ private void run2(final Network network) throws Exception { NetworkExpandNode neModule = new NetworkExpandNode(network, expansionRadius, this.linkSeparation); TreeMap>> mSequences = new TreeMap<>(); - + try (FileInputStream fis = new FileInputStream(this.mpDbfFileName)) { DbaseFileReader r = new DbaseFileReader(fis.getChannel(), true, IOUtils.CHARSET_WINDOWS_ISO88591); // get header indices @@ -190,7 +190,7 @@ private void run2(final Network network) throws Exception { log.trace(" "+MP_ID_NAME+"-->"+mpIdNameIndex); log.trace(" "+MP_SEQNR_NAME+"-->"+mpSeqNrNameIndex); log.trace(" "+MP_TRPELID_NAME+"-->"+mpTrpelIDNameIndex); - + // create mp data structure // TreeMap> log.info(" parsing meneuver paths dbf file..."); @@ -218,7 +218,7 @@ private void run2(final Network network) throws Exception { // TreeMap>> log.info(" parsing meneuver shape file..."); TreeMap, ArrayList>> maneuvers = new TreeMap<>(); - SimpleFeatureSource fs = ShapeFileReader.readDataFile(this.mnShpFileName); + SimpleFeatureSource fs = GeoFileReader.readDataFile(this.mnShpFileName); SimpleFeatureIterator fIt = fs.getFeatures().features(); while (fIt.hasNext()) { SimpleFeature f = fIt.next(); @@ -256,8 +256,8 @@ else if ((featType == 9401) || (featType == 2104)) { int virtualLinksCnt = 0; for (Map.Entry, ArrayList>> entry : maneuvers.entrySet()) { Id nodeId = entry.getKey(); - if (network.getNodes().get(nodeId) == null) { - log.trace(" nodeid="+nodeId+": maneuvers exist for that node but node is missing. Ignoring and proceeding anyway..."); + if (network.getNodes().get(nodeId) == null) { + log.trace(" nodeid="+nodeId+": maneuvers exist for that node but node is missing. Ignoring and proceeding anyway..."); nodesIgnoredCnt++; } else { // node found @@ -282,7 +282,7 @@ else if ((featType == 9401) || (featType == 2104)) { inLink = n.getInLinks().get(Id.create(firstLinkid+"TF", Link.class)); } Link outLink = n.getOutLinks().get(Id.create(otherLinkId+"FT", Link.class)); - if (outLink == null) { + if (outLink == null) { outLink = n.getOutLinks().get(Id.create(otherLinkId+"TF", Link.class)); } if ((inLink != null) && (outLink != null)) { diff --git a/matsim/src/main/java/org/matsim/core/network/io/NetworkReaderTeleatlas.java b/matsim/src/main/java/org/matsim/core/network/io/NetworkReaderTeleatlas.java index 92d71b014bb..c4416bb5531 100644 --- a/matsim/src/main/java/org/matsim/core/network/io/NetworkReaderTeleatlas.java +++ b/matsim/src/main/java/org/matsim/core/network/io/NetworkReaderTeleatlas.java @@ -33,7 +33,7 @@ import org.matsim.api.core.v01.network.Node; import org.matsim.core.api.internal.MatsimSomeReader; import org.matsim.core.network.NetworkUtils; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.opengis.feature.simple.SimpleFeature; import org.opengis.geometry.BoundingBox; @@ -47,7 +47,7 @@ *
    • nw.shp: junction shape file (typically called xyz________nw.shp) *
    • *
    - * + * * @author balmermi */ public final class NetworkReaderTeleatlas implements MatsimSomeReader { @@ -154,7 +154,7 @@ public final class NetworkReaderTeleatlas implements MatsimSomeReader { /** * Instantiate a new Tele Atlas MultiNet Shapefile reader based on the * junction and the network shape file. - * + * * @param network * MATSim network database in which the reader stores the data * @param jcShpFileName @@ -189,7 +189,7 @@ public void read() throws IOException { /** * Reads Tele Atlas MultiNet junction Shapefile given in * {@link #jcShpFileName}. - * + * *

    * It uses the following feature attributes: *

      @@ -212,7 +212,7 @@ public void read() throws IOException { *
    *

    * The MATSim {@link Node#type} is set as - * + * *
     	 * {@link Node#type} = {@link #NODE_FEATTYP_NAME}+"-"+{@link #NODE_JNCTTYP_NAME}
     	 * 
    @@ -220,7 +220,7 @@ public void read() throws IOException { */ private void readNodesFromJCshp() throws IOException { int nCnt = network.getNodes().size(); - SimpleFeatureSource fs = ShapeFileReader.readDataFile(jcShpFileName); + SimpleFeatureSource fs = GeoFileReader.readDataFile(jcShpFileName); SimpleFeatureIterator fIt = fs.getFeatures().features(); while (fIt.hasNext()) { SimpleFeature f = fIt.next(); @@ -258,7 +258,7 @@ private void readNodesFromJCshp() throws IOException { /** * Reads Tele Atlas MultiNet network Shapefile given in * {@link #nwShpFileName}. - * + * *

    * It uses the following feature attributes: *

      @@ -307,7 +307,7 @@ private void readNodesFromJCshp() throws IOException { * *
    • {@link #LINK_LANES_NAME} (Number of Lanes)
    • *
    - * + * * Conversion rules: *
      *
    • Links that refer to not existing from- or to-link will be ignored @@ -330,21 +330,21 @@ private void readNodesFromJCshp() throws IOException { * {@link #LINK_ID_NAME}+"TF", * {@link #LINK_ID_NAME}+"FT" resp.
    • *
    • The {@link Link#type} is set as: - * + * *
       	 * {@link Link#type} = {@link #LINK_FRCTYP_NAME}+"-"+{@link #LINK_FEATTYP_NAME}+"-"+{@link #LINK_FERRYTYP_NAME}
       	 * 
      - * + * *
    • *
    *

    - * + * * @throws IOException */ private void readLinksFromNWshp() throws IOException { int lCnt = network.getLinks().size(); int ignoreCnt = 0; - SimpleFeatureSource fs = ShapeFileReader.readDataFile(this.nwShpFileName); + SimpleFeatureSource fs = GeoFileReader.readDataFile(this.nwShpFileName); SimpleFeatureIterator fIt = fs.getFeatures().features(); while (fIt.hasNext()) { SimpleFeature f = fIt.next(); @@ -474,7 +474,7 @@ private void readLinksFromNWshp() throws IOException { /** * prints the variable settings to the STDOUT - * + * * @param prefix * a prefix for each line of the STDOUT */ diff --git a/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileReader.java b/matsim/src/main/java/org/matsim/core/utils/gis/GeoFileReader.java similarity index 73% rename from matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileReader.java rename to matsim/src/main/java/org/matsim/core/utils/gis/GeoFileReader.java index 33bb84d6982..24e69c75330 100644 --- a/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileReader.java +++ b/matsim/src/main/java/org/matsim/core/utils/gis/GeoFileReader.java @@ -23,12 +23,15 @@ 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.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.geometry.jts.ReferencedEnvelope; +import org.geotools.geopkg.GeoPkgDataStoreFactory; +import org.geotools.jdbc.JDBCDataStore; import org.matsim.core.api.internal.MatsimSomeReader; import org.matsim.core.gbl.Gbl; import org.matsim.core.utils.misc.Counter; @@ -41,17 +44,16 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; /** * @author glaemmel * @author dgrether * @author mrieser // switch to GeoTools 2.7.3 + * @author nkuehnel / MOIA // add gpkg suuport */ -public class ShapeFileReader implements MatsimSomeReader { - private static final Logger log = LogManager.getLogger(ShapeFileReader.class); +public class GeoFileReader implements MatsimSomeReader { + private static final Logger log = LogManager.getLogger(GeoFileReader.class); private SimpleFeatureSource featureSource = null; @@ -69,10 +71,22 @@ public class ShapeFileReader implements MatsimSomeReader { public static Collection getAllFeatures(final String filename) { try { - File dataFile = new File(filename); - log.info( "will try to read from " + dataFile.getAbsolutePath() ) ; - Gbl.assertIf( dataFile.exists() ); - return getSimpleFeatures(FileDataStoreFinder.getDataStore(dataFile)); + DataStore dataStore; + if(filename.endsWith(".shp")) { + File dataFile = new File(filename); + log.info("will try to read from " + dataFile.getAbsolutePath()); + Gbl.assertIf(dataFile.exists()); + dataStore = FileDataStoreFinder.getDataStore(dataFile); + } else if(filename.endsWith(".gpkg")){ + Map params = new HashMap<>(); + params.put(GeoPkgDataStoreFactory.DBTYPE.key, "geopkg"); + params.put(GeoPkgDataStoreFactory.DATABASE.key, filename); + params.put("read-only", true); + dataStore = DataStoreFinder.getDataStore(params); + } else { + throw new RuntimeException("Unsupported file type."); + } + return getSimpleFeatures(dataStore); } catch (IOException e) { throw new UncheckedIOException(e); } @@ -91,8 +105,8 @@ public static Collection getAllFeatures(final URL url) { * Read all simple features from a data store. This method makes sure the store is closed afterwards. * @return list of contained features. */ - public static List getSimpleFeatures(FileDataStore dataStore) throws IOException { - SimpleFeatureSource featureSource = dataStore.getFeatureSource(); + public static List getSimpleFeatures(DataStore dataStore) throws IOException { + SimpleFeatureSource featureSource = dataStore.getFeatureSource(dataStore.getNames().get(0)); SimpleFeatureIterator it = featureSource.getFeatures().features(); List featureSet = new ArrayList<>(); @@ -110,7 +124,7 @@ public static List getSimpleFeatures(FileDataStore dataStore) thr */ public Collection readFileAndInitialize(final String filename) throws UncheckedIOException { try { - this.featureSource = ShapeFileReader.readDataFile(filename); + this.featureSource = GeoFileReader.readDataFile(filename); this.init(); SimpleFeature ft = null; SimpleFeatureIterator it = this.featureSource.getFeatures().features(); @@ -135,16 +149,16 @@ public Collection readFileAndInitialize(final String filename) th *

    * There are many ways to use that class in a wrong way. The safe way is the following: *

    - *
     ShapeFileReader shapeFileReader = new ShapeFileReader();
    -	 * shapeFileReader.readFileAndInitialize(zonesShapeFile); 
    + *
     GeoFileReader geoFileReader = new GeoFileReader();
    +	 * geoFileReader.readFileAndInitialize(geoFile); 
    *

    * Then, get the features by *

    - *
     Set<{@link Feature}> features = shapeFileReader.getFeatureSet(); 
    + *
     Set<{@link Feature}> features = geoFileReader.getFeatureSet(); 
    *

    * If you need metadata you can use *

    - *
     FeatureSource fs = shapeFileReader.getFeatureSource(); 
    + *
     FeatureSource fs = geoFileReader.getFeatureSource(); 
    *

    * to get access to the feature source.
    * BUT NEVER CALL fs.getFeatures(); !!! It can happen that you will read from disk again!!! @@ -157,22 +171,36 @@ public Collection readFileAndInitialize(final String filename) th * The following old doc is kept here: *

    *

    - * Provides access to a shape file and returns a FeatureSource containing all features. + * Provides access to a shape or geopackage file and returns a FeatureSource containing all features. * Take care access means on disk access, i.e. the FeatureSource is only a pointer to the information * stored in the file. This can be horribly slow if invoked many times and throw exceptions if two many read * operations to the same file are performed. In those cases it is recommended to use the method readDataFileToMemory * of this class. * - * @param filename File name of a shape file (ending in *.shp) + * @param filename File name of a shape or geopackage file (ending in *.shp or *.gpkg) * @return FeatureSource containing all features. * @throws UncheckedIOException if the file cannot be found or another error happens during reading */ public static SimpleFeatureSource readDataFile(final String filename) throws UncheckedIOException { try { log.warn("Unsafe method! store.dispose() is not called from within this method"); - File dataFile = new File(filename); - FileDataStore store = FileDataStoreFinder.getDataStore(dataFile); - return store.getFeatureSource(); + SimpleFeatureSource featureSource; + if(filename.endsWith(".shp")) { + File dataFile = new File(filename); + FileDataStore store = FileDataStoreFinder.getDataStore(dataFile); + featureSource = store.getFeatureSource(); + } else if(filename.endsWith(".gpkg")) { + Map params = new HashMap<>(); + params.put(GeoPkgDataStoreFactory.DBTYPE.key, "geopkg"); + params.put(GeoPkgDataStoreFactory.DATABASE.key, filename); + params.put("read-only", true); + + DataStore datastore = DataStoreFinder.getDataStore(params); + featureSource = datastore.getFeatureSource(datastore.getNames().get(0)); + } else { + throw new RuntimeException("Unsupported file type."); + } + return featureSource; } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileWriter.java b/matsim/src/main/java/org/matsim/core/utils/gis/GeoFileWriter.java similarity index 69% rename from matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileWriter.java rename to matsim/src/main/java/org/matsim/core/utils/gis/GeoFileWriter.java index 2bb2650f814..8a2e8ba31e0 100644 --- a/matsim/src/main/java/org/matsim/core/utils/gis/ShapeFileWriter.java +++ b/matsim/src/main/java/org/matsim/core/utils/gis/GeoFileWriter.java @@ -22,9 +22,13 @@ 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.shapefile.ShapefileDataStore; import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.feature.DefaultFeatureCollection; +import org.geotools.geopkg.GeoPkgDataStoreFactory; +import org.geotools.jdbc.JDBCDataStoreFactory; import org.matsim.core.api.internal.MatsimSomeWriter; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; @@ -34,34 +38,48 @@ import java.io.UncheckedIOException; import java.net.URL; import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + /** * This is a simple utility class that provides methods to write Feature instances - * of the geotools framework to an ESRI shape file. + * of the geotools framework to an ESRI shape or geopackage file. * * @author glaemmel + * @author nkuehnel / MOIA // add gpkg support */ -public class ShapeFileWriter implements MatsimSomeWriter { +public class GeoFileWriter implements MatsimSomeWriter { - private static final Logger log = LogManager.getLogger(ShapeFileWriter.class); + private static final Logger log = LogManager.getLogger(GeoFileWriter.class); public static void writeGeometries(final Collection features, final String filename) { if (features.isEmpty()) { throw new UncheckedIOException(new IOException("Cannot write empty collection")); } - log.info("Writing shapefile to " + filename); + try { - URL fileURL = (new File(filename)).toURI().toURL(); + DataStore datastore; + if(filename.endsWith(".shp")) { + log.info("Writing shapefile to " + filename); + URL fileURL = (new File(filename)).toURI().toURL(); + datastore = new ShapefileDataStore(fileURL); + } else if(filename.endsWith(".gpkg")){ + Map map = new HashMap<>(); + map.put(GeoPkgDataStoreFactory.DBTYPE.key, GeoPkgDataStoreFactory.DBTYPE.sample); + map.put(GeoPkgDataStoreFactory.DATABASE.key, filename); + map.put(JDBCDataStoreFactory.BATCH_INSERT_SIZE.key, 50); + datastore = DataStoreFinder.getDataStore(map); + } else { + throw new RuntimeException("Unsupported file type."); + } - ShapefileDataStore datastore = new ShapefileDataStore(fileURL); SimpleFeature feature = features.iterator().next(); datastore.createSchema(feature.getFeatureType()); DefaultFeatureCollection coll = new DefaultFeatureCollection(); coll.addAll(features); - SimpleFeatureType featureType = features.iterator().next().getFeatureType(); - datastore.createSchema(featureType); - SimpleFeatureStore featureSource = (SimpleFeatureStore) datastore.getFeatureSource(); + SimpleFeatureStore featureSource = (SimpleFeatureStore) datastore.getFeatureSource(datastore.getNames().get(0)); featureSource.addFeatures(coll); } catch (IOException e) { throw new RuntimeException(e); diff --git a/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/network/Links2ESRIShape.java b/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/network/Links2ESRIShape.java index f27a0195ba1..d8c8d452eb4 100755 --- a/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/network/Links2ESRIShape.java +++ b/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/network/Links2ESRIShape.java @@ -33,7 +33,7 @@ import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -74,7 +74,7 @@ public void write() { features.add(this.featureGenerator.getFeature(link)); } log.info("writing features to shape file... " + this.filename); - ShapeFileWriter.writeGeometries(features, this.filename); + GeoFileWriter.writeGeometries(features, this.filename); log.info("done writing shape file."); } diff --git a/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/network/Nodes2ESRIShape.java b/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/network/Nodes2ESRIShape.java index 90b48753450..003c08d7a34 100644 --- a/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/network/Nodes2ESRIShape.java +++ b/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/network/Nodes2ESRIShape.java @@ -35,7 +35,7 @@ import org.matsim.core.scenario.MutableScenario; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -56,11 +56,11 @@ public class Nodes2ESRIShape { private final String filename; private SimpleFeatureBuilder builder; - + public Nodes2ESRIShape(final Network network, final String filename, final String coordinateSystem) { this(network, filename, MGC.getCRS(coordinateSystem)); } - + public Nodes2ESRIShape(Network network, String filename, CoordinateReferenceSystem crs) { this.network = network; this.filename = filename; @@ -72,7 +72,7 @@ public void write() { for (Node node : NetworkUtils.getSortedNodes(this.network)) { features.add(getFeature(node)); } - ShapeFileWriter.writeGeometries(features, this.filename); + GeoFileWriter.writeGeometries(features, this.filename); } diff --git a/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/plans/SelectedPlans2ESRIShape.java b/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/plans/SelectedPlans2ESRIShape.java index dfaee197ecc..f40dc653e51 100755 --- a/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/plans/SelectedPlans2ESRIShape.java +++ b/matsim/src/main/java/org/matsim/utils/gis/matsim2esri/plans/SelectedPlans2ESRIShape.java @@ -51,7 +51,7 @@ import org.matsim.core.scenario.MutableScenario; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileWriter; +import org.matsim.core.utils.gis.GeoFileWriter; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -112,7 +112,7 @@ public void write() { drawOutputSample(); if (this.writeActs) { writeActs(); - } + } if (this.writeLegs) { writeLegs(); } @@ -143,7 +143,7 @@ private void writeActs() throws IOException { } } - ShapeFileWriter.writeGeometries(fts, outputFile); + GeoFileWriter.writeGeometries(fts, outputFile); } private void writeLegs() throws IOException { @@ -164,7 +164,7 @@ private void writeLegs() throws IOException { } } } - ShapeFileWriter.writeGeometries(fts, outputFile); + GeoFileWriter.writeGeometries(fts, outputFile); } private SimpleFeature getActFeature(final String id, final Activity act) { @@ -176,7 +176,7 @@ private SimpleFeature getActFeature(final String id, final Activity act) { double ry = MatsimRandom.getRandom().nextDouble() * this.actBlurFactor; Coord cc = this.network.getLinks().get(act.getLinkId()).getCoord(); Coord c = new Coord(cc.getX() + rx, cc.getY() + ry); - + try { return this.actBuilder.buildFeature(null, new Object [] {MGC.coord2Point(c), id, type, linkId, startTime, endTime}); } catch (IllegalArgumentException e) { @@ -235,7 +235,7 @@ private void initFeatureType() { actBuilder.add("LINK_ID", String.class); actBuilder.add("START_TIME", Double.class); actBuilder.add("END_TIME", Double.class); - + SimpleFeatureTypeBuilder legBuilder = new SimpleFeatureTypeBuilder(); legBuilder.setName("leg"); legBuilder.setCRS(this.crs); diff --git a/matsim/src/main/java/org/matsim/utils/gis/shp2matsim/ShpGeometryUtils.java b/matsim/src/main/java/org/matsim/utils/gis/shp2matsim/ShpGeometryUtils.java index bee189e3e24..4c5d56e9f98 100644 --- a/matsim/src/main/java/org/matsim/utils/gis/shp2matsim/ShpGeometryUtils.java +++ b/matsim/src/main/java/org/matsim/utils/gis/shp2matsim/ShpGeometryUtils.java @@ -29,11 +29,11 @@ import org.locationtech.jts.geom.prep.PreparedGeometryFactory; import org.matsim.api.core.v01.Coord; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; public class ShpGeometryUtils { public static List loadGeometries(URL url) { - return ShapeFileReader.getAllFeatures(url) + return GeoFileReader.getAllFeatures(url) .stream() .map(sf -> (Geometry)sf.getDefaultGeometry()) .collect(Collectors.toList()); @@ -41,7 +41,7 @@ public static List loadGeometries(URL url) { public static List loadPreparedGeometries(URL url) { PreparedGeometryFactory factory = new PreparedGeometryFactory(); - return ShapeFileReader.getAllFeatures(url) + return GeoFileReader.getAllFeatures(url) .stream() .map(sf -> factory.create((Geometry)sf.getDefaultGeometry())) .collect(Collectors.toList()); diff --git a/matsim/src/test/java/org/matsim/core/utils/gis/ShapeFileReaderTest.java b/matsim/src/test/java/org/matsim/core/utils/gis/GeoFileReaderTest.java similarity index 80% rename from matsim/src/test/java/org/matsim/core/utils/gis/ShapeFileReaderTest.java rename to matsim/src/test/java/org/matsim/core/utils/gis/GeoFileReaderTest.java index 1a07451aa7b..fa9ab1dc10c 100644 --- a/matsim/src/test/java/org/matsim/core/utils/gis/ShapeFileReaderTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/gis/GeoFileReaderTest.java @@ -31,8 +31,9 @@ /** * @author mrieser / senozon + * @author nkuehnel / MOIA // add gpkg test */ -public class ShapeFileReaderTest { +public class GeoFileReaderTest { @RegisterExtension private MatsimTestUtils utils = new MatsimTestUtils(); @@ -41,9 +42,19 @@ public class ShapeFileReaderTest { * @throws IOException */ @Test - void testPlusInFilename() throws IOException { + void testShp() throws IOException { String filename = "src/test/resources/" + utils.getInputDirectory() + "test+test.shp"; - FeatureSource fs = ShapeFileReader.readDataFile(filename); + FeatureSource fs = GeoFileReader.readDataFile(filename); + Assertions.assertEquals(3, fs.getFeatures().size()); + } + + /** + * @throws IOException + */ + @Test + void testGpkg() throws IOException { + String filename = "src/test/resources/" + utils.getInputDirectory() + "test+test.gpkg"; + FeatureSource fs = GeoFileReader.readDataFile(filename); Assertions.assertEquals(3, fs.getFeatures().size()); } } diff --git a/matsim/src/test/java/org/matsim/core/utils/gis/ShapeFileWriterTest.java b/matsim/src/test/java/org/matsim/core/utils/gis/GeoFileWriterTest.java similarity index 70% rename from matsim/src/test/java/org/matsim/core/utils/gis/ShapeFileWriterTest.java rename to matsim/src/test/java/org/matsim/core/utils/gis/GeoFileWriterTest.java index 70c19d22d88..b1a950d9e11 100644 --- a/matsim/src/test/java/org/matsim/core/utils/gis/ShapeFileWriterTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/gis/GeoFileWriterTest.java @@ -45,7 +45,7 @@ import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; -public class ShapeFileWriterTest { +public class GeoFileWriterTest { @RegisterExtension private MatsimTestUtils utils = new MatsimTestUtils(); @@ -55,16 +55,16 @@ void testShapeFileWriter() throws IOException{ String inFile = "src/test/resources/" + utils.getInputDirectory() + "test.shp"; String outFile = utils.getOutputDirectory() + "/test.shp"; - SimpleFeatureSource s = ShapeFileReader.readDataFile(inFile); + SimpleFeatureSource s = GeoFileReader.readDataFile(inFile); SimpleFeatureCollection fts = s.getFeatures(); SimpleFeatureIterator it = fts.features(); SimpleFeature ft = it.next(); Geometry g = (Geometry) ft.getDefaultGeometry(); List fc = new ArrayList<>(); fc.add(ft); - ShapeFileWriter.writeGeometries(fc, outFile); + GeoFileWriter.writeGeometries(fc, outFile); - SimpleFeatureSource s1 = ShapeFileReader.readDataFile(outFile); + SimpleFeatureSource s1 = GeoFileReader.readDataFile(outFile); SimpleFeatureCollection fts1 = s1.getFeatures(); SimpleFeatureIterator it1 = fts1.features(); SimpleFeature ft1 = it1.next(); @@ -74,6 +74,31 @@ void testShapeFileWriter() throws IOException{ } + @Test + void testGeopackageFileWriter() throws IOException{ + + String inFile = "src/test/resources/" + utils.getInputDirectory() + "test.gpkg"; + + String outFile = utils.getOutputDirectory() + "/test.gpkg"; + SimpleFeatureSource s = GeoFileReader.readDataFile(inFile); + SimpleFeatureCollection fts = s.getFeatures(); + SimpleFeatureIterator it = fts.features(); + SimpleFeature ft = it.next(); + Geometry g = (Geometry) ft.getDefaultGeometry(); + List fc = new ArrayList<>(); + fc.add(ft); + GeoFileWriter.writeGeometries(fc, outFile); + + SimpleFeatureSource s1 = GeoFileReader.readDataFile(outFile); + SimpleFeatureCollection fts1 = s1.getFeatures(); + SimpleFeatureIterator it1 = fts1.features(); + SimpleFeature ft1 = it1.next(); + Geometry g1 = (Geometry) ft1.getDefaultGeometry(); + + Assertions.assertEquals(g.getCoordinates().length, g1.getCoordinates().length); + + } + @Test void testShapeFileWriterWithSelfCreatedContent() throws IOException { String outFile = utils.getOutputDirectory() + "/test.shp"; @@ -94,9 +119,42 @@ void testShapeFileWriterWithSelfCreatedContent() throws IOException { Geometry g0 = (Geometry) features.iterator().next().getDefaultGeometry(); - ShapeFileWriter.writeGeometries(features, outFile); + GeoFileWriter.writeGeometries(features, outFile); + + SimpleFeatureSource s1 = GeoFileReader.readDataFile(outFile); + SimpleFeatureCollection fts1 = s1.getFeatures(); + SimpleFeatureIterator it1 = fts1.features(); + SimpleFeature ft1 = it1.next(); + Geometry g1 = (Geometry) ft1.getDefaultGeometry(); + + Assertions.assertEquals(g0.getCoordinates().length, g1.getCoordinates().length); + + + } + + @Test + void testGeopackageFileWriterWithSelfCreatedContent() throws IOException { + String outFile = utils.getOutputDirectory() + "/test.gpkg"; + SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder(); + b.setName("EvacuationArea"); + b.setCRS(DefaultGeographicCRS.WGS84); + b.add("the_geom", MultiPolygon.class); + b.add("name", String.class); + SimpleFeatureType ft = b.buildFeatureType(); + + GeometryFactory geofac = new GeometryFactory(); + LinearRing lr = geofac.createLinearRing(new Coordinate[]{new Coordinate(0,0),new Coordinate(0,1),new Coordinate(1,1),new Coordinate(0,0)}); + Polygon p = geofac.createPolygon(lr,null); + MultiPolygon mp = geofac.createMultiPolygon(new Polygon[]{p}); + Collection features = new ArrayList(); + features.add(SimpleFeatureBuilder.build(ft, new Object[]{mp,"test_name"},"fid")); + + + Geometry g0 = (Geometry) features.iterator().next().getDefaultGeometry(); + + GeoFileWriter.writeGeometries(features, outFile); - SimpleFeatureSource s1 = ShapeFileReader.readDataFile(outFile); + SimpleFeatureSource s1 = GeoFileReader.readDataFile(outFile); SimpleFeatureCollection fts1 = s1.getFeatures(); SimpleFeatureIterator it1 = fts1.features(); SimpleFeature ft1 = it1.next(); @@ -125,9 +183,9 @@ void testShapeFileWriterWithSelfCreatedContent_withMatsimFactory_Polygon() throw Geometry g0 = (Geometry) f.getDefaultGeometry(); - ShapeFileWriter.writeGeometries(features, outFile); + GeoFileWriter.writeGeometries(features, outFile); - SimpleFeatureSource s1 = ShapeFileReader.readDataFile(outFile); + SimpleFeatureSource s1 = GeoFileReader.readDataFile(outFile); SimpleFeatureCollection fts1 = s1.getFeatures(); SimpleFeatureIterator it1 = fts1.features(); SimpleFeature ft1 = it1.next(); @@ -154,9 +212,9 @@ void testShapeFileWriterWithSelfCreatedContent_withMatsimFactory_Polyline() thro Geometry g0 = (Geometry) f.getDefaultGeometry(); - ShapeFileWriter.writeGeometries(features, outFile); + GeoFileWriter.writeGeometries(features, outFile); - SimpleFeatureSource s1 = ShapeFileReader.readDataFile(outFile); + SimpleFeatureSource s1 = GeoFileReader.readDataFile(outFile); SimpleFeatureCollection fts1 = s1.getFeatures(); SimpleFeatureIterator it1 = fts1.features(); SimpleFeature ft1 = it1.next(); @@ -182,9 +240,9 @@ void testShapeFileWriterWithSelfCreatedContent_withMatsimFactory_Point() throws Geometry g0 = (Geometry) f.getDefaultGeometry(); - ShapeFileWriter.writeGeometries(features, outFile); + GeoFileWriter.writeGeometries(features, outFile); - SimpleFeatureSource s1 = ShapeFileReader.readDataFile(outFile); + SimpleFeatureSource s1 = GeoFileReader.readDataFile(outFile); SimpleFeatureCollection fts1 = s1.getFeatures(); SimpleFeatureIterator it1 = fts1.features(); SimpleFeature ft1 = it1.next(); diff --git a/matsim/src/test/java/org/matsim/utils/gis/matsim2esri/network/Network2ESRIShapeTest.java b/matsim/src/test/java/org/matsim/utils/gis/matsim2esri/network/Network2ESRIShapeTest.java index 6700340ee8f..ad21f1e38cd 100755 --- a/matsim/src/test/java/org/matsim/utils/gis/matsim2esri/network/Network2ESRIShapeTest.java +++ b/matsim/src/test/java/org/matsim/utils/gis/matsim2esri/network/Network2ESRIShapeTest.java @@ -31,7 +31,7 @@ import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.testcases.MatsimTestUtils; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -60,7 +60,7 @@ void testPolygonCapacityShape() { builder.setCoordinateReferenceSystem(crs); new Links2ESRIShape(network,outputFileP, builder).write(); - Collection writtenFeatures = ShapeFileReader.getAllFeatures(outputFileP); + Collection writtenFeatures = GeoFileReader.getAllFeatures(outputFileP); Assertions.assertEquals(network.getLinks().size(), writtenFeatures.size()); } @@ -83,7 +83,7 @@ void testPolygonLanesShape() { builder.setCoordinateReferenceSystem(crs); new Links2ESRIShape(network,outputFileP, builder).write(); - Collection writtenFeatures = ShapeFileReader.getAllFeatures(outputFileP); + Collection writtenFeatures = GeoFileReader.getAllFeatures(outputFileP); Assertions.assertEquals(network.getLinks().size(), writtenFeatures.size()); } @@ -106,7 +106,7 @@ void testPolygonFreespeedShape() { builder.setCoordinateReferenceSystem(crs); new Links2ESRIShape(network,outputFileP, builder).write(); - Collection writtenFeatures = ShapeFileReader.getAllFeatures(outputFileP); + Collection writtenFeatures = GeoFileReader.getAllFeatures(outputFileP); Assertions.assertEquals(network.getLinks().size(), writtenFeatures.size()); } @@ -129,7 +129,7 @@ void testLineStringShape() { builder.setCoordinateReferenceSystem(crs); new Links2ESRIShape(network,outputFileShp, builder).write(); - Collection writtenFeatures = ShapeFileReader.getAllFeatures(outputFileShp); + Collection writtenFeatures = GeoFileReader.getAllFeatures(outputFileShp); Assertions.assertEquals(network.getLinks().size(), writtenFeatures.size()); } @@ -145,7 +145,7 @@ void testNodesShape() { new Nodes2ESRIShape(network,outputFileShp, "DHDN_GK4").write(); - Collection writtenFeatures = ShapeFileReader.getAllFeatures(outputFileShp); + Collection writtenFeatures = GeoFileReader.getAllFeatures(outputFileShp); Assertions.assertEquals(network.getNodes().size(), writtenFeatures.size()); } } diff --git a/matsim/src/test/java/org/matsim/utils/gis/matsim2esri/plans/SelectedPlans2ESRIShapeTest.java b/matsim/src/test/java/org/matsim/utils/gis/matsim2esri/plans/SelectedPlans2ESRIShapeTest.java index f5ec5a13be3..c619704622b 100755 --- a/matsim/src/test/java/org/matsim/utils/gis/matsim2esri/plans/SelectedPlans2ESRIShapeTest.java +++ b/matsim/src/test/java/org/matsim/utils/gis/matsim2esri/plans/SelectedPlans2ESRIShapeTest.java @@ -34,7 +34,7 @@ import org.matsim.core.population.io.PopulationReader; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; -import org.matsim.core.utils.gis.ShapeFileReader; +import org.matsim.core.utils.gis.GeoFileReader; import org.matsim.testcases.MatsimTestUtils; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -66,7 +66,7 @@ void testSelectedPlansActsShape() throws IOException { sp.setWriteLegs(false); sp.write(); - Collection writtenFeatures = ShapeFileReader.getAllFeatures(outShp); + Collection writtenFeatures = GeoFileReader.getAllFeatures(outShp); Assertions.assertEquals(2235, writtenFeatures.size()); } @@ -91,7 +91,7 @@ void testSelectedPlansLegsShape() throws IOException { sp.setWriteLegs(true); sp.write(); - Collection writtenFeatures = ShapeFileReader.getAllFeatures(outShp); + Collection writtenFeatures = GeoFileReader.getAllFeatures(outShp); Assertions.assertEquals(1431, writtenFeatures.size()); } diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testGpkg/test+test.gpkg b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testGpkg/test+test.gpkg new file mode 100644 index 0000000000000000000000000000000000000000..3b7e9a7b3fa422e63191ce24eee6b686585e3b13 GIT binary patch literal 106496 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 WS0?7e3orJ7mXlO|up9Zg7yl1EbSwJ+ literal 0 HcmV?d00001 diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.dbf b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.dbf similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.dbf rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.dbf diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.prj b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.prj similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.prj rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.prj diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.qpj b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.qpj similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.qpj rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.qpj diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.shp b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.shp similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.shp rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.shp diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.shx b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.shx similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileReaderTest/testPlusInFilename/test+test.shx rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileReaderTest/testShp/test+test.shx diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testGeopackageFileWriter/test.gpkg b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testGeopackageFileWriter/test.gpkg new file mode 100644 index 0000000000000000000000000000000000000000..f3221c7739c3ee74206a8b11d8602e4eb8afbb69 GIT binary patch literal 106496 zcmeI5Z)_XMb-z;^#Jj{ngXnGlj{a2hZrLRH=w+rGB@<>rz$Z zq0v-n$9mhAO8OQr$(pF@Zkd%V7teDfpG_tbT$Tjg@!j$Wk}KTROqL_bbdJmBNhaNy zE=WLvaPgIEB%8Sb2@=UP$#E%eB~P;PWR45PuVk`$mIO_`h$0hRxKkBLutSGnkld4$ zs-TM+DJrt2tAZr!7fG|0M)gQhkYzA+s@qAW0v8?ucSEQjwK-@6J8c-BFS?%^CX>tpF%3d+B8k3^BnE@tvE+7IV^Td zlqy>~H~?2-!~2*WvU}WN3G31hbgvy=lkSUTHB+D!YN=#K?skt{$)t06a4G3Lso&*w zy++ov$+dWPgS^ab*cq_4E*55O$;yzdR^x57sCP>y((W9>B+Fd|camP=awcwYN4hBM znhkY0{LSBYia1Lv@lvr&2D{mwOJVNDFZ_hN1ts#>Z09B3hCta0u1!+UhI&EK2GIj zXT#fsd+OS5Ybx@OZcEAGLI3UfBWrs3MfoklUlnDt9$rNSQ-dI6gS&FH9ea z%U*7?-`Rt_2cPKk`h!8w>)Y+RIqGFy^mo?Din1Hp5fy^jqQKLxn za-udlQOZwTyEw6SaiV-H$OdI)I~WeLc2CX{y9Z}$HpdN7HizvR7dktGO1lFcIUdHl zww&wYi9!Eb@W>XnTA|qytjmGL{@#`>=2J?_lc~cRs>nP55tjV87(hskAjY)s3jPxx(?qZu`J1wk%h|~n|24) zKm8p1^7+Q#cmLR5GN<6zsV%s`7ZN}MNB{{S0VIF~kN^@u0!RP}JU#-y$9OL@<3nd_ z1=whYrJYzJu#Zzwh5D9MB)M!Zok?>IE3WmyE@Z41B^mB%5!mDuRZ%XA1lEtbSlj%q z_3~a~#yw~6wo54rD%^{c;0{}}kl(g4Z+(DUAePV(g&chBFUrH`nen~{(%uU<5;?Lk zOVulhx>V%WbBWV$C%8;vCAS$cBLggKeH7M=OFpu=FdJZV>u`rJlU!|!T!_stL}K%7 zba7!SIyWDU#^x@>*mxm-Et5^=H#P$_=Kvd+pNY)`Zr|<_b0HSJKx62g1P)3|sG=xu zOU11KJJUscVR0rx#bFmGzZocr6%Yr>shP<9>|89m7@dnOF3!ff>981yMhzWqCZUok zSm5i85+qK;&CzS1ni;Ifm1Z~>&*i&mJZoxPwIrwEcBzpBc2HqUz-VHPNHQsjMX4rK z;hk!!8Mg_yMABrh)we`dkxF#^@A19Kz<+!p0VIF~kN^@u0!RP}AOR$R1dsp{Kmw1O zK*2LI{=)d!WiPz?U{gkK{s|52;AnbuCOSJg6Puj5kdMq?oQqzZiA^oc&E9(Jy$$7C zd&$>c`oV8r^!+sXS-74E2w#c7^$&mi<#&E~`t6fYFOTnk82FDbB!C2v01`j~NB{{S z0VIF~kN^@u0!ZLPM!?%YK1_EGaQ*)wYgnuf5fx009B!C2v01`j~ zNB{{S0VIF~kN^@u0>>mUdScvs_8;91z~}!RlOBpA0VIF~kN^@u0!RP}AOR$R1dsp{ zc!~(v|Nfsj{S+yVsv-d-fCP{L5s&uQO{sRPEHy`~Lh)VRGm}L|3IsMN}*GyA@uS zsv=(#AZW*W+m=fD7T>6s1YLB?tYo=(o+J5eGLhi2BcVX|I9xnVzspvL>p!8{6@)nt8OaCet}Cn}0-%W}c4`<7a%{GuOd7 z&mD&GzM|Cls(4SVKCEqaHbv8~-lKGtu zxHNRPGgR2=CJUjRvQCs0y{3I&EM3iHz|+ZeBo@nztZO~i@LhY7nN$GCTm9Xy90+h+uAL1 zcw@6>&fPk8D-(UUE_M?*%r@?md@{X3J5j6G)jET0Ee(B*7Dj8S*{#p6HVe}x%D_;> z(d8PDx@fnOLOOZ90Q04GCv?a|7p3yDv*B&RJ@rhtH5K_sx25Fpp#S##k+#%ol%_@S z(XKXeGC6eotjsaQUBd9*vjblL^t5Mhvu&74MTOQf{gt7BJz%iYAnnn%b~(cFltn>r zs3MfoklTa9Dt9#wr;`~YPdGj}=r2qkiOXJYv)|c+ya%7?^ZJ89&+FUmx;g4)UG#U> z$%?WY+7T6km5jjCuH=+qr4l%OsVs@A8DUy4TN1URD%Euf78S;TYgIiMWUGRv^F>%4 zRA79A)l5FQ)*j)AB^ZK5Mp>6?VkkJVF*#A2oG9fdu3em1yEsw46=Z|5vKQuhUdq66Wa9WiEAyN45JzR#7X0EZv9U$g+%< zm$gSh$5GT03{_o+?~+)SWXZ_FWsYvU3y%%`3p32zU{3wr*d6bK!O)3+@Be(?Eb~3) z#@Kg8|9I^6(Pu{fY{Y-^Plt0otp5!W1MVL_=k1k3JxG6^aj*-}pa2Px zKv^mUT9Xj_oGf0*XOd}1wZ_@U8xo*yEI{l>8L}i`%O$+O;WyXJmkwK>*r$pQyWH!N zhkL;XTM>4t$F}5iC{b%@#zsU%1wRa~$=Hi%ullIT8T%2AM9ZzUU-DU#?U|m~KIH1p zUiK5V{ zb>z`v` zQsZiMeb*SzO|fvedAGyLFbiwq^;CR?qm!@bGDTTb%AX@Mh9LNLFA) zrgWQavZe?X2=5YOZLl}qRShcQR)U5-d$bBv`};-7yxN^tUAM8lQK=4Ab9$qCE#@+Z&57aR)X{HCPLon`7WtckF|) zt(>}Tec9Ge&fRdWsC2CGZ982R=;cL`ICrS_^Us*G5WFdhH$^+{Et_M(q-TKHzc!p$XZqiU6ZSrr-20ZY z@!nf=Ul9Tm@XjZH>U;4wKX~a!?|k{kKZJMBAQa)DKmE-QG~l0Czx&+{kpAZXu70x& zQdTZjs)3(>?Y}Y*|KH=E*ZvXWt=zx!tAn4e!1Z50_l~e`E6tssx&D8b@x2R$;R^{M z0VIF~kN^@u0!RP}AOR$R1dsp{_%IRhdiuwQ>0hAH^?(1V?=ilw`&Qr$Uq}E6AOR$R z1dsp{Kmter2_OL^fCQc@0#g6rB__Ci&iG~sJY_{N9?$^KcM;(mL`CzVb5`({uGcS4 zPj7E;Pr>)f>q7CaP!Xr#>-N)HT`WeTGt-}Je_g~%1mB!4O>V37!A*UG!H%LF*R6G-c-wOk< zd0^b@@3wbf{{8=ZjPJdt92u&Q1dsp{Kmter2_OL^fCP{L5&<_t97&g}b zBa;mL#}^Vn0!RP}AOR$R1dsp{Kmv9Gf3)s7!F=&k5JaETMPHt`zW?pdzxDlp3NQcY z$L}ov=eSzleP{GvN544w{K!{F&Yt}8@TT|IgTEe-Pe}c5_I(XRp7htjTG;Eq zbjkBZ#5g(C@hyl$zCF8rd{;_nI7 zhG-qa%IZ=L9_%30>SQ&Z=km!l&N#X^T}Y+KDt9$rNaaaL)73H+36Q%sb zwTlyL7bnWMf^1M$wu9j?TPyKpsVYJlR_?8=Xq)W-SxbwfvkUK!guMP>&~s4eY)?nw z&mZ1)1QctbuvNCk*YA?`Y;rB0-7sny&#gF6b!pyKV+855L^M$kQl`*ya!F82d_$Fp z^R(C+v=^`Mx=)O4=cB`8MW%OZRmiCMgc4^CZOLGG?{d&MReFE^kW-~gVpY`P-}|2` zZAx0FO0RM$F3%A-MBRR>v{Ef~94dW@)B&qF+e-zSqE-#8bK#veXcbS+T_$PnhN+8jGPdn7 zYLd(u9W9fkr&k|wR(6lo20)=!$!xn^^LXon;Ryr6>uX0si1iL3_JKfvbHfb^y&W6g zBMOHFJb_1zzxFB9Am@&3i)im{5p}o4Rnk0{-PO5T1_Hh0|IIQT%|SclXFqAw|H1Z= z^^f#k|Hubh|Kl0ulV@Q2ivh!9KbSrQuzB`#FMLf&3$ImGr@sry;&zA2?yW;x8D?R8 zUr)tXI67ozx_I|j;;8}*{igq^K8W!HsT$jzH53g?NhO<5yB#7wakHlIa97(!#WiB{fOjf#1Ro{VmD6#^>Ge zVV~n zBq5{jM@{HkinN8=)5wxomSjnn6xlhgW4lZ)?UUyU%o>X#DWsFv3!GgEmK2q0qb3`L zvBX(;IJ_sH@t(=R6sy1KaGGztIpO2WqM$cakuNF@S?8(W>E?UhH<9IrIwp?h{IEG2 zGgvAW6-twJQPwq*q!zJ<^-~;Y>TQ5e;8!Vuprer*z^+e$Gcb9^q0r1 z@S%yU3R`Zn<#!*s!sm}!;q~VSscCN*cG>J2n)qsiKGM*2`4NX@yCOrfP!m~586NZ9 zU_8U;nc?&B3tvb82_OL^fCP{L51T2A;KNFF(DLn2yA^cGM41K+O(l3-PLV=EQ_KBlExdA zf@!N#lH>}6wLa4DqN>rP@JXu+x+GNLwu`o_5g9J-iB}c1Cg_&~H}2{N2}5xEuD+b$ zGKrOJZZmKrks}MU0hUYWxHVXdLWrVPOC%w}%3GI;B)6;SVvR%=7iNhlYhvwARSd9e zAk1Zt6b|K8LDnQa9Jt++cw#;_)3fZte5_~LNMx?}j3XE3XM4|i{z8-rbE#BvJ(o$Y zws~HN%`Ze^^K5i+VJbQ|AC1Q5F2vXrmrmrb!D=0i@c^lXNIM*P=!T(t**$>n~72;u~h=5 z4%RsZZ4l3L@uoe}%PUthH#a92XV}Te!VC-V@CH<96LIUgM1Y-*MK9dGy);dGgVBMY z3)NNS_h*;S)3?i2s0bh;=b=+JYL}s(KnFN4E3iXQ*1$&?qE# z;o7E~j%vx+iP6E|Eg6HrGJUH4o6MQ>FYNoAV?_nbmYyuo8X^*_@zh$Qs!OX%O_1cZ z=6ygTd;0}6W i#3pAh3J$U{C=`CxBd@y_u&`- literal 0 HcmV?d00001 diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.dbf b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.dbf similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.dbf rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.dbf diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.prj b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.prj similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.prj rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.prj diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.qix b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.qix similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.qix rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.qix diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.qpj b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.qpj similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.qpj rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.qpj diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.shp b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.shp similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.shp rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.shp diff --git a/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.shx b/matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.shx similarity index 100% rename from matsim/src/test/resources/test/input/org/matsim/core/utils/gis/ShapeFileWriterTest/testShapeFileWriter/test.shx rename to matsim/src/test/resources/test/input/org/matsim/core/utils/gis/GeoFileWriterTest/testShapeFileWriter/test.shx