private int addStopOnLink(Link link) { if (link == null) { return 0; } if (linkToNodeNotInServiceArea(link)) { return 0; } if (linkHasAlreadyAFormalPTStopFromTheGivenSchedule(link)) { return 0; } if (link.getFreespeed() >= this.pConfigGroup.getSpeedLimitForStops()) { return 0; } if (this.linkId2StopFacilityMap.get(link.getId()) != null) { log.warn("Link " + link.getId() + " has already a stop. This should not happen. Check code."); return 0; } Id<TransitStopFacility> 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; }
private void writeFile() throws Exception { FileOutputStream fos = null; OutputStreamWriter osw = null; BufferedWriter bw = null; fos = new FileOutputStream(outFile); osw = new OutputStreamWriter(fos, charset); bw = new BufferedWriter(osw); for (Link link : scenario.getNetwork().getLinks().values()) { StringBuffer sb = new StringBuffer(); sb.append(link.getId()); double[] meanArray = meanCounts.get(link.getId()); for (double mean : meanArray) { sb.append(separator); sb.append(mean); } bw.write(sb.toString()); bw.write("\n"); } bw.close(); osw.close(); fos.close(); }
private void assignVolumesToLinks(final NetworkImpl network) { computeTotalLinkCapacities(network); Iterator<Integer> n_it = this.fromZone.getNodes().iterator(); while (n_it.hasNext()) { Integer n_i = n_it.next(); Node node = network.getNodes().get(Id.create(n_i, Node.class)); for (Link l : node.getOutLinks().values()) { if (this.totalOutLinkCapacity > 0.0) { this.outLinkVolumes.add( new MyLink(l.getId(), this.volume * l.getCapacity() / this.totalOutLinkCapacity)); } else { this.outLinkVolumes.add(new MyLink(l.getId(), 0.0)); } } } n_it = this.toZone.getNodes().iterator(); while (n_it.hasNext()) { Integer n_i = n_it.next(); Node node = network.getNodes().get(Id.create(n_i, Node.class)); for (Link l : node.getInLinks().values()) { if (this.totalInLinkCapacity > 0.0) { this.inLinkVolumes.add( new MyLink(l.getId(), this.volume * l.getCapacity() / this.totalInLinkCapacity)); } else { this.inLinkVolumes.add(new MyLink(l.getId(), 0.0)); } } // for } // while } // assignVolumesToLinks
public MeanQueueLengthCalculator() throws Exception { scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig()); new MatsimNetworkReader(scenario).readFile(networkFile); linkInfos = new HashMap<Id, LinkInfo>(); counts = new HashMap<Id, AtomicInteger>(); sumCountsPerHour = new HashMap<Id, AtomicInteger>(); meanCounts = new HashMap<Id, double[]>(); for (Link link : scenario.getNetwork().getLinks().values()) { linkInfos.put(link.getId(), new LinkInfo(link.getId())); counts.put(link.getId(), new AtomicInteger()); sumCountsPerHour.put(link.getId(), new AtomicInteger()); meanCounts.put(link.getId(), new double[hours]); } log.info("start reading events file..."); EventsManager eventsManager = (EventsManager) EventsUtils.createEventsManager(); eventsManager.addHandler(this); MatsimEventsReader eventsReader = new MatsimEventsReader(eventsManager); eventsReader.readFile(eventsFile); log.info("done."); for (LinkInfo linkInfo : linkInfos.values()) { getLinkStatistic(linkInfo); } log.info("start writing file..."); writeFile(); log.info("done."); }
private void computeDelays(AfterMobsimEvent event) { TravelTime travelTime = event.getServices().getLinkTravelTimes(); int timeBinSize = this.congestionInfo.getScenario().getConfig().travelTimeCalculator().getTraveltimeBinSize(); for (Link link : this.congestionInfo.getScenario().getNetwork().getLinks().values()) { Map<Integer, Double> time2avgDelay = new HashMap<>(); double freespeedTravelTime = link.getLength() / link.getFreespeed(); int timeBinCounter = 0; for (int endTime = timeBinSize; endTime <= this.congestionInfo.getScenario().getConfig().travelTimeCalculator().getMaxTime(); endTime = endTime + timeBinSize) { double avgDelay = travelTime.getLinkTravelTime(link, (endTime - timeBinSize / 2.), null, null) - freespeedTravelTime; time2avgDelay.put(timeBinCounter, avgDelay); timeBinCounter++; } if (this.congestionInfo.getlinkInfos().containsKey(link.getId())) { this.congestionInfo.getlinkInfos().get(link.getId()).setTime2avgDelay(time2avgDelay); } else { LinkInfo linkInfo = new LinkInfo(link.getId()); linkInfo.setTime2avgDelay(time2avgDelay); this.congestionInfo.getlinkInfos().put(link.getId(), linkInfo); } } }
private SimpleFeature createFeature( Link link, GeometryFactory geofac, PolygonFeatureFactory factory, List<CountSimComparison> countSimLinkLeaveComparisonList, Double linkDelay1, Double linkDelay2) { Coordinate[] coords = PolygonFeatureGenerator.createPolygonCoordsForLink(link, 20.0); Object[] attribs = new Object[10 + 5 * (numberOfHours + 1) + 1]; attribs[0] = link.getId().toString(); attribs[1] = link.getFromNode().getId().toString(); attribs[2] = link.getToNode().getId().toString(); attribs[3] = link.getLength(); attribs[4] = link.getFreespeed(); attribs[5] = link.getCapacity(); attribs[6] = link.getNumberOfLanes(); attribs[7] = link.getNumberOfLanes(); attribs[8] = ((LinkImpl) link).getType(); // total delay caused by the link attribs[9] = linkDelay1; attribs[10] = linkDelay2; int i = 11; double sumAbsLinkLeaveDif = 0.0; double absLinkLeaveDif = 0.0; double sumAbsLinkLeaveRun1 = 0.0; double sumAbsLinkLeaveRun2 = 0.0; for (CountSimComparison csc : countSimLinkLeaveComparisonList) { // analyze only the selected time period if (csc.getHour() > firstHour && csc.getHour() <= lastHour) { // csc contains the number of link leave events in the time period between csc.getHour()-1 // and csc.getHour() absLinkLeaveDif = csc.getSimulationValue() - csc.getCountValue(); attribs[i] = csc.getCountValue(); attribs[i + numberOfHours + 1] = csc.getSimulationValue(); attribs[i + 2 * (numberOfHours + 1)] = absLinkLeaveDif; attribs[i + 3 * (numberOfHours + 1)] = (absLinkLeaveDif / link.getCapacity()) * 100; // in percent attribs[i + 4 * (numberOfHours + 1)] = absLinkLeaveDif * link.getLength(); sumAbsLinkLeaveDif += absLinkLeaveDif; sumAbsLinkLeaveRun1 += csc.getCountValue(); sumAbsLinkLeaveRun2 += csc.getSimulationValue(); i++; } } attribs[10 + numberOfHours + 1] = sumAbsLinkLeaveRun1; attribs[10 + 2 * (numberOfHours + 1)] = sumAbsLinkLeaveRun2; attribs[10 + 3 * (numberOfHours + 1)] = sumAbsLinkLeaveDif; // C: meanAbsLinkLeaveDif = sumAbsLinkLeaveDif/5 // mean (error/capacity) in percent per hour, i.e flow difference of the morning peak divided by // the maximal link capacity in this time period attribs[10 + 4 * (numberOfHours + 1)] = (sumAbsLinkLeaveDif / (link.getCapacity() * 5)) * 100; attribs[10 + 5 * (numberOfHours + 1)] = sumAbsLinkLeaveDif * link.getLength(); // alternative: meanAbsLinkLeaveDif*link.getLength(); return factory.createPolygon(coords, attribs, link.getId().toString()); }
public static void main(String[] args) { String path2MATSimNetwork = args[0]; MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario.getNetwork()); networkReader.readFile(path2MATSimNetwork); Network network = scenario.getNetwork(); String speedFactor = args[1]; String capacityFactor = args[2]; radius = Integer.parseInt(args[3]); final BufferedWriter out = IOUtils.getBufferedWriter(args[4]); try { // Header out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.newLine(); out.write( "<networkChangeEvents xmlns=\"http://www.matsim.org/files/dtd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.matsim.org/files/dtd http://www.matsim.org/files/dtd/networkChangeEvents.xsd\">"); out.newLine(); // reduce capacity and speed: out.write(" <networkChangeEvent startTime=\"07:00:00\">"); out.newLine(); for (Link link : network.getLinks().values()) { if (isLinkAffected(link)) { out.write(" <link refId=\"" + link.getId().toString() + "\"/>"); out.newLine(); } } out.write(" <flowCapacity type=\"scaleFactor\" value=\"" + capacityFactor + "\"/>"); out.newLine(); out.write(" <freespeed type=\"scaleFactor\" value=\"" + speedFactor + "\"/>"); out.newLine(); out.write(" </networkChangeEvent>"); out.newLine(); // reset capacity and speed: for (Link link : network.getLinks().values()) { if (isLinkAffected(link)) { out.write(" <networkChangeEvent startTime=\"09:00:00\">"); out.newLine(); out.write(" <link refId=\"" + link.getId().toString() + "\"/>"); out.newLine(); out.write( " <flowCapacity type=\"absolute\" value=\"" + link.getCapacity() + "\"/>"); out.newLine(); out.write(" <freespeed type=\"absolute\" value=\"" + link.getFreespeed() + "\"/>"); out.newLine(); out.write(" </networkChangeEvent>"); out.newLine(); } } // Footer: out.write("</networkChangeEvents>"); out.newLine(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
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); }
// Create external Facilities that are used by transit traffic agents. private static void createExternalFacilities(Scenario scenario, Set<Id<Node>> externalNodes) { ActivityFacilities activityFacilities = scenario.getActivityFacilities(); ActivityFacilitiesFactory factory = activityFacilities.getFactory(); /* * We check for all OutLinks of all external nodes if they already host a facility. If not, * a new facility with a tta ActivityOption will be created and added. */ for (Id<Node> id : externalNodes) { Node externalNode = scenario.getNetwork().getNodes().get(id); for (Link externalLink : externalNode.getOutLinks().values()) { ActivityFacility facility = activityFacilities.getFacilities().get(externalLink.getId()); // if already a facility exists we have nothing left to do if (facility != null) continue; /* * No Facility exists at that link therefore we create and add a new one. */ double fromX = externalLink.getFromNode().getCoord().getX(); double fromY = externalLink.getFromNode().getCoord().getY(); double toX = externalLink.getToNode().getCoord().getX(); double toY = externalLink.getToNode().getCoord().getY(); double dX = toX - fromX; double dY = toY - fromY; double length = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2)); double centerX = externalLink.getCoord().getX(); double centerY = externalLink.getCoord().getY(); /* * Unit vector that directs with an angle of 90° away from the link. */ double unitVectorX = dY / length; double unitVectorY = -dX / length; Coord coord = new Coord(centerX + unitVectorX, centerY + unitVectorY); facility = activityFacilities .getFactory() .createActivityFacility( Id.create(externalLink.getId().toString(), ActivityFacility.class), coord); activityFacilities.addActivityFacility(facility); ((ActivityFacilityImpl) facility).setLinkId(externalLink.getId()); ActivityOption activityOption = factory.createActivityOption(ttaActivityType); activityOption.addOpeningTime(new OpeningTimeImpl(0 * 3600, 24 * 3600)); activityOption.setCapacity(capacity); facility.addActivityOption(activityOption); } } }
private boolean linkHasAlreadyAFormalPTStopFromTheGivenSchedule(Link link) { if (this.linkId2StopFacilityMap.containsKey(link.getId())) { // There is already a stop at this link, used by formal public transport - Use this one // instead this.transitSchedule.addStopFacility(this.linkId2StopFacilityMap.get(link.getId())); return true; } else { return false; } }
public void createNearestChargerDb() { this.nearestChargers = new HashMap<Id, Link>(); for (Link l : optimConfig.context.getScenario().getNetwork().getLinks().values()) { Link chargerLink = findNearestCharger(l.getId()); this.nearestChargers.put(l.getId(), chargerLink); } log.info("...done"); }
private TransitRoute createRoute( Id<TransitRoute> routeID, TransitStopFacility startStop, TransitStopFacility endStop) { FreespeedTravelTimeAndDisutility tC = new FreespeedTravelTimeAndDisutility(-6.0, 0.0, 0.0); LeastCostPathCalculator routingAlgo = new Dijkstra(this.net, tC, tC); Node startNode = this.net.getLinks().get(startStop.getLinkId()).getToNode(); Node endNode = this.net.getLinks().get(endStop.getLinkId()).getFromNode(); int startTime = 0 * 3600; // get Route Path path = routingAlgo.calcLeastCostPath(startNode, endNode, startTime, null, null); NetworkRoute route = new LinkNetworkRouteImpl(startStop.getLinkId(), endStop.getLinkId()); route.setLinkIds( startStop.getLinkId(), NetworkUtils.getLinkIds(path.links), endStop.getLinkId()); // get stops at Route List<TransitRouteStop> stops = new LinkedList<TransitRouteStop>(); // first stop TransitRouteStop routeStop = this.tS.getFactory().createTransitRouteStop(startStop, startTime, startTime); stops.add(routeStop); // additional stops for (Link link : path.links) { startTime += link.getLength() / link.getFreespeed(); if (this.tS.getFacilities().get(link.getId()) == null) { continue; } routeStop = this.tS .getFactory() .createTransitRouteStop( this.tS.getFacilities().get(link.getId()), startTime, startTime); stops.add(routeStop); } // last stop startTime += this.net.getLinks().get(endStop.getLinkId()).getLength() / this.net.getLinks().get(endStop.getLinkId()).getFreespeed(); routeStop = this.tS.getFactory().createTransitRouteStop(endStop, startTime, startTime); stops.add(routeStop); // register departure TransitRoute transitRoute = this.tS.getFactory().createTransitRoute(routeID, route, stops, "pt"); return transitRoute; }
public String allStopsWithCorrectLink() { for (StopTime stopTime : trip.getStopTimes().values()) { Stop stop = stops.get(stopTime.getStopId()); Link link = network.getLinks().get(Id.create(stop.getLinkId(), Link.class)); Point2D fromPoint = new Point2D(link.getFromNode().getCoord().getX(), link.getFromNode().getCoord().getY()); Point2D toPoint = new Point2D(link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY()); Line2D linkLine = new Line2D(fromPoint, toPoint); Point2D point = new Point2D(stop.getPoint().getX(), stop.getPoint().getY()); if (!linkLine.isNearestInside(point)) { int pos = getLinkPosition(link.getId().toString()); if (pos == -1) return stopTime.getStopId(); if (pos == links.size() - 1 || pos == 0) return ""; Link link2 = links.get(pos + 1); fromPoint = new Point2D( link2.getFromNode().getCoord().getX(), link2.getFromNode().getCoord().getY()); toPoint = new Point2D(link2.getToNode().getCoord().getX(), link2.getToNode().getCoord().getY()); Line2D linkLine2 = new Line2D(fromPoint, toPoint); if (!(linkLine.getPointPosition(point).equals(Line2D.PointPosition.AFTER) && linkLine2.getPointPosition(point).equals(Line2D.PointPosition.BEFORE))) return stopTime.getStopId(); } } return ""; }
@Override public void setup() { // size(1800,1000); background(255); strokeWeight(16); textFont(createFont("Arial", 12)); textAlign(TOP, RIGHT); for (Node node : network.getNodes().values()) { if (minX > node.getCoord().getX()) minX = (float) node.getCoord().getX(); if (maxX < node.getCoord().getX()) maxX = (float) node.getCoord().getX(); if (minY > node.getCoord().getY()) minY = (float) node.getCoord().getY(); if (maxY < node.getCoord().getY()) maxY = (float) node.getCoord().getY(); } for (Link link : network.getLinks().values()) { if (link.getCapacity() < minCap) { minCap = (float) link.getCapacity(); } if (link.getCapacity() > maxCap) maxCap = (float) link.getCapacity(); } for (Link link : network.getLinks().values()) { strokeWeights.put(link.getId(), map((float) link.getCapacity(), minCap, maxCap, 10f, 160f)); } smooth(); // frameRate(3); // ArcBall arcball = new ArcBall(this); }
/** * @param internalizeEmissionOrCongestion emission congestion or both Total external costs * includes only emission and caused congestion costs. This is basically toll on each link */ public Map<Id<Link>, Double> getLinkToTotalExternalCost( final Scenario sc, final String internalizeEmissionOrCongestion) { if (noOfTimeBin != 1) throw new RuntimeException( "This method is not yet adapted to more than 1 time bin. Aborting ...."); double simEndTime = 30 * 2400; if (internalizeEmissionOrCongestion.equalsIgnoreCase("ei")) return getLink2EmissionToll(sc); else if (internalizeEmissionOrCongestion.equalsIgnoreCase("ci")) return getLink2CongestionToll(sc).get(simEndTime); else if (internalizeEmissionOrCongestion.equalsIgnoreCase("eci")) { Map<Id<Link>, Double> link2delaycost = getLink2CongestionToll(sc).get(simEndTime); Map<Id<Link>, Double> link2emissioncost = getLink2EmissionToll(sc); Map<Id<Link>, Double> totalCost = new HashMap<Id<Link>, Double>(); for (Link l : sc.getNetwork().getLinks().values()) { Id<Link> linkId = l.getId(); if (link2delaycost.containsKey(linkId) && link2emissioncost.containsKey(linkId)) { totalCost.put(linkId, link2delaycost.get(linkId) + link2emissioncost.get(linkId)); } else if (link2emissioncost.containsKey(linkId)) { totalCost.put(linkId, link2emissioncost.get(linkId)); } else totalCost.put(linkId, link2delaycost.get(linkId)); } return totalCost; } else throw new RuntimeException( "Do not recognize the external costs option. Available options are ei, ci or eci. Aborting ..."); }
@SuppressWarnings("static-method") private boolean checkNextLinkSemantics( Link currentLink, Id<Link> nextLinkId, QLinkInternalI nextQLink, QVehicle veh) { if (nextQLink == null) { // throw new IllegalStateException log.warn( "The link id " + nextLinkId + " is not available in the simulation network, but vehicle " + veh.getId() + " plans to travel on that link from link " + veh.getCurrentLink().getId()); return false; } if (currentLink.getToNode() != nextQLink.getLink().getFromNode()) { // throw new RuntimeException log.warn( "Cannot move vehicle " + veh.getId() + " from link " + currentLink.getId() + " to link " + nextQLink.getLink().getId()); return false; } return true; }
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; }
ArtificiallyConnectedStopFacility(TransitStopFacility facility) { myNode = networkFactory.createNode( Id.create(prefix + facility.getId(), Node.class), facility.getCoord()); myLink = getNewLink(myNode, myNode); facility.setLinkId(myLink.getId()); }
// added methods private void initializeFreeFloatingStartWalkLeg(Leg leg, double now) { this.state = MobsimAgent.State.LEG; Route route = leg.getRoute(); ParkingLinkInfo vehicleLocation = this.parkingModule.getNextFreeFloatingVehicle( this.scenario.getNetwork().getLinks().get(route.getStartLinkId()).getCoord(), this.person.getId(), now); if (vehicleLocation == null || vehicleLocation.getLinkId() == null) { log.warn( "Agent with id: " + this.getId().toString() + " was aborted because the freefloating vehicle was not avaialble or the vehicle id was not set up."); this.state = MobsimAgent.State.ABORT; return; } vehID = vehicleLocation.getVehicleId().toString(); startLink = this.scenario.getNetwork().getLinks().get(vehicleLocation.getLinkId()); LegImpl walkLeg = new LegImpl("walk_ff"); GenericRouteImpl walkRoute = new GenericRouteImpl(route.getStartLinkId(), startLink.getId()); final double dist = CoordUtils.calcEuclideanDistance( scenario.getNetwork().getLinks().get(route.getStartLinkId()).getCoord(), startLink.getCoord()); final double estimatedNetworkDistance = dist * this.beelineFactor; final int travTime = (int) (estimatedNetworkDistance / this.walkSpeed); walkRoute.setTravelTime(travTime); walkRoute.setDistance(estimatedNetworkDistance); walkLeg.setRoute(walkRoute); this.cachedDestinationLinkId = startLink.getId(); walkLeg.setDepartureTime(now); walkLeg.setTravelTime(travTime); walkLeg.setArrivalTime(now + travTime); // set the route according to the next leg this.currentLeg = walkLeg; this.cachedRouteLinkIds = null; this.currentLinkIdIndex = 0; this.cachedNextLinkId = null; return; }
public void createDilutedPlans( final Coord center, final double radius, final String fromFile, final String toFile) { final Map<Id<Link>, Link> areaOfInterest = new HashMap<>(); Network network = this.scenario.getNetwork(); log.info("extracting aoi:"); log.info(" center: " + center.getX() + " / " + center.getY()); log.info(" radius: " + radius); for (Link link : network.getLinks().values()) { final Node from = link.getFromNode(); final Node to = link.getToNode(); if ((CoordUtils.calcDistance(from.getCoord(), center) <= radius) || (CoordUtils.calcDistance(to.getCoord(), center) <= radius)) { System.out.println(" link " + link.getId().toString()); areaOfInterest.put(link.getId(), link); } } log.info(" # links in aoi: " + areaOfInterest.size()); log.info("creating diluted dpopulation:"); log.info(" input-file: " + fromFile); log.info(" output-file: " + toFile); PopulationImpl pop = (PopulationImpl) ((MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig())) .getPopulation(); pop.setIsStreaming(true); PopulationWriter writer = new PopulationWriter(pop, this.scenario.getNetwork()); writer.startStreaming(toFile); final PersonIntersectAreaFilter filter = new PersonIntersectAreaFilter(writer, areaOfInterest, network); filter.setAlternativeAOI(center, radius); pop.addAlgorithm(filter); new MatsimPopulationReader(new PseudoScenario(this.scenario, pop)).readFile(fromFile); writer.closeStreaming(); pop.printPlansCount(); log.info("persons in output: " + filter.getCount()); }
/** * Within search radius search for the closest link that has the current mode as allowed travel * mode and return this link. * * @param stopFacility Stop facility to search a link for. * @return Null if no such link could be found. */ private Id<Link> findClosestLink(TransitStopFacility stopFacility) { Link nearestLink = NetworkUtils.getNearestLink(this.network, stopFacility.getCoord()); if (NetworkUtils.getEuclidianDistance( stopFacility.getCoord(), nearestLink.getToNode().getCoord()) <= SEARCH_RADIUS) { // If nearest link is within search radius, return it. return nearestLink.getId(); } else { return null; } }
public static void main(String[] args) { String inputNetworkPath = "H:/data/experiments/ARTEMIS/zh/dumb charging/output/run2/output_network.xml.gz"; String outputFilePath = "H:/data/experiments/ARTEMIS/zh/dumb charging/output/run2/analysis/linksWithEnergyConsumpHigherThanThreshholdValue.kml"; LinkedList<Id<Link>> selectedLinks = new LinkedList<Id<Link>>(); selectedLinks.add(Id.create("17560000662724TF", Link.class)); selectedLinks.add(Id.create("17560002226916TF", Link.class)); selectedLinks.add(Id.create("17560000114875TF", Link.class)); selectedLinks.add(Id.create("17560000082333TF", Link.class)); selectedLinks.add(Id.create("17560002149918FT", Link.class)); selectedLinks.add(Id.create("17560000368213FT", Link.class)); selectedLinks.add(Id.create("17560002188272FT", Link.class)); selectedLinks.add(Id.create("17560001856956FT", Link.class)); selectedLinks.add(Id.create("17560001229496TF", Link.class)); selectedLinks.add(Id.create("17560001363425TF", Link.class)); selectedLinks.add(Id.create("17560001607380FT-1", Link.class)); selectedLinks.add(Id.create("17560000045386TF", Link.class)); selectedLinks.add(Id.create("17560000109095TF", Link.class)); selectedLinks.add(Id.create("17560001227588FT", Link.class)); selectedLinks.add(Id.create("17560000043382FT", Link.class)); selectedLinks.add(Id.create("17560000105015FT", Link.class)); selectedLinks.add(Id.create("17560000109323TF", Link.class)); selectedLinks.add(Id.create("17560001594646FT", Link.class)); selectedLinks.add(Id.create("17560001380278TF", Link.class)); BasicPointVisualizer basicPointVisualizer = new BasicPointVisualizer(); Network network = GeneralLib.readNetwork(inputNetworkPath); for (Link link : network.getLinks().values()) { if (selectedLinks.contains(link.getId())) { basicPointVisualizer.addPointCoordinate( link.getCoord(), link.getId().toString(), Color.GREEN); } } basicPointVisualizer.write(outputFilePath); }
public static final void moveFacility(ActivityFacilityImpl f, Link link) { double[] vector = new double[2]; vector[0] = (link.getToNode().getCoord().getY() - link.getFromNode().getCoord().getY()); vector[1] = (-(link.getToNode().getCoord().getX() - link.getFromNode().getCoord().getX())); Coord coord = new CoordImpl( link.getCoord().getX() + vector[0] * EPSILON, link.getCoord().getY() + vector[1] * 0.0001D); f.setCoord(coord); f.setLinkId(link.getId()); }
/** * @return <code>true</code> if the vehicle was successfully moved over the node, <code>false * </code> otherwise (e.g. in case where the next link is jammed) */ private boolean moveVehicleOverNode( final QVehicle veh, final QInternalI fromLaneBuffer, final double now) { Id<Link> nextLinkId = veh.getDriver().chooseNextLinkId(); Link currentLink = veh.getCurrentLink(); if ((!fromLaneBuffer.hasGreenForToLink(nextLinkId))) { // there is no longer a stuck check for red links. This means that // in case of an infinite red time the simulation will not stop automatically because // vehicles waiting in front of the red signal will never reach their destination. dg, mar'14 return false; } if (nextLinkId == null) { log.error( "Agent has no or wrong route! agentId=" + veh.getDriver().getId() + " currentLink=" + currentLink.getId().toString() + ". The agent is removed from the simulation."); moveVehicleFromInlinkToAbort(veh, fromLaneBuffer, now); return true; } QLinkInternalI nextQueueLink = network.getNetsimLinks().get(nextLinkId); if (!checkNextLinkSemantics(currentLink, nextLinkId, nextQueueLink, veh)) { moveVehicleFromInlinkToAbort(veh, fromLaneBuffer, now); return true; } if (nextQueueLink.isAcceptingFromUpstream()) { moveVehicleFromInlinkToOutlink(veh, fromLaneBuffer, nextQueueLink); return true; } if (vehicleIsStuck(fromLaneBuffer, now)) { /* We just push the vehicle further after stucktime is over, regardless * of if there is space on the next link or not.. optionally we let them * die here, we have a config setting for that! */ if (network.simEngine.getMobsim().getScenario().getConfig().qsim().isRemoveStuckVehicles()) { moveVehicleFromInlinkToAbort(veh, fromLaneBuffer, now); return false; } else { moveVehicleFromInlinkToOutlink(veh, fromLaneBuffer, nextQueueLink); return true; // (yyyy why is this returning `true'? Since this is a fix to avoid gridlock, this should // proceed in small steps. // kai, feb'12) } } return false; }
public void add() { List<Link> links = ((BusLaneAdderPanel) layersPanels.get(PanelIds.ONE)).getLinks(); Node prevNode = links.get(0).getFromNode(); for (Link link : links) if (!link.getAllowedModes().contains("bus")) { exitSave(); JOptionPane.showMessageDialog(this, "Wrong path, network saved"); } for (int i = 0; i < links.size(); i++) { Link link = links.get(i); Node node = null; if (link.getNumberOfLanes() == 1) { Set<String> modes = new HashSet<String>(); modes.add("bus"); link.setAllowedModes(modes); node = link.getToNode(); } else { Node oldNode = link.getToNode(); if (i == links.size() - 1 || oldNode.getInLinks().size() + oldNode.getOutLinks().size() > 2) node = oldNode; else { node = network .getFactory() .createNode( Id.createNodeId("fl" + oldNode.getId().toString()), oldNode.getCoord()); network.addNode(node); } LinkImpl newLink = (LinkImpl) network .getFactory() .createLink(Id.createLinkId("fl" + link.getId().toString()), prevNode, node); Set<String> modes = new HashSet<String>(); modes.add("car"); newLink.setAllowedModes(modes); newLink.setCapacity(link.getCapacity()); newLink.setFreespeed(link.getFreespeed()); newLink.setLength(link.getLength()); newLink.setNumberOfLanes(link.getNumberOfLanes() - 1); newLink.setOrigId(((LinkImpl) link).getOrigId()); newLink.setType(((LinkImpl) link).getType()); network.addLink(newLink); Set<String> modes2 = new HashSet<String>(); modes2.add("bus"); link.setAllowedModes(modes2); link.setCapacity(900); link.setNumberOfLanes(1); } prevNode = node; } ((BusLaneAdderPanel) layersPanels.get(PanelIds.ONE)).clearSelection(); }
NodeClusteringAlgorithm(String algorithmName, Network network) { this.flowValues = new ArrayList<>(); this.network = network; links = new LinkedHashMap<>(network.getLinks().size()); for (Link l : network.getLinks().values()) { links.put(l.getId(), new ClusterLink((Link) l)); } this.setNodes(new LinkedHashMap<Id, ClusterNode>(network.getNodes().size())); leafNodeClusters = new TreeMap<>(); this.setAlgorithmName(algorithmName); rootClusters = null; logger = Logger.getLogger("NodeClusterer"); }
public void writeShape( String outfile, Map<Id, List<CountSimComparison>> countSimLinkLeaveCompMap, Map<Id, Double> delayPerLink1, Map<Id, Double> delayPerLink2, String runId, String runId2) { PolygonFeatureFactory factory = createFeatureType(this.crs, runId, runId2); GeometryFactory geofac = new GeometryFactory(); Collection<SimpleFeature> features = new ArrayList<SimpleFeature>(); for (Link link : this.network.getLinks().values()) { features.add( this.createFeature( link, geofac, factory, countSimLinkLeaveCompMap.get(link.getId()), delayPerLink1.get(link.getId()), delayPerLink2.get(link.getId()))); } ShapeFileWriter.writeGeometries(features, outfile); }
private void createFreeLinks() { double referenceDensity = 120.0D; String freeLinksParameterString = "0.5"; Double freeLinksParameterInt = Double.valueOf(Double.parseDouble(freeLinksParameterString)); Integer newLinksMax = Integer.valueOf( (int) Math.round(this.currentLinks.size() * freeLinksParameterInt.doubleValue())); int numberLinks = this.scenario.getNetwork().getLinks().values().size(); log.info("number links = " + numberLinks); log.info("free links size will be = " + newLinksMax); int size = this.scenario.getNetwork().getLinks().values().toArray().length; Object[] arr = this.scenario.getNetwork().getLinks().values().toArray(); List<Object> list = Arrays.asList(arr); Collections.shuffle(list); int rd = -1; while (this.freeLinks.size() < newLinksMax.intValue() && rd < size - 1) { rd++; Link link = (Link) list.get(rd); if (this.currentLinks.contains((link))) { log.info("On the link " + link.getId() + " there is already a Station"); } else if (this.freeLinks.contains(link)) { log.info("The link " + link.getId() + " is already in the list"); } else { double density = this.personQuadTree .getDisk(link.getCoord().getX(), link.getCoord().getY(), 100.0D) .size(); if ((this.freeLinks.size() < newLinksMax.intValue()) && (density > referenceDensity)) { this.freeLinks.add(link); log.info("the link " + link.getId() + " has been added to the free links"); log.info("free links are" + this.freeLinks); this.allLinks.put(link.getId(), link); } } } }
private static Network filterNetwork(Network network) { CoordinateTransformation transform = TransformationFactory.getCoordinateTransformation( TransformationFactory.CH1903_LV03_GT, TransformationFactory.DHDN_GK4); // CoordinateTransformation transform = // TransformationFactory.getCoordinateTransformation(TransformationFactory.CH1903_LV03_GT, // "WGS84_UTM32T"); Network net = NetworkUtils.createNetwork(); RoadPricingSchemeImpl rps = new RoadPricingSchemeImpl(); RoadPricingReaderXMLv1 rpr = new RoadPricingReaderXMLv1(rps); rpr.parse(linksToFilter); Set<Id<Link>> linkList = rps.getTolledLinkIds(); for (Link link : network.getLinks().values()) { Id linkId = link.getId(); if (linkList.contains(linkId)) { Id fromId = link.getFromNode().getId(); Id toId = link.getToNode().getId(); Coord fromNodeCoord = link.getFromNode().getCoord(); Coord toNodeCoord = link.getToNode().getCoord(); Coord fromNodeTransformed = transform.transform(fromNodeCoord); Coord toNodeTransformed = transform.transform(toNodeCoord); // Node newFromNode = net.getFactory().createNode(fromId, fromNodeCoord); // Node newToNode = net.getFactory().createNode(toId, toNodeCoord); Node newFromNode = net.getFactory().createNode(fromId, fromNodeTransformed); Node newToNode = net.getFactory().createNode(toId, toNodeTransformed); if (!net.getNodes().containsKey(fromId)) { net.addNode(newFromNode); } if (!net.getNodes().containsKey(toId)) { net.addNode(newToNode); } Link ll = net.getFactory().createLink(link.getId(), newFromNode, newToNode); net.addLink(ll); } } return net; }
private void initializeCSWalkLeg(String mode, double now, Link startLink, Link destinationLink) { LegImpl walkLeg = new LegImpl(mode); GenericRouteImpl walkRoute = new GenericRouteImpl(startLink.getId(), destinationLink.getId()); final double dist = CoordUtils.calcEuclideanDistance(startLink.getCoord(), destinationLink.getCoord()); final double estimatedNetworkDistance = dist * beelineFactor; final int travTime = (int) (estimatedNetworkDistance / walkSpeed); walkRoute.setTravelTime(travTime); walkRoute.setDistance(estimatedNetworkDistance); walkLeg.setRoute(walkRoute); this.cachedDestinationLinkId = destinationLink.getId(); walkLeg.setDepartureTime(now); walkLeg.setTravelTime(travTime); walkLeg.setArrivalTime(now + travTime); // set the route according to the next leg this.currentLeg = walkLeg; this.cachedRouteLinkIds = null; this.currentLinkIdIndex = 0; this.cachedNextLinkId = null; }