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 protected void initFlow(HierarchicalConfiguration flowCfg) { // int node = flowCfg.getInt("[@node]"); int inLink = flowCfg.getInt("[@inLink]", -1); int outLink = flowCfg.getInt("[@outLink]", -1); // int next = flowCfg.getInt("[@next]"); int no = flowCfg.getInt("[@no]", 0); Node node; Node next; if (inLink != -1) { Link link = idToLinkMap.get(Id.create(inLink, Link.class)); node = link.getFromNode(); next = link.getToNode(); } else { Link link = idToLinkMap.get(Id.create(outLink, Link.class)); node = link.getToNode(); next = link.getFromNode(); } int nodeId = Integer.parseInt(node.getId().toString()); int nextId = Integer.parseInt(next.getId().toString()); flows[nodeId] = new MATSimFlow(nodeId, inLink, outLink, nextId, no); }
public double getAngle(Link link) { Point2D fromPoint = new Point2D(link.getFromNode().getCoord().getX(), link.getFromNode().getCoord().getY()); Point2D toPoint = new Point2D(link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY()); Vector2D linkVector = new Vector2D(fromPoint, toPoint); Vector2D shapeVector = getVector(link.getCoord()); return linkVector.getAngleTo(shapeVector); }
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()); }
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()); }
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"); }
private void expandLandmarkTo() { LandmarksToTravelTimeComparator comparator = new LandmarksToTravelTimeComparator(this.nodeData, this.landmarkIdx); PriorityQueue<Node> pendingNodes = new PriorityQueue<>(100, comparator); LandmarksData role = (LandmarksData) this.nodeData.get(this.landmark); role.setToLandmarkTravelTime(this.landmarkIdx, 0.0); role.setFromLandmarkTravelTime(this.landmarkIdx, 0.0); pendingNodes.add(this.landmark); while (!pendingNodes.isEmpty()) { Node node = pendingNodes.poll(); double toTravTime = ((LandmarksData) this.nodeData.get(node)).getToLandmarkTravelTime(this.landmarkIdx); LandmarksData role2; for (Link l : node.getInLinks().values()) { Node n = l.getFromNode(); double linkTravTime = this.costFunction.getLinkMinimumTravelDisutility(l); role2 = (LandmarksData) this.nodeData.get(n); double totalTravelTime = toTravTime + linkTravTime; if (role2.getToLandmarkTravelTime(this.landmarkIdx) > totalTravelTime) { role2.setToLandmarkTravelTime(this.landmarkIdx, totalTravelTime); pendingNodes.add(n); } } } }
public static void main(String[] args) { MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario.getNetwork()); networkReader.readFile(args[0]); int numberOfLinks = 0; double length = 0.0; double length1 = 0.0; double length2 = 0.0; double length3 = 0.0; Node previousNode1 = null; Node previousNode2 = null; for (Link l : scenario.getNetwork().getLinks().values()) { if (previousNode1 != null) { if (l.getFromNode().getId() != previousNode2.getId() && l.getToNode().getId() != previousNode1.getId()) { numberOfLinks++; length += l.getLength(); if (l.getFreespeed() > 24.99) { length1 += l.getLength(); } else if (l.getFreespeed() < 13.88) { length3 += l.getLength(); } else length2 += l.getLength(); } } else { numberOfLinks++; length += l.getLength(); if (l.getFreespeed() > 24.99) { length1 += l.getLength(); } else if (l.getFreespeed() < 13.88) { length3 += l.getLength(); } else length2 += l.getLength(); } previousNode1 = l.getFromNode(); previousNode2 = l.getToNode(); } System.out.println(numberOfLinks); System.out.println(length / 1000); System.out.println(length1 / 1000); System.out.println(length2 / 1000); System.out.println(length3 / 1000); }
// 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); } } }
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); }
private void initializeRoads() { Network network = optimContext.network; Map<Id<Link>, ? extends Link> linknetwork = network.getLinks(); for (Id<Link> id : linknetwork.keySet()) { Link curr = linknetwork.get(id); Node from = curr.getFromNode(); Node to = curr.getToNode(); roads.put(new Pair(from, to), curr); } }
public double getDistance(Link link) { double nearestDistance = Double.POSITIVE_INFINITY; for (Coord coord : points.values()) { final Coord coord1 = coord; Link r = ((Link) link); double distance = CoordUtils.distancePointLinesegment( r.getFromNode().getCoord(), r.getToNode().getCoord(), coord1); if (distance < nearestDistance) nearestDistance = distance; } return nearestDistance; }
/** * Looks in the network if the link has an opposite direction link and if so returns it. * * @param linkId of the link for which opposite direction links are searched. * @return List with the found links (resp. their Ids)... */ private List<Id<Link>> getOppositeDirection(Id<Link> linkId) { if (linkId == null) { return null; } List<Id<Link>> oppositeDirectionLinks = new ArrayList<>(); // If we find one with "opposite" direction, we return only this. Link lowerLink = this.network.getLinks().get(Id.createLinkId(Integer.parseInt(linkId.toString()) - 1)); Link link = this.network.getLinks().get(linkId); Link upperLink = this.network.getLinks().get(Id.createLinkId(Integer.parseInt(linkId.toString()) + 1)); if (lowerLink != null && lowerLink.getFromNode().getId().toString().equals(link.getToNode().getId().toString()) && lowerLink.getToNode().getId().toString().equals(link.getFromNode().getId().toString())) { oppositeDirectionLinks.add(lowerLink.getId()); } if (oppositeDirectionLinks.isEmpty() && upperLink != null && upperLink.getFromNode().getId().toString().equals(link.getToNode().getId().toString()) && upperLink.getToNode().getId().toString().equals(link.getFromNode().getId().toString())) { oppositeDirectionLinks.add(upperLink.getId()); } if (CONNECTION_TO_ALL_LINKS_WITHIN_SEARCH_AREA) { Set<Link> linksWithinRadius = getLinksWithinSearchRadius(link.getCoord()); if (linksWithinRadius != null) { for (Link presentLink : linksWithinRadius) { if (!presentLink.getId().toString().equals(link.getId().toString()) && oppositeDirectionLinks.contains(presentLink.getId())) { oppositeDirectionLinks.add(presentLink.getId()); } } } } return oppositeDirectionLinks; }
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 List<Link> getBestLinksMode(Network network, Coord coord, Shape shape) { List<Double> nearestDistances = new ArrayList<Double>(); List<Link> nearestLinks = new ArrayList<Link>(); for (double minDistance = this.minDistance; nearestLinks.size() < numCandidates; minDistance += MIN_DISTANCE_DELTA) for (Link link : network.getLinks().values()) if (link.getAllowedModes().contains(mode)) { Point2D fromPoint = new Point2D( link.getFromNode().getCoord().getX(), link.getFromNode().getCoord().getY()); Point2D toPoint = new Point2D(link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY()); Vector2D linkVector = new Vector2D(fromPoint, toPoint); Line2D linkSegment = new Line2D(fromPoint, toPoint); if (!withInsideStops || linkSegment.isNearestInside(new Point2D(coord.getX(), coord.getY()))) if (!withAngleShape || shape == null || linkVector.getAngleTo(shape.getVector(coord)) < Math.PI / 16) { double distance = ((LinkImpl) link).calcDistance(coord); if (distance < minDistance) { int i = 0; for (; i < nearestDistances.size() && distance < nearestDistances.get(i); i++) ; if (i > 0 || nearestLinks.size() < numCandidates) { nearestDistances.add(i, distance); nearestLinks.add(i, link); if (nearestLinks.size() > numCandidates) { nearestDistances.remove(0); nearestLinks.remove(0); } } } } } return nearestLinks; }
private void assignProps(Collection<Link> links, Link link) { double capacity = 0; double freespeed = 0; double lanes = 0; for (Link origLink : links) { capacity += origLink.getCapacity(); freespeed = Math.max(freespeed, origLink.getFreespeed()); lanes += origLink.getNumberOfLanes(); } link.setCapacity(capacity); link.setFreespeed(freespeed); link.setNumberOfLanes(lanes); link.setLength( NetworkUtils.getEuclideanDistance( link.getFromNode().getCoord(), link.getToNode().getCoord())); }
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()); }
private LeastCostPathCalculator.Path getShortestPath(Node startNode, TransitRouteStop toStop) { LeastCostPathCalculator.Path shortestPath = null; for (Id<TransitStopFacility> toStopFacilityId : linkedStopFacilitiesTree.get(toStop.getStopFacility().getId())) { TransitStopFacility facility = this.schedule.getFacilities().get(toStopFacilityId); Id<Link> linkId = facility.getLinkId(); Link link = this.network.getLinks().get(linkId); Node endNode = link.getFromNode(); LeastCostPathCalculator.Path tempShortestPath = this.router.calcLeastCostPath(startNode, endNode, "", ""); if (tempShortestPath != null && (shortestPath == null || (tempShortestPath.travelCost < shortestPath.travelCost))) { shortestPath = tempShortestPath; toStop.setStopFacility(this.schedule.getFacilities().get(toStopFacilityId)); } } return shortestPath; }
public void addLinkNext(int index, Coord second) { Link link = links.get(index); if (index == links.size() - 1 || !link.getToNode().equals(links.get(index + 1).getFromNode())) { Point2D toPoint = new Point2D(link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY()); Point2D secondPoint = new Point2D(second.getX(), second.getY()); Vector2D dirSegment = new Vector2D(toPoint, secondPoint); Link bestLink = null; double smallestAngle = Double.POSITIVE_INFINITY; for (Link linkN : network.getLinks().values()) if (link.getToNode().equals(linkN.getFromNode())) { Point2D toPoint2 = new Point2D(linkN.getToNode().getCoord().getX(), linkN.getToNode().getCoord().getY()); Vector2D linkNSegment = new Vector2D(toPoint, toPoint2); double angle = dirSegment.getAngleTo(linkNSegment); if (angle < smallestAngle) { smallestAngle = angle; bestLink = linkN; } } links.add(index + 1, bestLink); } }
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 double calculateAngleImmissionCorrection(Coord receiverPointCoord, Link link) { double angle = 0; double pointCoordX = receiverPointCoord.getX(); double pointCoordY = receiverPointCoord.getY(); double fromCoordX = link.getFromNode().getCoord().getX(); double fromCoordY = link.getFromNode().getCoord().getY(); double toCoordX = link.getToNode().getCoord().getX(); double toCoordY = link.getToNode().getCoord().getY(); if (pointCoordX == fromCoordX && pointCoordY == fromCoordY) { // receiver point is situated on the link (fromNode) // assume a maximum angle immission correction for this case angle = 0; } else if (pointCoordX == toCoordX && pointCoordY == toCoordY) { // receiver point is situated on the link (toNode) // assume a zero angle immission correction for this case angle = 180; } else { // all other cases double sc = (fromCoordX - pointCoordX) * (toCoordX - pointCoordX) + (fromCoordY - pointCoordY) * (toCoordY - pointCoordY); double cosAngle = sc / (Math.sqrt( Math.pow(fromCoordX - pointCoordX, 2) + Math.pow(fromCoordY - pointCoordY, 2)) * Math.sqrt( Math.pow(toCoordX - pointCoordX, 2) + Math.pow(toCoordY - pointCoordY, 2))); angle = Math.toDegrees(Math.acos(cosAngle)); if (sc > 0) { // spitzer winkel if (angle > 90) { angle = 180 - angle; } } else if (sc < 0) { // stumpfer winkel if (angle < 90) { angle = 180 - angle; } } else { angle = 0.; } } // since zero is not defined if (angle == 0.) { // zero degrees is not defined angle = 0.0000000001; } // System.out.println(receiverPointCoord + " // " + link.getId() + "(" + // link.getFromNode().getCoord() + "-->" + link.getToNode().getCoord() + " // " + angle); double immissionCorrection = NoiseEquations.calculateAngleCorrection(angle); return immissionCorrection; }
public void calculatePath() { links.clear(); Iterator<StopTime> prev = trip.getStopTimes().values().iterator(), next = trip.getStopTimes().values().iterator(); List<Link> prevLL, nextLL; Link prevL = null, nextL = null; next.next(); Stop prevStop = null, nextStop = null; if (next.hasNext()) { Path bestPath = null; prevStop = stops.get(prev.next().getStopId()); nextStop = stops.get(next.next().getStopId()); if (prevStop.getLinkId() != null) { prevLL = new ArrayList<Link>(); prevLL.add(network.getLinks().get(Id.create(prevStop.getLinkId(), Link.class))); } else prevLL = getBestLinksMode(network, prevStop.getPoint(), trip.getShape()); if (nextStop.getLinkId() != null) { nextLL = new ArrayList<Link>(); nextLL.add(network.getLinks().get(Id.create(nextStop.getLinkId(), Link.class))); } else nextLL = getBestLinksMode(network, nextStop.getPoint(), trip.getShape()); List<Tuple<Path, Link[]>> paths = new ArrayList<Tuple<Path, Link[]>>(); for (int i = 0; i < prevLL.size(); i++) for (int j = 0; j < nextLL.size(); j++) { prevL = prevLL.get(i); nextL = nextLL.get(j); Path path; if (prevL == nextL) path = new Path(new ArrayList<Node>(), new ArrayList<Link>(), 0.0, 0.0); else { path = leastCostPathCalculator.calcLeastCostPath( prevL.getToNode(), nextL.getFromNode(), 0, null, null); if (path == null) path = new Path(new ArrayList<Node>(), new ArrayList<Link>(), 0.0, 0.0); path.links.add(0, prevL); } path.links.add(nextL); paths.add(new Tuple<Path, Link[]>(path, new Link[] {prevL, nextLL.get(j)})); } double shortestDistance = Double.POSITIVE_INFINITY; for (Tuple<Path, Link[]> tuple : paths) { if (tuple.getFirst().links.size() > 0) { double distance = calculateDistance(tuple.getFirst(), prevStop.getPoint(), nextStop.getPoint()); if (bestPath == null || distance <= shortestDistance) { shortestDistance = distance; bestPath = tuple.getFirst(); prevStop.setLinkId(tuple.getSecond()[0].getId().toString()); nextStop.setLinkId(tuple.getSecond()[1].getId().toString()); } } } prevL = bestPath.links.get(bestPath.links.size() - 1); links.addAll(bestPath.links); prevStop = nextStop; } for (; next.hasNext(); ) { Path bestPath = null; nextStop = stops.get(next.next().getStopId()); if (nextStop.getLinkId() != null) { nextL = network.getLinks().get(Id.create(nextStop.getLinkId(), Link.class)); if (prevL.equals(nextL)) bestPath = new Path(new ArrayList<Node>(), new ArrayList<Link>(), 0.0, 0.0); else { bestPath = leastCostPathCalculator.calcLeastCostPath( prevL.getToNode(), nextL.getFromNode(), 0, null, null); if (bestPath == null) bestPath = new Path(new ArrayList<Node>(), new ArrayList<Link>(), 0.0, 0.0); else bestPath.links.add(0, prevL); } bestPath.links.add(nextL); } else { nextLL = getBestLinksMode(network, nextStop.getPoint(), trip.getShape()); List<Tuple<Path, Link>> paths = new ArrayList<Tuple<Path, Link>>(); for (int i = 0; i < nextLL.size(); i++) { nextL = nextLL.get(i); Path path; if (prevL.equals(nextL)) path = new Path(new ArrayList<Node>(), new ArrayList<Link>(), 0.0, 0.0); else { path = leastCostPathCalculator.calcLeastCostPath( prevL.getToNode(), nextL.getFromNode(), 0, null, null); if (path == null) path = new Path(new ArrayList<Node>(), new ArrayList<Link>(), 0.0, 0.0); else path.links.add(0, prevL); } path.links.add(nextL); paths.add(new Tuple<Path, Link>(path, nextL)); } double shortestDistance = Double.POSITIVE_INFINITY; for (Tuple<Path, Link> tuple : paths) { double distance = calculateDistance(tuple.getFirst(), prevStop.getPoint(), nextStop.getPoint()); if (bestPath == null || distance <= shortestDistance) { shortestDistance = distance; bestPath = tuple.getFirst(); nextStop.setLinkId(tuple.getSecond().getId().toString()); } } } prevL = bestPath.links.get(bestPath.links.size() - 1); bestPath.links.remove(0); links.addAll(bestPath.links); prevStop = nextStop; } }
public static void write( Network network, LinkOccupancyCalculator linkVols, double factor, String file) { Map<Link, Double> volumes = new HashMap<>(network.getLinks().size()); Map<Link, Double> loads = new HashMap<>(network.getLinks().size()); double maxVolume = 0; double minVolume = Double.MAX_VALUE; for (Link link : network.getLinks().values()) { String linkId = link.getId().toString(); if (!(linkId.startsWith(ODCalibrator.VIRTUAL_ID_PREFIX) || linkId.contains(".l"))) { double vol = linkVols.getOccupancy(link.getId()) * factor; double load = vol / (link.getCapacity() * 24); volumes.put(link, vol); loads.put(link, load); maxVolume = Math.max(maxVolume, vol); minVolume = Math.min(minVolume, vol); } } MathTransform transform = null; try { transform = CRS.findMathTransform(CRSUtils.getCRS(31467), CRSUtils.getCRS(4326)); } catch (FactoryException e) { e.printStackTrace(); } GeoJSONWriter jsonWriter = new GeoJSONWriter(); List<Feature> features = new ArrayList<>(network.getLinks().size()); for (Link link : volumes.keySet()) { double coord1[] = new double[] {link.getFromNode().getCoord().getX(), link.getFromNode().getCoord().getY()}; double coord2[] = new double[] {link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY()}; try { transform.transform(coord1, 0, coord1, 0, 1); transform.transform(coord2, 0, coord2, 0, 1); } catch (TransformException e) { e.printStackTrace(); } double coords[][] = new double[2][2]; coords[0][0] = coord1[0]; coords[0][1] = coord1[1]; coords[1][0] = coord2[0]; coords[1][1] = coord2[1]; LineString lineString = new LineString(coords); Map<String, Object> properties = new HashMap<>(); double volume = volumes.get(link); double load = loads.get(link); properties.put("volume", volume); properties.put("load", load); properties.put("capacity", link.getCapacity()); double width = (volume - minVolume) / (maxVolume - minVolume); properties.put("width", width); Color color = ColorUtils.getRedGreenColor(load); properties.put("color", "#" + String.format("%06x", color.getRGB() & 0x00FFFFFF)); Feature feature = new Feature(lineString, properties); features.add(feature); } try { FeatureCollection fCollection = jsonWriter.write(features); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(fCollection.toString()); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
/* (non-Javadoc) * @see org.matsim.core.api.internal.NetworkRunnable#run(org.matsim.api.core.v01.network.Network) */ @Override public void run(Network network) { Queue<Node> pendingNodes = new LinkedList<Node>(network.getNodes().values()); double[] env = NetworkUtils.getBoundingBox(pendingNodes); QuadTree<Node> quadTree = new QuadTree<Node>(env[0], env[1], env[2], env[3]); for (Node node : pendingNodes) { quadTree.put(node.getCoord().getX(), node.getCoord().getY(), node); } long linkIdCounter = 100000000000L; while (!pendingNodes.isEmpty()) { Node node = pendingNodes.poll(); double radius = 30; double minx = node.getCoord().getX() - radius; double miny = node.getCoord().getY() - radius; double maxx = node.getCoord().getX() + radius; double maxy = node.getCoord().getY() + radius; Set<Node> intersectionNodes = new HashSet<Node>(20); quadTree.getRectangle(minx, miny, maxx, maxy, intersectionNodes); if (intersectionNodes.size() > 1) { Set<Node> sourceNodes = new HashSet<Node>(); Map<Node, Set<Link>> inLinks = new HashMap<Node, Set<Link>>(); Set<Node> targetNodes = new HashSet<Node>(); Map<Node, Set<Link>> outLinks = new HashMap<Node, Set<Link>>(); for (Node intersectionNode : intersectionNodes) { for (Link link : intersectionNode.getInLinks().values()) { Node fromNode = link.getFromNode(); double x = fromNode.getCoord().getX(); double y = fromNode.getCoord().getY(); if (!(x > minx && y > miny && x < maxx && y < maxy)) { sourceNodes.add(fromNode); Set<Link> links = inLinks.get(fromNode); if (links == null) { links = new HashSet<Link>(); inLinks.put(fromNode, links); } links.add(link); } } for (Link link : intersectionNode.getOutLinks().values()) { Node toNode = link.getToNode(); double x = toNode.getCoord().getX(); double y = toNode.getCoord().getY(); if (!(x > minx && y > miny && x < maxx && y < maxy)) { targetNodes.add(toNode); Set<Link> links = outLinks.get(toNode); if (links == null) { links = new HashSet<Link>(); outLinks.put(toNode, links); } links.add(link); } } } for (Node intersectionNode : intersectionNodes) { network.removeNode(intersectionNode.getId()); quadTree.remove( intersectionNode.getCoord().getX(), intersectionNode.getCoord().getY(), intersectionNode); pendingNodes.remove(intersectionNode); } NetworkFactory factory = network.getFactory(); Node centerNode = factory.createNode(node.getId(), centerOfMass(intersectionNodes)); network.addNode(centerNode); quadTree.put(centerNode.getCoord().getX(), centerNode.getCoord().getY(), centerNode); for (Node source : sourceNodes) { Link newLink = factory.createLink(Id.create(linkIdCounter++, Link.class), source, centerNode); network.addLink(newLink); Set<Link> origLinks = inLinks.get(source); assignProps(origLinks, newLink); } for (Node target : targetNodes) { Link newLink = factory.createLink(Id.create(linkIdCounter++, Link.class), centerNode, target); network.addLink(newLink); Set<Link> origLinks = outLinks.get(target); assignProps(origLinks, newLink); } } } }
/** * Returns the next link the vehicle will drive along. * * @return The next link the vehicle will drive on, or null if an error has happened. */ @Override public Id<Link> chooseNextLinkId() { // Please, let's try, amidst all checking and caching, to have this method return the same thing // if it is called several times in a row. Otherwise, you get Heisenbugs. // I just fixed a situation where this method would give a warning about a bad route and return // null // the first time it is called, and happily return a link id when called the second time. // michaz 2013-08 if (this.cachedNextLinkId != null) { return this.cachedNextLinkId; } if (this.cachedRouteLinkIds == null) { if (this.currentLeg.getRoute() instanceof NetworkRoute) { this.cachedRouteLinkIds = ((NetworkRoute) this.currentLeg.getRoute()).getLinkIds(); } else { // (seems that this can happen if an agent is a DriverAgent, but wants to start a pt leg. // A situation where Marcel's ``wrapping approach'' may have an advantage. On the other // hand, // DriverAgent should be a NetworkAgent, i.e. including pedestrians, and then this function // should always be answerable. kai, nov'11) return null; } } if (this.currentLinkIdIndex >= this.cachedRouteLinkIds.size()) { // we have no more information for the route, so the next link should be the destination link Link currentLink = this.simulation.getScenario().getNetwork().getLinks().get(this.currentLinkId); Link destinationLink = this.simulation.getScenario().getNetwork().getLinks().get(this.cachedDestinationLinkId); if (currentLink == destinationLink && this.currentLinkIdIndex > this.cachedRouteLinkIds.size()) { // this can happen if the last link in a route is a loop link. Don't ask, it can happen in // special transit simulation cases... mrieser/jan2014 return null; } if (currentLink.getToNode().equals(destinationLink.getFromNode())) { this.cachedNextLinkId = destinationLink.getId(); return this.cachedNextLinkId; } if (!(this.currentLinkId.equals(this.cachedDestinationLinkId))) { // there must be something wrong. Maybe the route is too short, or something else, we don't // know... log.error( "The vehicle with driver " + this.getPerson().getId() + ", currently on link " + this.currentLinkId.toString() + ", is at the end of its route, but has not yet reached its destination link " + this.cachedDestinationLinkId.toString()); // yyyyyy personally, I would throw some kind of abort event here. kai, aug'10 } return null; // vehicle is at the end of its route } Id<Link> nextLinkId = this.cachedRouteLinkIds.get(this.currentLinkIdIndex); Link currentLink = this.simulation.getScenario().getNetwork().getLinks().get(this.currentLinkId); Link nextLink = this.simulation.getScenario().getNetwork().getLinks().get(nextLinkId); if (currentLink.getToNode().equals(nextLink.getFromNode())) { this.cachedNextLinkId = nextLinkId; // save time in later calls, if link is congested return this.cachedNextLinkId; } log.warn( this + " [no link to next routenode found: routeindex= " + this.currentLinkIdIndex + " ]"); // yyyyyy personally, I would throw some kind of abort event here. kai, aug'10 return null; }
private static boolean isLinkAffected(Link link) { return CoordUtils.calcEuclideanDistance(link.getFromNode().getCoord(), center) <= radius || CoordUtils.calcEuclideanDistance(link.getToNode().getCoord(), center) <= radius || CoordUtils.calcEuclideanDistance(link.getCoord(), center) <= radius; }
public QSimDensityDrawer(Scenario sc) { for (Link l : sc.getNetwork().getLinks().values()) { if (l.getId().toString().contains("jps") || l.getId().toString().contains("el") || l.getAllowedModes().contains("walk2d") || l.getCapacity() >= 100000 || l.getFreespeed() > 100 || l.getId().toString().contains("el")) { continue; } float width = (float) (l.getCapacity() / sc.getNetwork().getCapacityPeriod() / 1.3); boolean isCar = false; if (l.getFreespeed() > 1.35) { width = (float) (l.getNumberOfLanes() * 3.5); isCar = true; } else { width = (float) (width); } double dx = l.getToNode().getCoord().getX() - l.getFromNode().getCoord().getX(); double dy = l.getToNode().getCoord().getY() - l.getFromNode().getCoord().getY(); double length = Math.sqrt(dx * dx + dy * dy); dx /= length; dy /= length; LinkInfo info = new LinkInfo(); info.id = l.getId(); info.cap = (l.getLength() / ((NetworkImpl) sc.getNetwork()).getEffectiveCellSize()) * l.getNumberOfLanes(); double x0 = l.getFromNode().getCoord().getX(); double y0 = l.getFromNode().getCoord().getY(); double x1 = l.getToNode().getCoord().getX(); double y1 = l.getToNode().getCoord().getY(); x0 += dy * width / 2; x1 += dy * width / 2; y0 -= dx * width / 2; y1 -= dx * width / 2; info.width = width; info.x0 = x0; info.x1 = x1; info.y0 = y0; info.y1 = y1; double tan = dx / dy; double atan = Math.atan(tan); if (atan > 0) { atan -= Math.PI / 2; } else { atan += Math.PI / 2; } double offsetX = dy * .075; double offsetY = -dx * .075; if (dx > 0) { offsetX *= -1; offsetY *= -1; } info.tx = (x0 + x1) / 2 + offsetX; info.ty = (y0 + y1) / 2 + offsetY; info.text = "0"; info.atan = atan; info.isCar = isCar; if (isCar) { info.cap = l.getLength() / 7.5 * l.getNumberOfLanes(); } this.links.add(info); this.map.put(l.getId(), info); } }
public void updateRoadClosure() { String shapeID; int secondaryLayerID = this.controller.getVisualizer().getSecondaryShapeRenderLayer().getId(); if ((this.currentLinkId1 != null)) { if (this.cbLink1.isSelected()) { if (this.roadClosures.get(this.currentLinkId1) == null) { Link link = this.controller.getScenario().getNetwork().getLinks().get(currentLinkId1); Point2D c0 = this.controller.coordToPoint(link.getFromNode().getCoord()); Point2D c1 = this.controller.coordToPoint(link.getToNode().getCoord()); LineShape shape = ShapeFactory.getRoadClosureShape(secondaryLayerID, currentLinkId1.toString(), c0, c1); this.controller.addShape(shape); this.controller .getVisualizer() .getSecondaryShapeRenderLayer() .updatePixelCoordinates(shape); } this.roadClosures.put( this.currentLinkId1, this.blockFieldLink1hh.getText() + ":" + this.blockFieldLink1mm.getText()); } else { shapeID = Constants.ID_ROADCLOSURE_PREFIX + currentLinkId1.toString(); if (this.roadClosures.get(this.currentLinkId1) != null) { this.controller.removeShape(shapeID); } this.roadClosures.remove(this.currentLinkId1); } } if ((this.currentLinkId2 != null)) { if (this.cbLink2.isSelected()) { if (this.roadClosures.get(this.currentLinkId2) == null) { Link link = this.controller.getScenario().getNetwork().getLinks().get(currentLinkId2); Point2D c0 = this.controller.coordToPoint(link.getFromNode().getCoord()); Point2D c1 = this.controller.coordToPoint(link.getToNode().getCoord()); LineShape shape = ShapeFactory.getRoadClosureShape(secondaryLayerID, currentLinkId2.toString(), c1, c0); this.controller.addShape(shape); this.controller .getVisualizer() .getSecondaryShapeRenderLayer() .updatePixelCoordinates(shape); } this.roadClosures.put( this.currentLinkId2, this.blockFieldLink2hh.getText() + ":" + this.blockFieldLink2mm.getText()); } else { shapeID = Constants.ID_ROADCLOSURE_PREFIX + currentLinkId2.toString(); if (this.roadClosures.get(this.currentLinkId2) != null) { this.controller.removeShape(shapeID); } this.roadClosures.remove(this.currentLinkId2); } } this.controller.paintLayers(); // only enable Save Button if OK was clicked before boolean enableSave = blockButtonOkClicked && (this.roadClosures.size() > 0); this.saveBtn.setEnabled(enableSave); }
@SuppressWarnings("unchecked") public Path calcLeastCostPath( final Map<Node, InitialNode> fromNodes, final Map<Node, InitialNode> toNodes, final Person person) { this.person = person; this.customDataManager.reset(); Set<Node> endNodes = new HashSet<Node>(toNodes.keySet()); augmentIterationId(); RouterPriorityQueue<Node> pendingNodes = (RouterPriorityQueue<Node>) createRouterPriorityQueue(); for (Map.Entry<Node, InitialNode> entry : fromNodes.entrySet()) { DijkstraNodeData data = getData(entry.getKey()); visitNode( entry.getKey(), data, pendingNodes, entry.getValue().initialTime, entry.getValue().initialCost, null); } // find out which one is the cheapest end node double minCost = Double.POSITIVE_INFINITY; Node minCostNode = null; // do the real work while (endNodes.size() > 0) { Node outNode = pendingNodes.poll(); if (outNode == null) { // seems we have no more nodes left, but not yet reached all endNodes... endNodes.clear(); } else { DijkstraNodeData data = getData(outNode); boolean isEndNode = endNodes.remove(outNode); if (isEndNode) { InitialNode initData = toNodes.get(outNode); double cost = data.getCost() + initData.initialCost; if (cost < minCost) { minCost = cost; minCostNode = outNode; } } if (data.getCost() > minCost) { endNodes.clear(); // we can't get any better now } else { relaxNode(outNode, null, pendingNodes); } } } if (minCostNode == null) { log.warn("No route was found"); return null; } Node toNode = minCostNode; // now construct the path List<Node> nodes = new LinkedList<Node>(); List<Link> links = new LinkedList<Link>(); nodes.add(0, toNode); Link tmpLink = getData(toNode).getPrevLink(); while (tmpLink != null) { links.add(0, tmpLink); nodes.add(0, tmpLink.getFromNode()); tmpLink = getData(tmpLink.getFromNode()).getPrevLink(); } DijkstraNodeData startNodeData = getData(nodes.get(0)); DijkstraNodeData toNodeData = getData(toNode); Path path = new Path( nodes, links, toNodeData.getTime() - startNodeData.getTime(), toNodeData.getCost() - startNodeData.getCost()); return path; }