@Override
 public void handleEvent(final PersonEntersVehicleEvent event) {
   try {
     writer.newLine();
     final Id linkId = lastDepartureLinkForAgent.remove(event.getPersonId());
     writer.write(
         event.getPersonId()
             + "\t"
             + linkId
             + "\t"
             + network.getLinks().get(linkId).getFromNode().getCoord().getX()
             + "\t"
             + network.getLinks().get(linkId).getFromNode().getCoord().getY()
             + "\t"
             + lastDepartureModeForAgent.remove(event.getPersonId())
             + "\t"
             + event.getVehicleId()
             + "\t"
             + lastDepartureTimeForAgent.remove(event.getPersonId())
             + "\t"
             + event.getTime());
   } catch (IOException e) {
     throw new UncheckedIOException(e);
   }
 }
  public static void main(String[] args) {
    Matrix parkingTimesEC =
        GeneralLib.readStringMatrix(
            "A:/for marina/26. april 2012/parkingTimesAndEnergyConsumptionCH.txt");
    Network network =
        GeneralLib.readNetwork(
            "H:/data/cvs/ivt/studies/switzerland/networks/teleatlas-ivtcheu/network.xml.gz");

    HashMap<String, Id> agentIds = new HashMap();

    BasicPointVisualizer basicPointVisualizer = new BasicPointVisualizer();

    for (int i = 0; i < parkingTimesEC.getNumberOfRows(); i++) {
      String actType = parkingTimesEC.getString(i, 4);
      Id<Link> linkId = Id.create(parkingTimesEC.getString(i, 3), Link.class);
      Link link = network.getLinks().get(linkId);
      if (actType.equalsIgnoreCase("tta")) {
        agentIds.put(parkingTimesEC.getString(i, 0), null);
        // System.out.println("x");
        basicPointVisualizer.addPointCoordinate(
            new Coord(link.getCoord().getX(), link.getCoord().getY()), "", Color.GREEN);
      }
    }

    // for (String agentId:agentIds.keySet()){
    // System.out.println(agentId);
    // }

    basicPointVisualizer.write("c:/temp/abdd.kml");
  }
  public Network createSmallNetwork(Network net, SignalSystemsData data) {
    Map<Id<SignalSystem>, Set<Id<Link>>> signalsToLinks =
        DgSignalsUtils.calculateSignalizedLinksPerSystem(data);
    final Set<Id<Link>> signalizedLinks = new HashSet<>();
    for (Set<Id<Link>> linkSet : signalsToLinks.values()) {
      signalizedLinks.addAll(linkSet);
    }
    NetworkFilterManager filterManager = new NetworkFilterManager(net);
    filterManager.addLinkFilter(
        new NetworkLinkFilter() {

          @Override
          public boolean judgeLink(Link l) {
            if (signalizedLinks.contains(l.getId())) {
              return true;
            }
            return false;
          }
        });

    Network newNetwork = filterManager.applyFilters();
    if (signalizedLinks.size() != newNetwork.getLinks().size()) {
      throw new IllegalStateException("Network should contain all signalized links but not more!");
    }
    return newNetwork;
  }
Beispiel #4
0
 @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);
 }
  private void initializeOneWayCarsharingCarLeg(Link l, double now) {
    this.state = MobsimAgent.State.LEG;

    PlanElement pe = this.getCurrentPlanElement();

    Leg leg = (Leg) pe;
    Network network = scenario.getNetwork();
    endStationOW =
        findClosestAvailableParkingSpace(network.getLinks().get(leg.getRoute().getEndLinkId()));

    if (endStationOW == null) {

      this.state = MobsimAgent.State.ABORT;
      this.simulation
          .getEventsManager()
          .processEvent(new NoParkingSpaceEvent(now, leg.getRoute().getEndLinkId(), "ow"));

      return;
    } else {
      startStationOW.freeParkingSpot();
      endStationOW.reserveParkingSpot();

      Link destinationLink = endStationOW.getLink();
      // create route for the car part of the onewaycarsharing trip
      initializeCSVehicleLeg("onewaycarsharing", now, l, destinationLink);
    }
  }
  public static void main(String[] args) {
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario).readFile("../../input/network.xml");

    TravelTimeCalculator ttc =
        new TravelTimeCalculator(
            network, 60, 30 * 3600, scenario.getConfig().travelTimeCalculator());
    LeastCostPathTree st =
        new LeastCostPathTree(
            ttc.getLinkTravelTimes(),
            new RandomizingTimeDistanceTravelDisutility.Builder(TransportMode.car)
                .createTravelDisutility(
                    ttc.getLinkTravelTimes(), scenario.getConfig().planCalcScore()));
    Node origin = network.getNodes().get(Id.create(1, Node.class));
    st.calculate(network, origin, 8 * 3600);
    Map<Id<Node>, NodeData> tree = st.getTree();
    for (Map.Entry<Id<Node>, NodeData> e : tree.entrySet()) {
      Id<Node> id = e.getKey();
      NodeData d = e.getValue();
      if (d.getPrevNodeId() != null) {
        System.out.println(id + "\t" + d.getTime() + "\t" + d.getCost() + "\t" + d.getPrevNodeId());
      } else {
        System.out.println(id + "\t" + d.getTime() + "\t" + d.getCost() + "\t" + "0");
      }
    }
  }
 @Override
 public void handleEvent(LinkLeaveEvent event) {
   if (event.getVehicleId().toString().startsWith("tr")) {
     PTVehicle vehicle = ptVehicles.get(event.getVehicleId());
     if (vehicle.in) {
       vehicle.in = false;
       vehicle.incDistance(network.getLinks().get(event.getLinkId()).getLength());
     }
   } else {
     TravellerChain chain = chains.get(event.getDriverId());
     if (chain == null) {
       chain = new TravellerChain();
       chains.put(event.getDriverId(), chain);
       chain.modes.add("car");
       chain.distances.add(0.0);
     } else {
       if (chain.in) {
         chain.in = false;
         if (chain.modes.size() == chain.distances.size()
             && chain.modes.get(chain.modes.size() - 1).equals("car")) {
           double linkDistance = network.getLinks().get(event.getLinkId()).getLength();
           chain.distances.set(
               chain.distances.size() - 1,
               chain.distances.get(chain.distances.size() - 1) + linkDistance);
         } else if (chain.modes.size() == chain.distances.size())
           throw new RuntimeException("Person is leaving a link, but is not in a car mode");
         else
           throw new RuntimeException("Modes list has not the same size of distances list (car)");
       } else {
         chain.modes.add("car");
         chain.distances.add(0.0);
       }
     }
   }
 }
  @Override
  public void handleEvent(ActivityEndEvent event) {
    try {
      if (isTransitScenario) {
        if (transitDriverIds.contains(event.getPersonId())) return;
      }
      TravellerChain chain = chains.get(event.getPersonId());
      locations.put(event.getPersonId(), network.getLinks().get(event.getLinkId()).getCoord());
      if (chain == null) {
        chain = new TravellerChain();
        chains.put(event.getPersonId(), chain);
        Activity act = chain.addActivity();
        act.setCoord(network.getLinks().get(event.getLinkId()).getCoord());
        act.setEndTime(event.getTime());
        act.setFacility(event.getFacilityId());
        act.setStartTime(0.0);
        act.setType(event.getActType());

      } else if (!event.getActType().equals(PtConstants.TRANSIT_ACTIVITY_TYPE)) {
        Activity act = chain.getActs().getLast();
        act.setEndTime(event.getTime());
      }
    } catch (Exception e) {
      System.err.println(e.getStackTrace());
      System.err.println(event.toString());
    }
  }
Beispiel #9
0
    @Override
    void initializeFactory(
        AgentCounter agentCounter, MobsimTimer mobsimTimer, NetsimInternalInterface netsimEngine1) {
      double effectiveCellSize = ((Network) network).getEffectiveCellSize();

      SnapshotLinkWidthCalculator linkWidthCalculator = new SnapshotLinkWidthCalculator();
      linkWidthCalculator.setLinkWidthForVis(qsimConfig.getLinkWidthForVis());
      if (!Double.isNaN(network.getEffectiveLaneWidth())) {
        linkWidthCalculator.setLaneWidth(network.getEffectiveLaneWidth());
      }
      AbstractAgentSnapshotInfoBuilder snapshotBuilder =
          QNetsimEngine.createAgentSnapshotInfoBuilder(scenario, linkWidthCalculator);
      this.snapshotInfoFactory = new AgentSnapshotInfoFactory(linkWidthCalculator);

      this.context =
          new NetsimEngineContext(
              events,
              effectiveCellSize,
              agentCounter,
              snapshotBuilder,
              qsimConfig,
              mobsimTimer,
              linkWidthCalculator);

      this.netsimEngine = netsimEngine1;
    }
  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();
    }
  }
  @Override
  public void run(final Network network) {
    super.run(network);

    log.info("Putting landmarks on network...");
    long now = System.currentTimeMillis();
    landmarks = landmarker.identifyLandmarks(landmarkCount, network);
    log.info("done in " + (System.currentTimeMillis() - now) + " ms");

    log.info("Initializing landmarks data");
    for (Node node : network.getNodes().values()) {
      this.nodeData.put(node, new LandmarksData(this.landmarkCount));
    }

    int nOfThreads = this.numberOfThreads;
    if (nOfThreads > this.landmarks.length) {
      nOfThreads = this.landmarks.length;
    }
    if (nOfThreads < 2) {
      nOfThreads = 2; // always use at least two threads
    }
    log.info(
        "Calculating distance from each node to each of the "
            + this.landmarkCount
            + " landmarks using "
            + nOfThreads
            + " threads...");
    now = System.currentTimeMillis();

    ExecutorService executor = Executors.newFixedThreadPool(nOfThreads);
    for (int i = 0; i < this.landmarks.length; i++) {
      executor.execute(new Calculator(i, this.landmarks[i], this.nodeData, this.costFunction));
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
      log.info("wait for landmarks Calculator to finish...");
      try {
        executor.awaitTermination(10, TimeUnit.MINUTES);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    for (Node node : network.getNodes().values()) {
      LandmarksData r = getNodeData(node);
      r.updateMinMaxTravelTimes();
    }

    for (Node node : network.getNodes().values()) {
      LandmarksData r = getNodeData(node);
      for (int i = 0; i < this.landmarks.length; i++) {
        if (r.getMinLandmarkTravelTime(i) > r.getMaxLandmarkTravelTime(i)) {
          log.info("Min > max for node " + node.getId() + " and landmark " + i);
        }
      }
    }

    log.info("done in " + (System.currentTimeMillis() - now) + " ms");
  }
Beispiel #12
0
  public static void main(String[] args) {

    // Dummy MATSim scenario including dummy network
    Config conf = ConfigUtils.createConfig();
    conf.global().setCoordinateSystem("EPSG:3395");
    Scenario sc = ScenarioUtils.createScenario(conf);
    //		Sim2DConfig conf2d = Sim2DConfigUtils.createConfig();
    //		Sim2DScenario sc2d = Sim2DScenarioUtils.createSim2dScenario(conf2d);
    //		sc.addScenarioElement(Sim2DScenario.ELEMENT_NAME,sc2d);
    Network net = sc.getNetwork();
    NetworkFactory fac = net.getFactory();
    Node n0 = fac.createNode(Id.create("0", Node.class), new Coord(minX, minY));
    Node n1 = fac.createNode(Id.create("1", Node.class), new Coord(minX, maxY));
    Node n2 = fac.createNode(Id.create("2", Node.class), new Coord(maxX, maxY));
    Node n3 = fac.createNode(Id.create("3", Node.class), new Coord(maxX, minY));
    net.addNode(n0);
    net.addNode(n1);
    net.addNode(n2);
    net.addNode(n3);

    // visualization stuff
    EventsManager em = new EventsManagerImpl();
    EventBasedVisDebuggerEngine vis = new EventBasedVisDebuggerEngine(sc);
    em.addHandler(vis);

    // routing algorithm - for now standard Dijkstra could be replaced by A*  in future
    Dijkstra d = new Dijkstra(env);

    // dummy data
    int number = 20;
    for (double time = 0; time <= 1000; time++) {
      List<XYVxVyEventImpl> events = createDummyData(MatsimRandom.getRandom().nextInt(21), time);

      List<TwoDObject> objs = new ArrayList<TwoDObject>();
      for (XYVxVyEventImpl e : events) {
        em.processEvent(e); // needed for visualization
        objs.add(e);
      }

      System.out.println("");
      LinearQuadTreeLD quad = new LinearQuadTreeLD(objs, env, em);

      // routing
      List<Quad> fromL = quad.query(new Envelope(0, 0.1, 0, 0.1));
      Quad from = fromL.get(0);
      List<Quad> toL = quad.query(new Envelope(19.9, 20, 19.9, 20));
      Quad to = toL.get(0);
      LinkedList<Quad> path = d.computeShortestPath(quad, from, to);
      path.addFirst(from);
      draw(path, em);
      //			to.getEnvelope().get
      try {
        Thread.sleep(2000); // to slow it down a bit
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }
    }
  }
 @Override
 public void handleEvent(PersonArrivalEvent event) {
   try {
     if (isTransitScenario) {
       if (transitDriverIds.contains(event.getPersonId())) return;
     }
     TravellerChain chain = chains.get(event.getPersonId());
     switch (event.getLegMode()) {
       case "walk":
       case "transit_walk":
         {
           Journey journey = chain.getJourneys().getLast();
           Walk walk = journey.getWalks().getLast();
           walk.setDest(network.getLinks().get(event.getLinkId()).getCoord());
           walk.setEndTime(event.getTime());
           walk.setDistance(walk.getDuration() * walkSpeed);
           break;
         }
       case TransportMode.car:
         {
           Journey journey = chain.getJourneys().getLast();
           journey.setDest(network.getLinks().get(event.getLinkId()).getCoord());
           journey.setEndTime(event.getTime());
           Trip trip = journey.getTrips().getLast();
           trip.setDistance(journey.getDistance());
           trip.setEndTime(event.getTime());
           chain.inCar = false;
           break;
         }
       case "pt":
         if (isTransitScenario) {
           Journey journey = chain.getJourneys().getLast();
           Trip trip = journey.getTrips().getLast();
           trip.setDest(network.getLinks().get(event.getLinkId()).getCoord());
           trip.setEndTime(event.getTime());
           journey.setPossibleTransfer(new Transfer());
           journey.getPossibleTransfer().setStartTime(event.getTime());
           journey.getPossibleTransfer().setFromTrip(trip);
         } else {
           Journey journey = chain.getJourneys().getLast();
           journey.setEndTime(event.getTime());
           journey.setDest(network.getLinks().get(event.getLinkId()).getCoord());
           journey.setEndTime(event.getTime());
         }
         break;
       default:
         Journey journey = chain.getJourneys().getLast();
         journey.setEndTime(event.getTime());
         journey.setDest(network.getLinks().get(event.getLinkId()).getCoord());
         journey.setEndTime(event.getTime());
         break;
     }
   } catch (Exception e) {
     System.err.println(e.getStackTrace());
     System.err.println(event.toString());
   }
 }
  public void createMapping(CoordinateTransformation coordinateTransformation) throws Exception {
    network = scenario.getNetwork();

    log.info("Loading Network ... done");
    log.info("Nodes: " + network.getNodes().size());
    log.info("Links: " + network.getLinks().size());

    /*
     * read zones shape file
     */
    zones = new HashSet<SimpleFeature>();

    for (SimpleFeature feature : ShapeFileReader.getAllFeatures(shapeFile)) {
      zones.add(feature);
    }

    zonesMap = new TreeMap<Integer, SimpleFeature>();
    for (SimpleFeature zone : zones) {
      //			int id = Integer.valueOf(zone.getID().replace("postcode4.", ""));	// Object Id
      //			int id = ((Long)zone.getAttribute(1)).intValue();	// Zone Id
      int id = ((Long) zone.getAttribute(3)).intValue(); // PostCode
      zonesMap.put(id, zone);
    }

    /*
     * print zones
     */
    log.info("Using " + zones.size() + " zones.");

    log.info("Adding connector nodes and links...");
    addConnectorLinks();
    log.info("done.");

    log.info("writing network ...");
    new NetworkWriter(network).write(networkOutFile);
    log.info(" ... done.");

    log.info("writing kmz network ...");
    ObjectFactory kmlObjectFactory = new ObjectFactory();
    KMZWriter kmzWriter = new KMZWriter(kmzOutFile);

    KmlType mainKml = kmlObjectFactory.createKmlType();
    DocumentType mainDoc = kmlObjectFactory.createDocumentType();
    mainKml.setAbstractFeatureGroup(kmlObjectFactory.createDocument(mainDoc));

    KmlNetworkWriter kmlNetworkWriter;
    kmlNetworkWriter =
        new KmlNetworkWriter(
            network, new GeotoolsTransformation("EPSG:28992", "WGS84"), kmzWriter, mainDoc);

    mainDoc
        .getAbstractFeatureGroup()
        .add(kmlObjectFactory.createFolder(kmlNetworkWriter.getNetworkFolder()));
    kmzWriter.writeMainKml(mainKml);
    kmzWriter.close();
    log.info("... done.");
  }
  /** @param args */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    String networkPath = args[0];
    String newNetworkPath = args[1];
    String shapeFilePath = args[2];

    // String shapeFile = "C:/Work/Roadpricing Scenarios/SiouxFalls/Network/SiouxFalls_nodes.shp";

    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());

    new NetworkReaderMatsimV1(scenario).parse(networkPath);
    Network network = scenario.getNetwork();
    Map<Id<Node>, ? extends Node> nodes = network.getNodes();

    Double x = 0.0;
    Double y = 0.0;

    System.out.println(shapeFilePath);
    ShapeFileReader shapeFileReader = new ShapeFileReader();
    Collection<SimpleFeature> fts = shapeFileReader.readFileAndInitialize(shapeFilePath);
    log.info("Shape file contains " + fts.size() + " features!");

    for (SimpleFeature ft : fts) {
      Geometry geo = (Geometry) ft.getDefaultGeometry();
      Coordinate[] coordinates = geo.getCoordinates();
      Collection<Property> properties = ft.getProperties("Id");

      System.out.println(
          "Feature: "
              + ft.getID()
              + ","
              + ft.getIdentifier().toString()
              + ","
              + ft.getName().toString());

      for (int i = 0; i < coordinates.length; i++) {
        System.out.print(coordinates[i].x + "," + coordinates[i].y + "   ");
        x = coordinates[i].x;
        y = coordinates[i].y;
      }

      for (Property p : properties) {
        System.out.println("Value: " + p.getValue().toString());
        Node node = nodes.get(Id.create(p.getValue().toString(), Node.class));
        node.getCoord().setXY(x, y);
        System.out.println("Name: " + p.getName().toString());
        System.out.println("Descriptor: " + p.getDescriptor().toString());
      }
      System.out.println();
      System.out.println();

      NetworkWriter writer = new NetworkWriter(network);
      writer.write(newNetworkPath);
    }
  }
  private Network createNetwork(Scenario sc) {
    Network net = sc.getNetwork();
    if (net.getCapacityPeriod() != 3600.0) {
      throw new IllegalStateException();
    }

    ((NetworkImpl) net).setEffectiveLaneWidth(1.0);
    NetworkFactory fac = net.getFactory();
    net.addNode(fac.createNode(idN1, new Coord(-500, 0)));
    net.addNode(fac.createNode(idN2, new Coord(-300, 0)));
    net.addNode(fac.createNode(idN3, new Coord(-100, 100)));
    net.addNode(fac.createNode(idN4, new Coord(-100, -100)));
    net.addNode(fac.createNode(idN5, new Coord(100, 100)));
    net.addNode(fac.createNode(idN6, new Coord(100, -100)));
    net.addNode(fac.createNode(idN7, new Coord(300, 0)));
    net.addNode(fac.createNode(idN8, new Coord(500, 0)));

    this.createAndAddLinks(idL12, idL21, idN1, idN2, net);
    this.createAndAddLinks(idL23, idL32, idN2, idN3, net);
    this.createAndAddLinks(idL24, idL42, idN2, idN4, net);
    this.createAndAddLinks(idL35, idL53, idN3, idN5, net);
    this.createAndAddLinks(idL46, idL64, idN4, idN6, net);
    this.createAndAddLinks(idL57, idL75, idN5, idN7, net);
    this.createAndAddLinks(idL67, idL76, idN6, idN7, net);
    this.createAndAddLinks(idL78, idL87, idN7, idN8, net);

    return net;
  }
Beispiel #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);
    }
  }
  public static TransitSchedule removeAllRoutesWithMissingLinksFromSchedule(
      TransitSchedule transitSchedule, Network network) {
    log.info("Removing stops and routes with missing links from the schedule");
    TransitSchedule tS = TransitScheduleCleaner.makeTransitScheduleModifiable(transitSchedule);
    printStatistic(tS);
    int removedRoutes = 0;

    // Remove routes with missing links
    for (TransitLine transitLine : tS.getTransitLines().values()) {

      Set<TransitRoute> transitRouteToBeRemoved = new HashSet<TransitRoute>();

      for (TransitRoute transitRoute : transitLine.getRoutes().values()) {

        // Remove Route, when links are missing in the network
        if (network.getLinks().get(transitRoute.getRoute().getStartLinkId()) == null) {
          transitRouteToBeRemoved.add(transitRoute);
          continue;
        }

        for (Id linkId : transitRoute.getRoute().getLinkIds()) {
          if (network.getLinks().get(linkId) == null) {
            transitRouteToBeRemoved.add(transitRoute);
            break;
          }
        }

        if (network.getLinks().get(transitRoute.getRoute().getEndLinkId()) == null) {
          transitRouteToBeRemoved.add(transitRoute);
          continue;
        }

        // Remove route, if one of its stops, has a missing link
        for (TransitRouteStop transitRouteStop : transitRoute.getStops()) {
          if (network.getLinks().get(transitRouteStop.getStopFacility().getLinkId()) == null) {
            transitRouteToBeRemoved.add(transitRoute);
            break;
          }
        }
      }

      for (TransitRoute transitRoute : transitRouteToBeRemoved) {
        if (transitLine.removeRoute(transitRoute) == true) {
          removedRoutes++;
        }
      }
    }

    log.info("Removed " + removedRoutes + " routes due to missing links or stops");
    printStatistic(tS);

    return tS;
  }
 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");
 }
  private void initializeTwoWayCarsharingEndCarLeg(Link l, double now) {
    this.state = MobsimAgent.State.LEG;

    PlanElement pe = this.getCurrentPlanElement();

    Leg leg = (Leg) pe;
    Network network = scenario.getNetwork();
    Link link = mapTW.get(network.getLinks().get(leg.getRoute().getEndLinkId()));

    // create route for the car part of the twowaycarsharing trip
    initializeCSVehicleLeg(
        "twowaycarsharing", now, network.getLinks().get(leg.getRoute().getStartLinkId()), link);
  }
Beispiel #22
0
 public void addLinkNetwork(Node fromNode, Node toNode) {
   Id<Link> linkId = Id.create(network.getLinks().size() * 2, Link.class);
   network.addLink(network.getFactory().createLink(linkId, fromNode, toNode));
   try {
     PrintWriter writer =
         new PrintWriter(new FileWriter(RoutesPathsGenerator.NEW_NETWORK_LINKS_FILE, true));
     writer.println(linkId);
     writer.println(fromNode.getId());
     writer.println(toNode.getId());
     writer.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  private Population getTestPopulation() {
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario.getNetwork()).readFile("test/scenarios/equil/network.xml");

    Link link1 = network.getLinks().get(Id.create(1, Link.class));
    Link link20 = network.getLinks().get(Id.create(20, Link.class));

    Population population = scenario.getPopulation();

    Person person;
    PlanImpl plan;
    LegImpl leg;
    NetworkRoute route;

    person = PopulationUtils.createPerson(Id.create("1", Person.class));
    plan = PersonUtils.createAndAddPlan(person, true);
    ActivityImpl a = plan.createAndAddActivity("h", link1.getId());
    a.setEndTime(7.0 * 3600);
    leg = plan.createAndAddLeg(TransportMode.car);
    route = new LinkNetworkRouteImpl(link1.getId(), link20.getId());
    route.setLinkIds(link1.getId(), NetworkUtils.getLinkIds("6 15"), link20.getId());
    leg.setRoute(route);
    plan.createAndAddActivity("w", link20.getId());
    population.addPerson(person);

    person = PopulationUtils.createPerson(Id.create("2", Person.class));
    plan = PersonUtils.createAndAddPlan(person, true);
    ActivityImpl a2 = plan.createAndAddActivity("h", link1.getId());
    a2.setEndTime(7.0 * 3600 + 5.0 * 60);
    leg = plan.createAndAddLeg(TransportMode.car);
    route = new LinkNetworkRouteImpl(link1.getId(), link20.getId());
    route.setLinkIds(link1.getId(), NetworkUtils.getLinkIds("6 15"), link20.getId());
    leg.setRoute(route);
    plan.createAndAddActivity("w", link20.getId());
    population.addPerson(person);

    person = PopulationUtils.createPerson(Id.create("3", Person.class));
    plan = PersonUtils.createAndAddPlan(person, true);
    ActivityImpl a3 = plan.createAndAddActivity("h", link1.getId());
    a3.setEndTime(7.0 * 3600 + 10.0 * 60);
    leg = plan.createAndAddLeg(TransportMode.car);
    route = new LinkNetworkRouteImpl(link1.getId(), link20.getId());
    route.setLinkIds(link1.getId(), NetworkUtils.getLinkIds("5 14"), link20.getId());
    leg.setRoute(route);
    plan.createAndAddActivity("w", link20.getId());
    population.addPerson(person);

    return population;
  }
  /*package*/ void addConnectorLinks() {

    QuadTree<Node> quadTree = getNodesQuadTree();
    NetworkFactory factory = network.getFactory();

    /*
     * Try to use the centroid of the polygon. If that does not lie within
     * the polygon, use an interior point.
     */
    for (Entry<Integer, SimpleFeature> entry : zonesMap.entrySet()) {
      int zoneId = entry.getKey();
      SimpleFeature zone = entry.getValue();

      if (SpecialZones.skipZone(zone)) continue;

      Geometry polygon = (Geometry) zone.getDefaultGeometry();
      Point point = polygon.getCentroid();
      if (!polygon.contains(point)) point = polygon.getInteriorPoint();

      /*
       * Convert coordinate from WGS84 to EPSG:28992 (Netherlands Projection)
       */
      Coord wgs84Coord = new Coord(point.getCoordinate().x, point.getCoordinate().y);
      Coord nodeCoord = ct.transform(wgs84Coord);

      Id<Node> nodeId = Id.create(String.valueOf(zoneId), Node.class);
      network.addNode(factory.createNode(nodeId, nodeCoord));

      Node networkConnectorNode = quadTree.getClosest(nodeCoord.getX(), nodeCoord.getY());
      Id<Node> networkConnectorNodeId = networkConnectorNode.getId();

      double length = CoordUtils.calcDistance(nodeCoord, networkConnectorNode.getCoord());

      Id<Link> linkFromId = Id.create(String.valueOf(zoneId) + "from", Link.class);
      Link fromLink = factory.createLink(linkFromId, nodeId, networkConnectorNodeId);
      fromLink.setLength(length);
      fromLink.setCapacity(this.connectorCapacity);
      fromLink.setFreespeed(this.connectorLinkFreeSpeed);
      network.addLink(fromLink);

      Id<Link> linkToId = Id.create(String.valueOf(zoneId) + "to", Link.class);
      Link toLink = factory.createLink(linkToId, networkConnectorNodeId, nodeId);
      toLink.setLength(length);
      toLink.setCapacity(this.connectorCapacity);
      toLink.setFreespeed(this.connectorLinkFreeSpeed);
      network.addLink(toLink);
    }
  }
  @Override
  public void handleEvent(WarmEmissionEvent event) {

    Id<Person> driverId =
        Id.createPersonId(
            event
                .getVehicleId()); // TODO [AA]: either it should be mapped to vehicle id or read
                                  // events file too to get driver id

    if (this.af != null) { // area filtering
      Link link = network.getLinks().get(event.getLinkId());
      if (!this.af.isLinkInsideShape(link)) return;

      if (this.ug == null || this.pf == null) { // only area filtering
        delegate.handleEvent(event);
      } else if (this.pf
          .getUserGroupAsStringFromPersonId(driverId)
          .equals(this.ug)) { // both filtering
        delegate.handleEvent(event);
      }

    } else {

      if (this.ug == null || this.pf == null) { // no filtering
        delegate.handleEvent(event);
      } else if (this.pf
          .getUserGroupAsStringFromPersonId(driverId)
          .equals(this.ug)) { // user group filtering
        delegate.handleEvent(event);
      }
    }
  }
 @Override
 public void handleEvent(ActivityStartEvent event) {
   TravellerChain chain = chains.get(event.getPersonId());
   if (!event.getActType().equals(PtConstants.TRANSIT_ACTIVITY_TYPE)) {
     if (chain == null) {
       chain = new TravellerChain();
       chains.put(event.getPersonId(), chain);
       chain.distances.add(0.0);
       chain.modes.add("walk");
     }
     chains.get(event.getPersonId()).in = false;
     acts.put(
         event.getPersonId(),
         acts.get(event.getPersonId()) == null ? 1 : acts.get(event.getPersonId()) + 1);
   }
   if (chain.modes.get(chain.modes.size() - 1).equals("walk")) {
     Double distance =
         CoordUtils.calcDistance(
             locations.get(event.getPersonId()),
             network.getLinks().get(event.getLinkId()).getCoord());
     if (chain.modes.size() == chain.distances.size()) {
       if (event.getActType().equals(PtConstants.TRANSIT_ACTIVITY_TYPE))
         chain.modes.set(chain.modes.size() - 1, "pt");
       chain.distances.set(chain.distances.size() - 1, distance);
     } else {
       chain.modes.remove(chain.modes.size() - 1);
       chain.distances.set(
           chain.distances.size() - 1, chain.distances.get(chain.distances.size() - 1) + distance);
     }
   }
 }
  @Override
  public void handleEvent(ActivityStartEvent event) {
    try {
      if (isTransitScenario) {
        if (transitDriverIds.contains(event.getPersonId())) return;
      }
      TravellerChain chain = chains.get(event.getPersonId());
      boolean beforeInPT = chain.isInPT();
      if (event.getActType().equals(PtConstants.TRANSIT_ACTIVITY_TYPE)) {
        chain.setInPT(true);

      } else {
        chain.setInPT(false);
        chain.traveling = false;
        Activity act = chain.addActivity();
        act.setCoord(network.getLinks().get(event.getLinkId()).getCoord());
        act.setFacility(event.getFacilityId());
        act.setStartTime(event.getTime());
        act.setType(event.getActType());
        // end the preceding journey
        Journey journey = chain.getJourneys().getLast();
        journey.setDest(act.getCoord());
        journey.setEndTime(event.getTime());
        journey.setToAct(act);
        if (beforeInPT) journey.getWalks().getLast().setEgressWalk(true);
      }
    } catch (Exception e) {
      System.err.println(e.getStackTrace());
      System.err.println(event.toString());
      ;
    }
  }
Beispiel #28
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 "";
 }
  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;
  }
Beispiel #30
0
 public Collection<Link> getStopLinks() {
   Collection<Link> links = new ArrayList<Link>();
   for (StopTime stopTime : trip.getStopTimes().values()) {
     String linkId = stops.get(stopTime.getStopId()).getLinkId();
     if (linkId != null) links.add(network.getLinks().get(Id.create(linkId, Link.class)));
   }
   return links;
 }