Пример #1
0
  @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);
  }
Пример #2
0
 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 "";
 }
Пример #3
0
 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);
 }
Пример #4
0
 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();
 }
Пример #5
0
  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());
  }
Пример #6
0
 public Node getNearestNode(double x, double y) {
   Coord point = new Coord(x, y);
   Node nearest = links.get(0).getFromNode();
   double nearestDistance = CoordUtils.calcEuclideanDistance(point, nearest.getCoord());
   for (Link link : links) {
     double distance = CoordUtils.calcEuclideanDistance(point, link.getToNode().getCoord());
     if (distance < nearestDistance) {
       nearestDistance = distance;
       nearest = link.getToNode();
     }
   }
   return nearest;
 }
Пример #7
0
 @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 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());
  }
Пример #9
0
 private void expandLandmarkFrom() {
   LandmarksFromTravelTimeComparator comparator =
       new LandmarksFromTravelTimeComparator(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 fromTravTime =
         ((LandmarksData) this.nodeData.get(node)).getFromLandmarkTravelTime(this.landmarkIdx);
     LandmarksData role2;
     for (Link l : node.getOutLinks().values()) {
       Node n;
       n = l.getToNode();
       double linkTravTime = this.costFunction.getLinkMinimumTravelDisutility(l);
       role2 = (LandmarksData) this.nodeData.get(n);
       double totalTravelTime = fromTravTime + linkTravTime;
       if (role2.getFromLandmarkTravelTime(this.landmarkIdx) > totalTravelTime) {
         role2.setFromLandmarkTravelTime(this.landmarkIdx, totalTravelTime);
         pendingNodes.add(n);
       }
     }
   }
 }
Пример #10
0
  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");
  }
Пример #11
0
  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;
  }
Пример #12
0
  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);
  }
Пример #13
0
  // 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);
      }
    }
  }
Пример #14
0
 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);
 }
 /**
  * Logic that was previously located in the relaxNode(...) method. By doing so, the FastDijkstra
  * can overwrite relaxNode without copying the logic.
  */
 /*package*/ void relaxNodeLogic(
     final Link l,
     final RouterPriorityQueue<Node> pendingNodes,
     final double currTime,
     final double currCost,
     final Node toNode,
     final PreProcessDijkstra.DeadEndData ddOutData) {
   addToPendingNodes(l, l.getToNode(), pendingNodes, currTime, currCost, toNode);
 }
Пример #16
0
 private Set<Link> getLinksWithinSearchRadius(Coord centralCoords) {
   Set<Link> linksWithinRadius = new HashSet<>();
   for (Link link : this.network.getLinks().values()) {
     if (NetworkUtils.getEuclidianDistance(centralCoords, link.getToNode().getCoord())
         < SEARCH_RADIUS) {
       linksWithinRadius.add(link);
     }
   }
   return linksWithinRadius;
 }
Пример #17
0
  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);
    }
  }
Пример #18
0
 /**
  * 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;
   }
 }
Пример #19
0
 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;
 }
Пример #20
0
  /**
   * 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;
  }
Пример #21
0
  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;
  }
Пример #22
0
 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;
 }
Пример #23
0
  private boolean linkToNodeNotInServiceArea(Link link) {
    Coord toNodeCoord = link.getToNode().getCoord();

    if (toNodeCoord.getX() < this.pConfigGroup.getMinX()) {
      return true;
    }
    if (toNodeCoord.getX() > this.pConfigGroup.getMaxX()) {
      return true;
    }
    if (toNodeCoord.getY() < this.pConfigGroup.getMinY()) {
      return true;
    }
    if (toNodeCoord.getY() > this.pConfigGroup.getMaxY()) {
      return true;
    }
    return false;
  }
Пример #24
0
  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()));
  }
Пример #25
0
  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());
  }
Пример #26
0
  private void relaxNode(final Node n, PriorityQueue<Node> pendingNodes) {
    NodeData nData = nodeData.get(n.getId());
    double currTime = nData.getTime();
    double currCost = nData.getCost();
    for (Link l : n.getOutLinks().values()) {
      Node nn = l.getToNode();
      NodeData nnData = nodeData.get(nn.getId());
      if (nnData == null) {
        nnData = new NodeData();
        this.nodeData.put(nn.getId(), nnData);
      }
      double visitCost =
          currCost + tcFunction.getLinkTravelDisutility(l, currTime, PERSON, VEHICLE);
      double visitTime = currTime + ttFunction.getLinkTravelTime(l, currTime, PERSON, VEHICLE);

      if (visitCost < nnData.getCost()) {
        pendingNodes.remove(nn);
        nnData.visit(n.getId(), visitCost, visitTime);
        additionalComputationsHook(l, currTime);
        pendingNodes.add(nn);
      }
    }
  }
Пример #27
0
  private void decomposePassPaths(Map<Link, Set<Path>> routes, MLCell j) {
    Network network = optimContext.network;
    Map<Id<Node>, ? extends Node> nodenetwork = network.getNodes();
    ArrayList<MLArray> paths = j.cells();
    for (MLArray path : paths) {
      MLCell cellpath = (MLCell) path;
      if (path.getM() != 0) {
        List<Node> nodelist = new ArrayList<Node>();
        List<Link> linklist = new ArrayList<Link>();
        MLDouble route = (MLDouble) (cellpath.get(0));
        double[][] nodes = route.getArray();
        for (int i = 0; i < nodes.length - 1; i++) {
          int currnode = (int) nodes[i][0];
          int nextnode = (int) nodes[i + 1][0];
          Node start = nodenetwork.get(Id.createNodeId(Integer.toString(currnode)));
          Node finish = nodenetwork.get(Id.createNodeId(Integer.toString(nextnode)));
          nodelist.add(start);
          Collection<? extends Link> possiblelinks = start.getOutLinks().values();
          for (Link l : possiblelinks) {
            if (l.getToNode().equals(finish)) {
              linklist.add(l);
              break;
            }
          }
          if (i == nodes.length - 2) {
            nodelist.add(finish);
          }

          Path temppath = convertNodeListtoPath(nodelist, linklist);
          if (routes.get(linklist.get(0)) == null) { // add path to routelist
            routes.put(linklist.get(0), new HashSet<Path>());
          }
          routes.get(linklist.get(0)).add(temppath);
        }
      }
    }
  }
Пример #28
0
  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);
  }
Пример #29
0
 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);
   }
 }
Пример #30
0
  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);
  }