private void makeLinks() { PolylineFeatureFactory pl = new PolylineFeatureFactory.Builder() .setName("Link") .setCrs(MGC.getCRS("EPSG:32632")) .addAttribute("nr_veh", Integer.class) .addAttribute("flow", Double.class) .addAttribute("angle", Double.class) .create(); Collection<SimpleFeature> features = new ArrayList<SimpleFeature>(); for (LinkInfo li : this.lis) { Link l = li.getLink(); Coordinate[] coords = new Coordinate[] { MGC.coord2Coordinate(l.getFromNode().getCoord()), MGC.coord2Coordinate(l.getToNode().getCoord()) }; SimpleFeature ft = pl.createPolyline( coords, new Object[] {li.getVeh().size(), li.getFlow(), li.getAngle()}, li.getLink().getId().toString()); features.add(ft); } ShapeFileWriter.writeGeometries(features, this.debugDir + "/links.shp"); }
public SimpleFeature getFeature(final Link link) { return this.factory.createPolyline( new Coordinate[] { MGC.coord2Coordinate(link.getFromNode().getCoord()), MGC.coord2Coordinate(link.getToNode().getCoord()) }, new Object[] {link.getId().toString(), linkDeltas.get(link.getId()).delta}, null); }
public void runAccessibilityComputation() { final Network network = (Network) this.scenario.getNetwork(); ProgressBar bar = new ProgressBar(this.measuringPoints.getZones().size()); for (Zone<Id<Zone>> measurePoint : this.measuringPoints.getZones()) { bar.update(); Coord coord = MGC.point2Coord(measurePoint.getGeometry().getCentroid()); Point p = measurePoint.getGeometry().getCentroid(); final Coord coord1 = coord; Link nearestLink = NetworkUtils.getNearestLinkExactly(network, coord1); final Coord coord2 = coord; Node nearestNode = NetworkUtils.getNearestNode(network, coord2); Distances distance = NetworkUtil.getDistances2NodeViaGivenLink(coord, nearestLink, nearestNode); double distanceMeasuringPoint2Road_meter = distance.getDistancePoint2Intersection(); double walkTravelTime_h = distanceMeasuringPoint2Road_meter / this.walkSpeedMeterPerHour; // travel time from coord to network (node or link) if (boundary.contains(p)) this.freeSpeedGrid.setValue(walkTravelTime_h, p); } }
public void convertTransitSchedule(String file) { Config config = ConfigUtils.createConfig(); config.scenario().setUseTransit(true); config.scenario().setUseVehicles(true); Scenario scenario = ScenarioUtils.createScenario(config); TransitScheduleReader ts = new TransitScheduleReader(scenario); ts.readFile(file); PointFeatureFactory.Builder builder = new PointFeatureFactory.Builder(); builder.setName("nodes"); builder.addAttribute("id", String.class); PointFeatureFactory factory = builder.create(); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); for (TransitStopFacility stop : scenario.getTransitSchedule().getFacilities().values()) { features.add(factory.createPoint(MGC.coord2Coordinate(stop.getCoord()))); } ShapeFileWriter.writeGeometries( features, "C:/Users/Daniel/Documents/work/shared-svn/studies/countries/cl/Kai_und_Daniel/Visualisierungen/stops.shp"); }
private void initFeatureType() { this.factory = new PolylineFeatureFactory.Builder() .setCrs(MGC.getCRS(TransformationFactory.WGS84_UTM35S)) .setName("links") .addAttribute("ID", String.class) .addAttribute("flowDelta", Double.class) .create(); }
private Coord findClosestBuildingFromCoord(Coord coord) { Coord closest = coord; Coord ii = coord; double closestDistance = Double.MAX_VALUE; for (String key : this.buildingsMap.keySet()) { ii = MGC.point2Coord(this.buildingsMap.get(key).getCentroid()); double distance = CoordUtils.calcDistance(ii, coord); if (distance < closestDistance) { closestDistance = distance; closest = ii; } } return closest; }
public void convertNet2Shape(Network net, String crs, String outputFile) { SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder(); typeBuilder.setCRS(MGC.getCRS(crs)); typeBuilder.setName("link feature"); typeBuilder.add("Line String", LineString.class); typeBuilder.add("id", String.class); typeBuilder.add("length", Double.class); typeBuilder.add("freespeed", Double.class); typeBuilder.add("capacity", Double.class); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(typeBuilder.buildFeatureType()); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); for (Link link : net.getLinks().values()) { Coord from = link.getFromNode().getCoord(); Coord to = link.getToNode().getCoord(); SimpleFeature feature = builder.buildFeature( link.getId().toString(), new Object[] { new GeometryFactory() .createLineString( new Coordinate[] {MGC.coord2Coordinate(from), MGC.coord2Coordinate(to)}), link.getId().toString(), link.getLength(), link.getFreespeed(), link.getCapacity() }); features.add(feature); } ShapeFileWriter.writeGeometries(features, outputFile); }
private TransitStopFacility drawRandomStop( Geometry buffer, PRouteProvider pRouteProvider, Set<Id> stopsUsed) { List<TransitStopFacility> choiceSet = new LinkedList<TransitStopFacility>(); // find choice-set for (TransitStopFacility stop : pRouteProvider.getAllPStops()) { if (!stopsUsed.contains(stop.getId())) { if (buffer.contains(MGC.coord2Point(stop.getCoord()))) { choiceSet.add(stop); } } } return pRouteProvider.drawRandomStopFromList(choiceSet); }
public static void main(String[] args) { String netfile = null; String outputFileLs = null; String outputFileP = null; if (args.length == 0) { netfile = "d:\\Berlin\\berlin-fggeoinfo\\30_Run_20_percent\\20101005_run777_778\\network_modified_20100806_added_BBI_AS_cl.xml.gz"; // String netfile = "./test/scenarios/berlin/network.xml.gz"; EventsCompareConfig.eventsFileOne = "E:/run778/output/ITERS/it.900/run778.900.events.txt"; EventsCompareConfig.eventsFileTwo = "E:/run777/output/ITERS/it.900/run777.900.events.txt"; outputFileLs = "e:\\temp\\networkLs_abs.shp"; outputFileP = "e:\\temp\\networkP_abs.shp"; } else if (args.length == 3) { netfile = args[0]; outputFileLs = args[1]; outputFileP = args[2]; } else { log.error("Arguments cannot be interpreted. Aborting ..."); System.exit(-1); } ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig()); scenario.getConfig().global().setCoordinateSystem("DHDN_GK4"); log.info("loading network from " + netfile); final Network network = scenario.getNetwork(); new MatsimNetworkReader(scenario).readFile(netfile); log.info("done."); FeatureGeneratorBuilderImpl builder = new FeatureGeneratorBuilderImpl(network, "DHDN_GK4"); // builder.setFeatureGeneratorPrototype(CountVehOnLinksStringBasedFeatureGenerator.class); builder.setFeatureGeneratorPrototype(CountVehOnLinksStringBasedFeatureGenerator.class); builder.setWidthCoefficient(0.5); builder.setWidthCalculatorPrototype(LanesBasedWidthCalculator.class); new Links2ESRIShape(network, outputFileLs, builder).write(); CoordinateReferenceSystem crs = MGC.getCRS("DHDN_GK4"); builder.setWidthCoefficient(0.01); // builder.setFeatureGeneratorPrototype(CountVehOnLinksPolygonBasedFeatureGenerator.class); builder.setFeatureGeneratorPrototype(CountVehOnLinksPolygonBasedFeatureGenerator.class); builder.setWidthCalculatorPrototype(CapacityBasedWidthCalculator.class); builder.setCoordinateReferenceSystem(crs); new Links2ESRIShape(network, outputFileP, builder).write(); }
private Coord drawRandomPointFromGeometry(Geometry g) { Point p; double x, y; do { x = g.getEnvelopeInternal().getMinX() + random.nextDouble() * (g.getEnvelopeInternal().getMaxX() - g.getEnvelopeInternal().getMinX()); y = g.getEnvelopeInternal().getMinY() + random.nextDouble() * (g.getEnvelopeInternal().getMaxY() - g.getEnvelopeInternal().getMinY()); p = MGC.xy2Point(x, y); } while (!g.contains(p)); Coord coord = new Coord(p.getX(), p.getY()); return coord; }
public GeoPosition getNetworkCenter() { if (this.networkCenter != null) { return this.networkCenter; } Envelope e = new Envelope(); for (Node node : this.sc.getNetwork().getNodes().values()) { // ignore end nodes if (node.getId().toString().contains("en")) continue; e.expandToInclude(MGC.coord2Coordinate(node.getCoord())); } Coord centerC = new CoordImpl((e.getMaxX() + e.getMinX()) / 2, (e.getMaxY() + e.getMinY()) / 2); CoordinateTransformation ct2 = new GeotoolsTransformation(this.sc.getConfig().global().getCoordinateSystem(), "EPSG:4326"); centerC = ct2.transform(centerC); this.networkCenter = new GeoPosition(centerC.getY(), centerC.getX()); return this.networkCenter; }
private void makeVeh() { PointFeatureFactory pf = new PointFeatureFactory.Builder() .setName("vehicle") .setCrs(MGC.getCRS("EPSG:32632")) .addAttribute("angle", Double.class) .addAttribute("speed", Double.class) .create(); Collection<SimpleFeature> features = new ArrayList<SimpleFeature>(); int id = 0; for (LinkInfo li : this.lis) { for (SensorDataVehicle veh : li.getVeh()) { SimpleFeature ft = pf.createPoint( new Coordinate(veh.getX(), veh.getY()), new Object[] {veh.getAngle(), veh.getSpeed()}, id++ + ""); features.add(ft); } } ShapeFileWriter.writeGeometries(features, this.debugDir + "/vehicles.shp"); }
/** @author amit after Benjamin */ public class SpatialAveragingCongestion { private final Logger logger = Logger.getLogger(SpatialAveragingCongestion.class); private ExperiencedDelayHandler congestionPerLinkHandler; final double scalingFactor = 1.; private static final String runDir = "/Users/amit/Documents/repos/runs-svn/detEval/emissionCongestionInternalization/output/1pct/run9/"; private static final String runBAU = runDir + "/baseCaseCtd"; private static final String runNumber = runDir + "/ei"; private final String netFile1 = runBAU + "/output_network.xml.gz"; private final String munichShapeFile = "/Users/amit/Documents/repos/shared-svn/projects/detailedEval/Net/shapeFromVISUM/urbanSuburban/cityArea.shp"; private static String configFileBAU = runBAU + "/output_config.xml"; private final String eventsFileBAU = runBAU + "/ITERS/it.1500/1500.events.xml.gz"; private final String eventsFile2 = runNumber + "/ITERS/it.1500/1500.events.xml.gz"; private final String emissionFileBAU = runBAU + "/ITERS/it.1500/1500.emission.events.xml.gz"; private final String emissionFile2 = runNumber + "/ITERS/it.1500/1500.emission.events.xml.gz"; final CoordinateReferenceSystem targetCRS = MGC.getCRS("EPSG:20004"); final double xMin = 4452550.25; final double xMax = 4479483.33; final double yMin = 5324955.00; final double yMax = 5345696.81; final int noOfXbins = 160; final int noOfYbins = 120; final int noOfTimeBins = 1; // ======== final double smoothingRadius_m = 500.; final boolean line = true; // ======== final boolean compareToBAU = true; SpatialAveragingUtils sau; LocationFilter lf; double simulationEndTime; Scenario scenario; Network network; String outPathStub; SpatialAveragingUtilsExtended extended; EmissionsPerLinkWarmEventHandler warmHandler; public void run() { this.sau = new SpatialAveragingUtils( xMin, xMax, yMin, yMax, noOfXbins, noOfYbins, smoothingRadius_m, munichShapeFile, targetCRS); this.lf = new LocationFilter(); extended = new SpatialAveragingUtilsExtended(smoothingRadius_m); this.simulationEndTime = getEndTime(configFileBAU); scenario = loadScenario(netFile1); this.network = scenario.getNetwork(); processCongestions(eventsFileBAU); processEmissions(emissionFileBAU); Map<Double, Map<Id<Link>, Double>> time2LinkDelays = this.congestionPerLinkHandler.getDelayPerLinkAndTimeInterval(); // to keep the same demand in emission and congestion pricing, more logical is using demand from // warm emission analysis module. Map<Double, Map<Id<Link>, Double>> time2CountsPerLink = this.warmHandler.getTime2linkIdLeaveCount(); Map<Double, double[][]> time2WeightedCongestion = fillWeightedCongestionValues(filterLinks(time2LinkDelays)); Map<Double, double[][]> time2WeightedDemand = fillWeightedDemandValues(filterLinks(time2CountsPerLink)); this.congestionPerLinkHandler.reset(0); this.warmHandler.reset(0); Map<Double, double[][]> normalizedTime2WeightedCongestion = normalizeAllArrays(time2WeightedCongestion); Map<Double, double[][]> normalizedTime2WeightedDemand = normalizeAllArrays(time2WeightedDemand); /* Sum over weighted values for cell does not need to be normalized, since normalization cancels out. * Result is an average value for cell*/ Map<Double, double[][]> time2SpecificDelays = calculateSpecificDelaysPerBin(time2WeightedCongestion, time2WeightedDemand); if (line) { outPathStub = runDir + "/analysis/spatialPlots/rCongestionLine" + smoothingRadius_m; } else { outPathStub = runDir + "/analysis/spatialPlots/rCongestionPoint" + smoothingRadius_m; } for (double endOfTimeInterval : time2WeightedCongestion.keySet()) { this.sau.writeRoutput( normalizedTime2WeightedCongestion.get(endOfTimeInterval), outPathStub + ".sec" + endOfTimeInterval + ".txt"); this.sau.writeRoutput( normalizedTime2WeightedDemand.get(endOfTimeInterval), outPathStub + ".vkm." + endOfTimeInterval + ".txt"); this.sau.writeRoutput( time2SpecificDelays.get(endOfTimeInterval), outPathStub + ".secVkm." + endOfTimeInterval + ".txt"); } if (compareToBAU) { processCongestions(eventsFile2); processEmissions(emissionFile2); Map<Double, Map<Id<Link>, Double>> time2LinkDelays2 = this.congestionPerLinkHandler.getDelayPerLinkAndTimeInterval(); Map<Double, Map<Id<Link>, Double>> time2CountsPerLink2 = this.warmHandler.getTime2linkIdLeaveCount(); Map<Double, double[][]> time2WeightedCongestion2 = fillWeightedCongestionValues(filterLinks(time2LinkDelays2)); Map<Double, double[][]> normalizedTime2WeightedCongestion2 = normalizeAllArrays(time2WeightedCongestion2); Map<Double, double[][]> time2WeightedDemand2 = fillWeightedDemandValues(filterLinks(time2CountsPerLink2)); Map<Double, double[][]> normalizedTime2WeightedDemand2 = normalizeAllArrays(time2WeightedDemand2); /* Sum over weighted values for cell does not need to be normalized, since normalization canceles out. * Result is an average value for cell*/ Map<Double, double[][]> time2SpecificDelays2 = calculateSpecificDelaysPerBin(time2WeightedCongestion2, time2WeightedDemand2); //// Map<Double, double[][]> time2SpecificEmissions2 = // calculateSpecificEmissionsPerBin(time2NormalizedWeightedEmissions2, // time2NormalizedWeightedDemand2); // /* Sum over weighted values for cell is normalized to "per sqkm" (dependent on calcluateWeightOfLinkForCell) * Values NEED to be additive (e.g. vkm, g, counts, or AVERAGE g/vkm!) * Make sure coordinate system is metric */ Map<Double, double[][]> time2AbsoluteDelaysDifferences = calculateAbsoluteDifferencesPerBin( normalizedTime2WeightedCongestion, normalizedTime2WeightedCongestion2); Map<Double, double[][]> time2AbsoluteDemandDifferences = calculateAbsoluteDifferencesPerBin( normalizedTime2WeightedDemand, normalizedTime2WeightedDemand2); Map<Double, double[][]> time2SpecificCongestionDifferences = calculateAbsoluteDifferencesPerBin(time2SpecificDelays, time2SpecificDelays2); if (line) { outPathStub = runDir + "/analysis/spatialPlots/rCongestionWRTBAULine" + smoothingRadius_m; // runDirectory1 + "analysis/spatialAveraging/" + runNumber1 + // "." + lastIteration1; } else { outPathStub = runDir + "/analysis/spatialPlots/rCongestionWRTBAUPoint" + smoothingRadius_m; // runDirectory1 + "analysis/spatialAveraging/" + runNumber1 + // "." + lastIteration1; } for (double endOfTimeInterval : time2AbsoluteDemandDifferences.keySet()) { this.sau.writeRoutput( time2AbsoluteDelaysDifferences.get(endOfTimeInterval), outPathStub + ".sec." + endOfTimeInterval + ".txt"); this.sau.writeRoutput( time2AbsoluteDemandDifferences.get(endOfTimeInterval), outPathStub + ".vkm." + endOfTimeInterval + ".txt"); this.sau.writeRoutput( time2SpecificCongestionDifferences.get(endOfTimeInterval), outPathStub + ".secPerVkm." + endOfTimeInterval + ".txt"); } } } private Map<Double, double[][]> calculateSpecificDelaysPerBin( Map<Double, double[][]> time2weightedDelays, Map<Double, double[][]> time2weightedDemand) { Map<Double, double[][]> time2specificDelays = new HashMap<Double, double[][]>(); for (Double endOfTimeInterval : time2weightedDelays.keySet()) { double[][] specificDelays = new double[noOfXbins][noOfYbins]; for (int xIndex = 0; xIndex < noOfXbins; xIndex++) { for (int yIndex = 0; yIndex < noOfYbins; yIndex++) { specificDelays[xIndex][yIndex] = time2weightedDelays.get(endOfTimeInterval)[xIndex][yIndex] / time2weightedDemand.get(endOfTimeInterval)[xIndex][yIndex]; } } time2specificDelays.put(endOfTimeInterval, specificDelays); } return time2specificDelays; } private Map<Double, double[][]> normalizeAllArrays(Map<Double, double[][]> time2Array) { Map<Double, double[][]> time2NormalizedArray = new HashMap<Double, double[][]>(); for (Double endOfTimeInterval : time2Array.keySet()) { double[][] normalizedArray = this.sau.normalizeArray(time2Array.get(endOfTimeInterval)); time2NormalizedArray.put(endOfTimeInterval, normalizedArray); } return time2NormalizedArray; } private Map<Double, Map<Id<Link>, Double>> filterLinks( Map<Double, Map<Id<Link>, Double>> time2LinksData) { Map<Double, Map<Id<Link>, Double>> time2LinksDataFiltered = new HashMap<Double, Map<Id<Link>, Double>>(); for (Double endOfTimeInterval : time2LinksData.keySet()) { Map<Id<Link>, Double> linksData = time2LinksData.get(endOfTimeInterval); Map<Id<Link>, Double> linksDataFiltered = new HashMap<Id<Link>, Double>(); for (Link link : network.getLinks().values()) { Coord linkCoord = link.getCoord(); if (this.sau.isInResearchArea(linkCoord)) { Id<Link> linkId = link.getId(); if (linksData.get(linkId) == null) { linksDataFiltered.put(linkId, 0.); } else { linksDataFiltered.put(linkId, linksData.get(linkId)); } } } time2LinksDataFiltered.put(endOfTimeInterval, linksDataFiltered); } return time2LinksDataFiltered; } private Map<Double, double[][]> fillWeightedCongestionValues( Map<Double, Map<Id<Link>, Double>> map) { Map<Double, double[][]> time2weightedDelays = new HashMap<Double, double[][]>(); for (Double endOfTimeInterval : map.keySet()) { double[][] weightedDelays = new double[noOfXbins][noOfYbins]; for (Id<Link> linkId : map.get(endOfTimeInterval).keySet()) { Coord linkCoord = this.network.getLinks().get(linkId).getCoord(); double xLink = linkCoord.getX(); double yLink = linkCoord.getY(); Coord fromNodeCoord = this.network.getLinks().get(linkId).getFromNode().getCoord(); Coord toNodeCoord = this.network.getLinks().get(linkId).getToNode().getCoord(); double value = map.get(endOfTimeInterval).get(linkId); double scaledValue = this.scalingFactor * value; // TODO: maybe calculate the following once and look it up here? for (int xIndex = 0; xIndex < noOfXbins; xIndex++) { for (int yIndex = 0; yIndex < noOfYbins; yIndex++) { Coord cellCentroid = this.sau.findCellCentroid(xIndex, yIndex); double weightOfLinkForCell; if (line) { weightOfLinkForCell = extended.calculateWeightOfLineForCellV2( fromNodeCoord, toNodeCoord, cellCentroid.getX(), cellCentroid.getY()); } else { weightOfLinkForCell = this.sau.calculateWeightOfPointForCell( xLink, yLink, cellCentroid.getX(), cellCentroid.getY()); } weightedDelays[xIndex][yIndex] += weightOfLinkForCell * scaledValue; } } } time2weightedDelays.put(endOfTimeInterval, weightedDelays); } return time2weightedDelays; } private Map<Double, double[][]> fillWeightedDemandValues(Map<Double, Map<Id<Link>, Double>> map) { Map<Double, double[][]> time2weightedDemand = new HashMap<Double, double[][]>(); for (Double endOfTimeInterval : map.keySet()) { double[][] weightedDemand = new double[noOfXbins][noOfYbins]; for (Id<Link> linkId : map.get(endOfTimeInterval).keySet()) { Coord linkCoord = this.network.getLinks().get(linkId).getCoord(); double xLink = linkCoord.getX(); double yLink = linkCoord.getY(); double linkLength_km = this.network.getLinks().get(linkId).getLength() / 1000.; Coord fromNodeCoord = this.network.getLinks().get(linkId).getFromNode().getCoord(); Coord toNodeCoord = this.network.getLinks().get(linkId).getToNode().getCoord(); double count = map.get(endOfTimeInterval).get(linkId); double vkm = count * linkLength_km; double scaledVkm = this.scalingFactor * vkm; // TODO: maybe calculate the following once and look it up here? for (int xIndex = 0; xIndex < noOfXbins; xIndex++) { for (int yIndex = 0; yIndex < noOfYbins; yIndex++) { Coord cellCentroid = this.sau.findCellCentroid(xIndex, yIndex); double weightOfLinkForCell; if (line) { weightOfLinkForCell = extended.calculateWeightOfLineForCellV2( fromNodeCoord, toNodeCoord, cellCentroid.getX(), cellCentroid.getY()); } else { weightOfLinkForCell = this.sau.calculateWeightOfPointForCell( xLink, yLink, cellCentroid.getX(), cellCentroid.getY()); } weightedDemand[xIndex][yIndex] += weightOfLinkForCell * scaledVkm; } } } time2weightedDemand.put(endOfTimeInterval, weightedDemand); } return time2weightedDemand; } private Map<Double, double[][]> calculateAbsoluteDifferencesPerBin( Map<Double, double[][]> time2weightedValues1, Map<Double, double[][]> time2weightedValues2) { Map<Double, double[][]> time2absoluteDifferences = new HashMap<Double, double[][]>(); for (Double endOfTimeInterval : time2weightedValues1.keySet()) { double[][] absoluteDifferences = new double[noOfXbins][noOfYbins]; for (int xIndex = 0; xIndex < noOfXbins; xIndex++) { for (int yIndex = 0; yIndex < noOfYbins; yIndex++) { absoluteDifferences[xIndex][yIndex] = time2weightedValues2.get(endOfTimeInterval)[xIndex][yIndex] - time2weightedValues1.get(endOfTimeInterval)[xIndex][yIndex]; } } time2absoluteDifferences.put(endOfTimeInterval, absoluteDifferences); } return time2absoluteDifferences; } private void processCongestions(String eventFile) { EventsManager eventsManager = EventsUtils.createEventsManager(); MatsimEventsReader eventsReader = new MatsimEventsReader(eventsManager); this.congestionPerLinkHandler = new ExperiencedDelayHandler(scenario, noOfTimeBins); eventsManager.addHandler(this.congestionPerLinkHandler); eventsReader.readFile(eventFile); } private void processEmissions(String emissionFile) { EventsManager eventsManager = EventsUtils.createEventsManager(); EmissionEventsReader emissionReader = new EmissionEventsReader(eventsManager); this.warmHandler = new EmissionsPerLinkWarmEventHandler(this.simulationEndTime, noOfTimeBins); eventsManager.addHandler(this.warmHandler); emissionReader.parse(emissionFile); } private Scenario loadScenario(String netFile) { Config config = ConfigUtils.createConfig(); config.network().setInputFile(netFile); Scenario scenario = ScenarioUtils.loadScenario(config); return scenario; } private Double getEndTime(String configfile) { Config config = ConfigUtils.createConfig(); ConfigReader configReader = new ConfigReader(config); configReader.readFile(configfile); Double endTime = config.qsim().getEndTime(); logger.info("Simulation end time is: " + endTime / 3600 + " hours."); logger.info( "Aggregating emissions for " + (int) (endTime / 3600 / noOfTimeBins) + " hour time bins."); return endTime; } public static void main(String[] args) { SpatialAveragingCongestion sac = new SpatialAveragingCongestion(); sac.run(); } }
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; String populationOutputDirectory = baseDir + "cb_spn_gemeinde_nachfrage_landuse_ohneTagebau/"; // 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); File shapes = new File(shapesOutputDirectory); 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(); Collection<SimpleFeature> gemeindenFeatures = gemeindenReader.readFileAndInitialize(gemeindenBrandenburgShapeFile); CommuterDemandWriter cdw = new CommuterDemandWriter( gemeindenFeatures, gemeindenReader.getCoordinateSystem(), cdr.getCommuterRelations(), MGC.getCRS(TransformationFactory.WGS84_UTM33N)); // landuse if (useLanduse) { DgLanduseReader landuseReader = new DgLanduseReader(); Tuple<Collection<SimpleFeature>, CoordinateReferenceSystem> homeLanduse = landuseReader.readLanduseDataHome(); Tuple<Collection<SimpleFeature>, CoordinateReferenceSystem> workLanduse = landuseReader.readLanduseDataWork(); 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(); }
public static void main(String[] args) { // Parameters Integer planningAreaId = 11000000; boolean onlyCar = false; // car; new, should be used for runs with ChangeLedModes enabled boolean onlyInterior = false; // int boolean onlyBerlinBased = true; // ber; usually varied for analysis boolean distanceFilter = true; // dist; usually varied for analysis // double minDistance = 0; double maxDistance = 100; boolean onlyWorkTrips = false; // NEW // -------------------------------------------------------------------------------------------------- boolean ageFilter = false; Integer minAge = 80; Integer maxAge = 119; // -------------------------------------------------------------------------------------------------- String runId = "run_168a"; // String runId = "run791"; String usedIteration = "300"; // most frequently used value: 150 // String usedIteration = "600"; int maxBinDuration = 120; int binWidthDuration = 1; // int binWidthDuration = 5; int maxBinTime = 23; int binWidthTime = 1; int maxBinDistance = 60; int binWidthDistance = 1; // int binWidthDistance = 5; int maxBinSpeed = 60; int binWidthSpeed = 1; // int binWidthSpeed = 5; // Input and output files String networkFile = "/Users/dominik/Workspace/shared-svn/studies/countries/de/berlin/counts/iv_counts/network.xml"; // String networkFile = // "D:/Workspace/shared-svn/studies/countries/de/berlin/counts/iv_counts/network.xml"; // String networkFile = "D:/Workspace/runs-svn/" + runId + // "/counts_network_merged.xml_cl.xml.gz"; // String eventsFile = "D:/Workspace/data/cemdapMatsimCadyts/output/" + runId + "/ITERS/it." // + usedIteration + "/" // String eventsFile = "D:/Workspace/runs-svn/" + runId + "/output_rerun/ITERS/it." + // usedIteration + "/" // + runId + "." + usedIteration + ".events.txt.gz"; // String eventsFile = "D:/Workspace/runs-svn/cemdapMatsimCadyts/" + runId + "/ITERS/it." + // usedIteration + "/" // + runId + "." + usedIteration + ".events.xml.gz"; String eventsFile = "/Users/dominik/Workspace/runs-svn/cemdapMatsimCadyts/" + runId + "/ITERS/it." + usedIteration + "/" + runId + "." + usedIteration + ".events.xml.gz"; // String cemdapPersonFile = // "D:/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/19/persons1.dat"; // wrong!!! // String cemdapPersonFile = // "D:/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/18/persons1.dat"; // String cemdapPersonFile = // "D:/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/21/persons1.dat"; String cemdapPersonFile = "/Users/dominik/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/21/persons1.dat"; // String outputDirectory = "D:/Workspace/data/cemdapMatsimCadyts/output/" + runId + // "/analysis"; // String outputDirectory = "D:/Workspace/runs-svn/cemdapMatsimCadyts/" + runId + // "/analysis"; String outputDirectory = "/Users/dominik/Workspace/runs-svn/cemdapMatsimCadyts/" + runId + "/analysis"; // String outputDirectory = "D:/Workspace/runs-svn/other/" + runId + "/analysis"; // String shapeFileBerlin = // "D:/Workspace/data/cemdapMatsimCadyts/input/shapefiles/Berlin_DHDN_GK4.shp"; String shapeFileBerlin = "/Users/dominik/Workspace/data/cemdapMatsimCadyts/input/shapefiles/Berlin_DHDN_GK4.shp"; Map<Integer, Geometry> zoneGeometries = ShapeReader.read(shapeFileBerlin, "NR"); Geometry berlinGeometry = zoneGeometries.get(planningAreaId); // Output naming Integer usedIt = Integer.parseInt(usedIteration); if (!usedIt.equals(150)) { outputDirectory = outputDirectory + "_" + usedIteration; } // -------------------------------------------------------------------------------------------------- if (onlyCar == true) { outputDirectory = outputDirectory + "_car"; } // -------------------------------------------------------------------------------------------------- if (onlyInterior == true) { outputDirectory = outputDirectory + "_int"; } if (onlyBerlinBased == true) { outputDirectory = outputDirectory + "_ber"; } if (distanceFilter == true) { outputDirectory = outputDirectory + "_dist"; } // -------------------------------------------------------------------------------------------------- if (onlyWorkTrips == true) { outputDirectory = outputDirectory + "_work"; } // -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------- if (ageFilter == true) { outputDirectory = outputDirectory + "_" + minAge.toString(); outputDirectory = outputDirectory + "_" + maxAge.toString(); } // -------------------------------------------------------------------------------------------------- // Create an EventsManager instance (MATSim infrastructure) EventsManager eventsManager = EventsUtils.createEventsManager(); TripHandler handler = new TripHandler(); eventsManager.addHandler(handler); // Connect a file reader to the EventsManager and read in the event file MatsimEventsReader reader = new MatsimEventsReader(eventsManager); reader.readFile(eventsFile); System.out.println("Events file read!"); // check if all trips have been completed; if so, result will be zero int numberOfIncompleteTrips = 0; for (Trip trip : handler.getTrips().values()) { if (!trip.getTripComplete()) { numberOfIncompleteTrips++; } } System.out.println(numberOfIncompleteTrips + " trips are incomplete."); // -------------------------------------------------------------------------------------------------- CemdapPersonFileReader cemdapPersonFileReader = new CemdapPersonFileReader(); if (ageFilter == true) { // TODO needs to be adapted for other analyses that are based on person-specific attributes as // well // so far age is the only one // parse person file cemdapPersonFileReader.parse(cemdapPersonFile); } // -------------------------------------------------------------------------------------------------- // get network, which is needed to calculate distances Config config = ConfigUtils.createConfig(); Scenario scenario = ScenarioUtils.createScenario(config); MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario); networkReader.readFile(networkFile); Network network = scenario.getNetwork(); // create objects int tripCounter = 0; int tripCounterSpeed = 0; int tripCounterIncomplete = 0; Map<Integer, Double> tripDurationMap = new TreeMap<Integer, Double>(); double aggregateTripDuration = 0.; Map<Integer, Double> departureTimeMap = new TreeMap<Integer, Double>(); Map<String, Double> activityTypeMap = new TreeMap<String, Double>(); Map<Integer, Double> tripDistanceRoutedMap = new TreeMap<Integer, Double>(); double aggregateTripDistanceRouted = 0.; Map<Integer, Double> tripDistanceBeelineMap = new TreeMap<Integer, Double>(); double aggregateTripDistanceBeeline = 0.; Map<Integer, Double> averageTripSpeedRoutedMap = new TreeMap<Integer, Double>(); double aggregateOfAverageTripSpeedsRouted = 0.; Map<Integer, Double> averageTripSpeedBeelineMap = new TreeMap<Integer, Double>(); double aggregateOfAverageTripSpeedsBeeline = 0.; int numberOfTripsWithNoCalculableSpeed = 0; Map<Id<Trip>, Double> distanceRoutedMap = new TreeMap<Id<Trip>, Double>(); Map<Id<Trip>, Double> distanceBeelineMap = new TreeMap<Id<Trip>, Double>(); Map<String, Integer> otherInformationMap = new TreeMap<String, Integer>(); // -------------------------------------------------------------------------------------------------- ObjectAttributes personActivityAttributes = new ObjectAttributes(); // -------------------------------------------------------------------------------------------------- // do calculations for (Trip trip : handler.getTrips().values()) { if (trip.getTripComplete()) { boolean considerTrip = false; // get coordinates of links Id<Link> departureLinkId = trip.getDepartureLinkId(); Id<Link> arrivalLinkId = trip.getArrivalLinkId(); Link departureLink = network.getLinks().get(departureLinkId); Link arrivalLink = network.getLinks().get(arrivalLinkId); double arrivalCoordX = arrivalLink.getCoord().getX(); double arrivalCoordY = arrivalLink.getCoord().getY(); double departureCoordX = departureLink.getCoord().getX(); double departureCoordY = departureLink.getCoord().getY(); // calculate (beeline) distance double horizontalDistanceInMeter = (Math.abs(departureCoordX - arrivalCoordX)) / 1000; double verticalDistanceInMeter = (Math.abs(departureCoordY - arrivalCoordY)) / 1000; double tripDistanceBeeline = Math.sqrt( horizontalDistanceInMeter * horizontalDistanceInMeter + verticalDistanceInMeter * verticalDistanceInMeter); // create points Point arrivalLocation = MGC.xy2Point(arrivalCoordX, arrivalCoordY); Point departureLocation = MGC.xy2Point(departureCoordX, departureCoordY); // choose if trip will be considered // Note: Check of "interior"/"berlinBased" has to come first since this sets the // "considerTrip" // variable to true. if (onlyInterior == true) { if (berlinGeometry.contains(arrivalLocation) && berlinGeometry.contains(departureLocation)) { considerTrip = true; } } else if (onlyBerlinBased == true) { if (berlinGeometry.contains(arrivalLocation) || berlinGeometry.contains(departureLocation)) { considerTrip = true; } } else { considerTrip = true; } // -------------------------------------------------------------------------------------------------- // if (!trip.getMode().equals("car") && !trip.getMode().equals("pt")) { // throw new RuntimeException("In current implementation leg mode must either be car or // pt"); // } if (onlyCar == true) { if (!trip.getMode().equals("car")) { considerTrip = false; } } // -------------------------------------------------------------------------------------------------- if (distanceFilter == true && tripDistanceBeeline >= maxDistance) { considerTrip = false; } // if (distanceFilter == true && tripDistanceBeeline <= minDistance) { // considerTrip = false; // } // -------------------------------------------------------------------------------------------------------------------- if (onlyWorkTrips == true) { boolean doesWorkTrip = false; if (trip.getActivityEndActType().equals("work")) { doesWorkTrip = true; } if (doesWorkTrip == true) { // can be varied considerTrip = false; } } // -------------------------------------------------------------------------------------------------------------------- // write person activity attributes // if (trip.getActivityEndActType().equals("work")) { // personActivityAttributes.putAttribute(trip.getDriverId(), "hasWorkActivity", // true); // } // TODO The plan was to claculated activity-chain frequencies here... // -------------------------------------------------------------------------------------------------- // PERSON-SPECIFIC ATTRIBUTES if (ageFilter == true) { // TODO needs to be adapted for other analyses that are based on person-specific // attributes as well // so far age is the only one String personId = trip.getPersonId().toString(); int age = (int) cemdapPersonFileReader.getPersonAttributes().getAttribute(personId, "age"); if (age < minAge) { considerTrip = false; } if (age > maxAge) { considerTrip = false; } } // -------------------------------------------------------------------------------------------------- if (considerTrip == true) { tripCounter++; // calculate travel times and store them in a map // trip.getArrivalTime() / trip.getDepartureTime() yields values in seconds! double departureTimeInSeconds = trip.getDepartureTime(); double arrivalTimeInSeconds = trip.getArrivalTime(); double tripDurationInSeconds = arrivalTimeInSeconds - departureTimeInSeconds; double tripDurationInMinutes = tripDurationInSeconds / 60.; double tripDurationInHours = tripDurationInMinutes / 60.; // addToMapIntegerKey(tripDurationMap, tripDurationInMinutes, 5, 120); addToMapIntegerKey( tripDurationMap, tripDurationInMinutes, binWidthDuration, maxBinDuration, 1.); aggregateTripDuration = aggregateTripDuration + tripDurationInMinutes; // store departure times in a map double departureTimeInHours = departureTimeInSeconds / 3600.; addToMapIntegerKey(departureTimeMap, departureTimeInHours, binWidthTime, maxBinTime, 1.); // store activities in a map String activityType = trip.getActivityStartActType(); addToMapStringKey(activityTypeMap, activityType); // calculate (routed) distances and and store them in a map double tripDistanceMeter = 0.; for (int i = 0; i < trip.getLinks().size(); i++) { Id<Link> linkId = trip.getLinks().get(i); Link link = network.getLinks().get(linkId); double length = link.getLength(); tripDistanceMeter = tripDistanceMeter + length; } // TODO here, the distances from activity to link and link to activity are missing! double tripDistanceRouted = tripDistanceMeter / 1000.; // store (routed) distances in a map addToMapIntegerKey( tripDistanceRoutedMap, tripDistanceRouted, binWidthDistance, maxBinDistance, 1.); aggregateTripDistanceRouted = aggregateTripDistanceRouted + tripDistanceRouted; distanceRoutedMap.put(trip.getTripId(), tripDistanceRouted); // store (beeline) distances in a map addToMapIntegerKey( tripDistanceBeelineMap, tripDistanceBeeline, binWidthDistance, maxBinDistance, 1.); aggregateTripDistanceBeeline = aggregateTripDistanceBeeline + tripDistanceBeeline; distanceBeelineMap.put(trip.getTripId(), tripDistanceBeeline); // calculate speeds and and store them in a map if (tripDurationInHours > 0.) { // System.out.println("trip distance is " + tripDistance + " and time is " + // timeInHours); double averageTripSpeedRouted = tripDistanceRouted / tripDurationInHours; addToMapIntegerKey( averageTripSpeedRoutedMap, averageTripSpeedRouted, binWidthSpeed, maxBinSpeed, 1.); aggregateOfAverageTripSpeedsRouted = aggregateOfAverageTripSpeedsRouted + averageTripSpeedRouted; double averageTripSpeedBeeline = tripDistanceBeeline / tripDurationInHours; addToMapIntegerKey( averageTripSpeedBeelineMap, averageTripSpeedBeeline, binWidthSpeed, maxBinSpeed, 1.); aggregateOfAverageTripSpeedsBeeline = aggregateOfAverageTripSpeedsBeeline + averageTripSpeedBeeline; tripCounterSpeed++; } else { numberOfTripsWithNoCalculableSpeed++; } } } else { System.err.println("Trip is not complete!"); tripCounterIncomplete++; // Until now, the only case where incomplete trips happen is when agents are removed // according to "removeStuckVehicles = true" // Since a removed agent can at most have one incomplete trip (this incomplete trip is // exactly the event when he is removed) // the number of incomplete trips should be equal to the number of removed agents } } double averageTripDuration = aggregateTripDuration / tripCounter; double averageTripDistanceRouted = aggregateTripDistanceRouted / tripCounter; double averageTripDistanceBeeline = aggregateTripDistanceBeeline / tripCounter; double averageOfAverageTripSpeedsRouted = aggregateOfAverageTripSpeedsRouted / tripCounterSpeed; double averageOfAverageTripSpeedsBeeline = aggregateOfAverageTripSpeedsBeeline / tripCounterSpeed; otherInformationMap.put( "Number of trips that have no previous activity", handler.getNoPreviousEndOfActivityCounter()); otherInformationMap.put( "Number of trips that have no calculable speed", numberOfTripsWithNoCalculableSpeed); otherInformationMap.put( "Number of incomplete trips (i.e. number of removed agents)", tripCounterIncomplete); otherInformationMap.put("Number of (complete) trips", tripCounter); // write results to files new File(outputDirectory).mkdir(); AnalysisFileWriter writer = new AnalysisFileWriter(); writer.writeToFileIntegerKey( tripDurationMap, outputDirectory + "/tripDuration.txt", binWidthDuration, tripCounter, averageTripDuration); writer.writeToFileIntegerKey( departureTimeMap, outputDirectory + "/departureTime.txt", binWidthTime, tripCounter, averageTripDuration); writer.writeToFileStringKey( activityTypeMap, outputDirectory + "/activityTypes.txt", tripCounter); writer.writeToFileIntegerKey( tripDistanceRoutedMap, outputDirectory + "/tripDistanceRouted.txt", binWidthDistance, tripCounter, averageTripDistanceRouted); writer.writeToFileIntegerKey( tripDistanceBeelineMap, outputDirectory + "/tripDistanceBeeline.txt", binWidthDistance, tripCounter, averageTripDistanceBeeline); writer.writeToFileIntegerKey( averageTripSpeedRoutedMap, outputDirectory + "/averageTripSpeedRouted.txt", binWidthSpeed, tripCounterSpeed, averageOfAverageTripSpeedsRouted); writer.writeToFileIntegerKey( averageTripSpeedBeelineMap, outputDirectory + "/averageTripSpeedBeeline.txt", binWidthSpeed, tripCounterSpeed, averageOfAverageTripSpeedsBeeline); writer.writeToFileIntegerKeyCumulative( tripDurationMap, outputDirectory + "/tripDurationCumulative.txt", binWidthDuration, tripCounter, averageTripDuration); writer.writeToFileIntegerKeyCumulative( tripDistanceBeelineMap, outputDirectory + "/tripDistanceBeelineCumulative.txt", binWidthDistance, tripCounter, averageTripDistanceBeeline); writer.writeToFileIntegerKeyCumulative( averageTripSpeedBeelineMap, outputDirectory + "/averageTripSpeedBeelineCumulative.txt", binWidthSpeed, tripCounterSpeed, averageOfAverageTripSpeedsBeeline); writer.writeToFileOther(otherInformationMap, outputDirectory + "/otherInformation.txt"); // write a routed distance vs. beeline distance comparison file writer.writeRoutedBeelineDistanceComparisonFile( distanceRoutedMap, distanceBeelineMap, outputDirectory + "/beeline.txt", tripCounter); }
private boolean isBuildingInZone(Geometry zone, Coord building) { ; Point p = MGC.xy2Point(building.getX(), building.getY()); return zone.contains(p); }