private void startAct(final Attributes atts) {
    ActivityImpl act = null;
    if (atts.getValue("link") != null) {
      final Id<Link> linkId = Id.create(atts.getValue("link"), Link.class);
      act = this.currplan.createAndAddActivity(atts.getValue("type"), linkId);
      if (atts.getValue(ATTR_X100) != null && atts.getValue(ATTR_Y100) != null) {
        final Coord coord = parseCoord(atts);
        act.setCoord(coord);
      }
    } else if (atts.getValue(ATTR_X100) != null && atts.getValue(ATTR_Y100) != null) {
      final Coord coord = parseCoord(atts);
      act = this.currplan.createAndAddActivity(atts.getValue("type"), coord);
    } else {
      throw new IllegalArgumentException(
          "Either the coords or the link must be specified for an Act.");
    }
    act.setStartTime(Time.parseTime(atts.getValue("start_time")));
    act.setMaximumDuration(Time.parseTime(atts.getValue("dur")));
    act.setEndTime(Time.parseTime(atts.getValue("end_time")));

    if (this.routeNodes != null) {
      this.currroute.setLinkIds(
          this.prevAct.getLinkId(),
          NetworkUtils.getLinkIds(
              RouteUtils.getLinksFromNodes(NetworkUtils.getNodes(this.network, this.routeNodes))),
          act.getLinkId());
      this.routeNodes = null;
      this.currroute = null;
    }
    this.prevAct = act;
  }
Example #2
0
  public void runAccessibilityComputation() {

    final Network network = (Network) this.scenario.getNetwork();

    ProgressBar bar = new ProgressBar(this.measuringPoints.getZones().size());

    for (Zone<Id<Zone>> measurePoint : this.measuringPoints.getZones()) {

      bar.update();

      Coord coord = MGC.point2Coord(measurePoint.getGeometry().getCentroid());
      Point p = measurePoint.getGeometry().getCentroid();
      final Coord coord1 = coord;

      Link nearestLink = NetworkUtils.getNearestLinkExactly(network, coord1);
      final Coord coord2 = coord;
      Node nearestNode = NetworkUtils.getNearestNode(network, coord2);

      Distances distance =
          NetworkUtil.getDistances2NodeViaGivenLink(coord, nearestLink, nearestNode);
      double distanceMeasuringPoint2Road_meter = distance.getDistancePoint2Intersection();

      double walkTravelTime_h =
          distanceMeasuringPoint2Road_meter
              / this.walkSpeedMeterPerHour; // travel time from coord to network (node or link)

      if (boundary.contains(p)) this.freeSpeedGrid.setValue(walkTravelTime_h, p);
    }
  }
 @Override
 public void process(
     ActivityFacility quelle,
     ActivityFacility ziel,
     int quantity,
     String mode,
     String destinationActivityType,
     double departureTimeOffset) {
   Node quellNode = NetworkUtils.getNearestNode(((Network) network), quelle.getCoord());
   Node zielNode = NetworkUtils.getNearestNode(((Network) network), ziel.getCoord());
   Path path = dijkstra.calcLeastCostPath(quellNode, zielNode, 0.0, null, null);
   double travelTimeToWork = calculateFreespeedTravelTimeToNode(this.network, path, zielNode);
   //		if(quelle.id == 9375 && ziel.id == 9162){
   System.out.println(
       "from zone "
           + quelle.getId()
           + " to zone "
           + ziel.getId()
           + ", it takes "
           + travelTimeToWork
           + " seconds to travel.");
   sink.process(
       quelle,
       ziel,
       quantity,
       mode,
       destinationActivityType,
       departureTimeOffset - travelTimeToWork);
   //		}
 }
  @Override
  public void startTag(String name, Attributes atts, Stack<String> context) {

    if (name.equals("company")) {

      companyName = atts.getValue("name");
      this.companyNames.add(companyName);
      createQuadTrees();

      twowaycarsharingstationsMap = new HashMap<String, CarsharingStation>();
      onewaycarsharingstationsMap = new HashMap<String, CarsharingStation>();

      ffvehiclesMap = new HashMap<CSVehicle, Link>();
      ffvehicleIdMap = new HashMap<String, CSVehicle>();

      owvehicleIdMap = new HashMap<String, CSVehicle>();
      owvehiclesMap = new HashMap<CSVehicle, Link>();

      twvehicleIdMap = new HashMap<String, CSVehicle>();
      twvehiclesMap = new HashMap<CSVehicle, Link>();
      // allVehicles = new HashMap<String, CSVehicle>();
      // companies = new HashMap<String, CompanyContainer>();
    } else if (name.equals("twoway") || name.equals("oneway")) {
      csType = name;
      id = atts.getValue("id");
      String xCoord = atts.getValue("x");
      String yCoord = atts.getValue("y");
      Coord coordStation = new Coord(Double.parseDouble(xCoord), Double.parseDouble(yCoord));

      link = (Link) NetworkUtils.getNearestLinkExactly(network, coordStation);
      vehicles = new ArrayList<StationBasedVehicle>();
      if (name.equals("oneway")) {
        avaialbleParkingSpots = Integer.parseInt(atts.getValue("freeparking"));
        hasOW = true;
      } else hasTW = true;

    } else if (name.equals("freefloating")) {
      hasFF = true;
      String xCoord = atts.getValue("x");
      String yCoord = atts.getValue("y");
      String type = atts.getValue("type");
      Coord coordStation = new Coord(Double.parseDouble(xCoord), Double.parseDouble(yCoord));

      link = (Link) NetworkUtils.getNearestLinkExactly(network, coordStation);
      FFVehicleImpl ffcsvehicle = new FFVehicleImpl(type, atts.getValue("id"), companyName);
      ffVehicleLocationQuadTree.put(link.getCoord().getX(), link.getCoord().getY(), ffcsvehicle);
      ffvehiclesMap.put(ffcsvehicle, link);
      ffvehicleIdMap.put(atts.getValue("id"), ffcsvehicle);
      this.allVehicles.put(atts.getValue("id"), ffcsvehicle);
      allVehicleLocations.put(ffcsvehicle, link);
    } else if (name.equals("vehicle")) {

      StationBasedVehicle vehicle =
          new StationBasedVehicle(
              atts.getValue("type"), atts.getValue("vehicleID"), id, csType, companyName);
      vehicles.add(vehicle);
      this.allVehicles.put(atts.getValue("vehicleID"), vehicle);
      this.allVehicleLocations.put(vehicle, link);
    }
  }
 /**
  * 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;
   }
 }
 private void startAct(final Attributes atts) {
   Coord coord = null;
   if (atts.getValue("link") != null) {
     Id<Link> linkId = Id.create(atts.getValue("link"), Link.class);
     this.curract = this.currplan.createAndAddActivity(atts.getValue(ATTR_TYPE), linkId);
     if ((atts.getValue("x") != null) && (atts.getValue("y") != null)) {
       coord =
           new Coord(
               Double.parseDouble(atts.getValue("x")), Double.parseDouble(atts.getValue("y")));
       this.curract.setCoord(coord);
     }
   } else if ((atts.getValue("x") != null) && (atts.getValue("y") != null)) {
     coord =
         new Coord(Double.parseDouble(atts.getValue("x")), Double.parseDouble(atts.getValue("y")));
     this.curract = this.currplan.createAndAddActivity(atts.getValue(ATTR_TYPE), coord);
   } else {
     throw new IllegalArgumentException(
         "In this version of MATSim either the coords or the link must be specified for an Act.");
   }
   this.curract.setStartTime(Time.parseTime(atts.getValue("start_time")));
   this.curract.setMaximumDuration(Time.parseTime(atts.getValue("dur")));
   this.curract.setEndTime(Time.parseTime(atts.getValue("end_time")));
   String fId = atts.getValue("facility");
   if (fId != null) {
     this.curract.setFacilityId(Id.create(fId, ActivityFacility.class));
   }
   if (this.routeDescription != null) {
     Id<Link> startLinkId = null;
     if (this.prevAct.getLinkId() != null) {
       startLinkId = this.prevAct.getLinkId();
     }
     Id<Link> endLinkId = null;
     if (this.curract.getLinkId() != null) {
       endLinkId = this.curract.getLinkId();
     }
     this.currRoute.setStartLinkId(startLinkId);
     this.currRoute.setEndLinkId(endLinkId);
     if (this.currRoute instanceof NetworkRoute) {
       ((NetworkRoute) this.currRoute)
           .setLinkIds(
               startLinkId,
               NetworkUtils.getLinkIds(
                   RouteUtils.getLinksFromNodes(
                       NetworkUtils.getNodes(this.network, this.routeDescription))),
               endLinkId);
     } else {
       this.currRoute.setRouteDescription(this.routeDescription.trim());
     }
     this.routeDescription = null;
     this.currRoute = null;
   }
 }
Example #7
0
  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;
  }
Example #8
0
  public static final QuadTree<ActivityFacility> createFacilityQuadTree(Controler controler) {
    double minx = (1.0D / 0.0D);
    double miny = (1.0D / 0.0D);
    double maxx = (-1.0D / 0.0D);
    double maxy = (-1.0D / 0.0D);

    for (Link l : controler.getScenario().getNetwork().getLinks().values()) {
      if (l.getCoord().getX() < minx) minx = l.getCoord().getX();
      if (l.getCoord().getY() < miny) miny = l.getCoord().getY();
      if (l.getCoord().getX() > maxx) maxx = l.getCoord().getX();
      if (l.getCoord().getY() <= maxy) continue;
      maxy = l.getCoord().getY();
    }
    minx -= 1.0D;
    miny -= 1.0D;
    maxx += 1.0D;
    maxy += 1.0D;

    QuadTree<ActivityFacility> facilityQuadTree =
        new QuadTree<ActivityFacility>(minx, miny, maxx, maxy);
    for (ActivityFacility f :
        controler.getScenario().getActivityFacilities().getFacilities().values()) {
      ((ActivityFacilityImpl) f)
          .setLinkId(
              NetworkUtils.getNearestLink(
                      ((NetworkImpl) controler.getScenario().getNetwork()), f.getCoord())
                  .getId());
      Coord c = f.getCoord();
      facilityQuadTree.put(c.getX(), c.getY(), f);
    }
    return facilityQuadTree;
  }
  protected TreeMap<Integer, String> createInitialLocationsForGA(
      TreeMap<Id, LinkRetailersImpl> availableLinks) {
    TreeMap<Integer, String> locations = new TreeMap<Integer, String>();
    int intCount = 0;
    for (ActivityFacility af : this.retailerFacilities.values()) {
      locations.put(
          Integer.valueOf(intCount),
          NetworkUtils.getNearestLink(
                  ((NetworkImpl) this.controler.getScenario().getNetwork()), af.getCoord())
              .getId()
              .toString());
      ++intCount;
      log.info(
          "The facility with Id: "
              + af.getId()
              + " has been added, this is located on the link: "
              + af.getLinkId());
    }
    for (LinkRetailersImpl l : availableLinks.values()) {
      if (locations.containsValue(l.getId().toString())) {
        log.info("The Link: " + l.getId() + " is already on the list");
      } else {
        locations.put(Integer.valueOf(intCount), l.getId().toString());
        ++intCount;
        log.info("The Link: " + l.getId() + " has been added");
      }
    }

    log.info("Initial Locations (with Free Links) = " + locations);
    return locations;
  }
 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;
 }
Example #11
0
  @Override
  public void run() {
    if (scenario instanceof MutableScenario) {
      ((MutableScenario) scenario).setLocked();
      // see comment in ScenarioImpl. kai, sep'14
    }

    /*
     * Create single-mode network here and hand it over to PersonPrepareForSim. Otherwise, each instance would create its
     * own single-mode network. However, this assumes that the main mode is car - which PersonPrepareForSim also does. Should
     * be probably adapted in a way that other main modes are possible as well. cdobler, oct'15.
     */
    final Network net;
    if (NetworkUtils.isMultimodal(network)) {
      log.info(
          "Network seems to be multimodal. Create car-only network which is handed over to PersonPrepareForSim.");
      TransportModeNetworkFilter filter = new TransportModeNetworkFilter(network);
      net = NetworkUtils.createNetwork();
      HashSet<String> modes = new HashSet<>();
      modes.add(TransportMode.car);
      filter.filter(net, modes);
    } else {
      net = network;
    }

    // make sure all routes are calculated.
    ParallelPersonAlgorithmRunner.run(
        population,
        globalConfigGroup.getNumberOfThreads(),
        new ParallelPersonAlgorithmRunner.PersonAlgorithmProvider() {
          @Override
          public AbstractPersonAlgorithm getPersonAlgorithm() {
            return new MyPersonPrepareForSim(
                new PlanRouter(tripRouterProvider.get(), activityFacilities), scenario, net);
          }
        });
    if (population instanceof Lockable) {
      ((Lockable) population).setLocked();
    }
  }
  private TransitRoute createRoute(
      Id<TransitRoute> routeID, TransitStopFacility startStop, TransitStopFacility endStop) {

    FreespeedTravelTimeAndDisutility tC = new FreespeedTravelTimeAndDisutility(-6.0, 0.0, 0.0);
    LeastCostPathCalculator routingAlgo = new Dijkstra(this.net, tC, tC);

    Node startNode = this.net.getLinks().get(startStop.getLinkId()).getToNode();
    Node endNode = this.net.getLinks().get(endStop.getLinkId()).getFromNode();

    int startTime = 0 * 3600;

    // get Route
    Path path = routingAlgo.calcLeastCostPath(startNode, endNode, startTime, null, null);
    NetworkRoute route = new LinkNetworkRouteImpl(startStop.getLinkId(), endStop.getLinkId());
    route.setLinkIds(
        startStop.getLinkId(), NetworkUtils.getLinkIds(path.links), endStop.getLinkId());

    // get stops at Route
    List<TransitRouteStop> stops = new LinkedList<TransitRouteStop>();

    // first stop
    TransitRouteStop routeStop =
        this.tS.getFactory().createTransitRouteStop(startStop, startTime, startTime);
    stops.add(routeStop);

    // additional stops
    for (Link link : path.links) {
      startTime += link.getLength() / link.getFreespeed();
      if (this.tS.getFacilities().get(link.getId()) == null) {
        continue;
      }
      routeStop =
          this.tS
              .getFactory()
              .createTransitRouteStop(
                  this.tS.getFacilities().get(link.getId()), startTime, startTime);
      stops.add(routeStop);
    }

    // last stop
    startTime +=
        this.net.getLinks().get(endStop.getLinkId()).getLength()
            / this.net.getLinks().get(endStop.getLinkId()).getFreespeed();
    routeStop = this.tS.getFactory().createTransitRouteStop(endStop, startTime, startTime);
    stops.add(routeStop);

    // register departure
    TransitRoute transitRoute =
        this.tS.getFactory().createTransitRoute(routeID, route, stops, "pt");

    return transitRoute;
  }
 @Override
 public void notifyIterationStarts(IterationStartsEvent event) {
   List<NetworkChangeEvent> allchangeevents = new ArrayList<NetworkChangeEvent>();
   Iterator<GenericP0ControlHandler> hiter = handlers.iterator();
   while (hiter.hasNext()) {
     GenericP0ControlHandler handler = hiter.next();
     handler.setIteration(
         event.getIteration()); // To run without P0 call with 0, and comment out initialisation of
     // events in initialise function
     allchangeevents.addAll(handler.getChangeEvents());
     handler.initialise();
   }
   final List<NetworkChangeEvent> events = allchangeevents;
   NetworkUtils.setNetworkChangeEvents(network, events);
   allchangeevents.removeAll(allchangeevents);
 }
  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()));
  }
Example #15
0
  /** @param args */
  public static void main(String[] args) {
    Network network = NetworkUtils.createNetwork();
    new MatsimNetworkReader(network)
        .readFile(
            "../../../shared-svn/studies/jbischoff/multimodal/berlin/input/10pct/network.final10pct.xml.gz");
    NetworkFilterManager m = new NetworkFilterManager(network);
    m.addLinkFilter(
        new NetworkLinkFilter() {

          @Override
          public boolean judgeLink(Link l) {
            if (l.getAllowedModes().contains(TransportMode.car)) return true;
            else return false;
          }
        });
    Network network2 = m.applyFilters();
    new NetworkWriter(network2)
        .write(
            "../../../shared-svn/studies/jbischoff/multimodal/berlin/input/10pct/network.final10pct_car.xml.gz");
  }
Example #16
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;
  }
Example #17
0
  public static final QuadTree<PersonPrimaryActivity> createPersonPrimaryActivityQuadTree(
      Controler controler) {
    int i;
    double minx = (1.0D / 0.0D);
    double miny = (1.0D / 0.0D);
    double maxx = (-1.0D / 0.0D);
    double maxy = (-1.0D / 0.0D);

    for (ActivityFacility f :
        controler.getScenario().getActivityFacilities().getFacilities().values()) {
      if (f.getCoord().getX() < minx) minx = f.getCoord().getX();
      if (f.getCoord().getY() < miny) miny = f.getCoord().getY();
      if (f.getCoord().getX() > maxx) maxx = f.getCoord().getX();
      if (f.getCoord().getY() <= maxy) continue;
      maxy = f.getCoord().getY();
    }
    minx -= 1.0D;
    miny -= 1.0D;
    maxx += 1.0D;
    maxy += 1.0D;
    QuadTree<PersonPrimaryActivity> personPrimaryActivityQuadTree =
        new QuadTree<PersonPrimaryActivity>(minx, miny, maxx, maxy);
    i = 0;
    for (Person p : controler.getScenario().getPopulation().getPersons().values()) {
      int primaryActivityCount = 0;
      boolean hasHome = false;
      boolean hasWork = false;
      boolean hasEducation = false;
      // boolean hasShop = false;

      if (p.getSelectedPlan().getPlanElements().toString().contains("type=shopgrocery")) {
        for (PlanElement pe : p.getSelectedPlan().getPlanElements()) {
          if (pe instanceof Activity) {
            Coord c;
            Id<Link> activityLink;
            int ppaId;
            PersonPrimaryActivity ppa;
            Activity act = (Activity) pe;

            if (act.getType().equals("home")) {
              if (!(hasHome)) {
                c =
                    ((ActivityFacility)
                            controler
                                .getScenario()
                                .getActivityFacilities()
                                .getFacilities()
                                .get(act.getFacilityId()))
                        .getCoord();
                activityLink =
                    (NetworkUtils.getNearestLink(
                            ((NetworkImpl) controler.getScenario().getNetwork()), act.getCoord()))
                        .getId();
                // activityLink =
                // (IdImpl)((ActivityFacility)controler.getFacilities().getFacilities().get(act.getFacilityId())).getLinkId();
                ppaId = Integer.parseInt(p.getId().toString()) * 10 + primaryActivityCount;
                ppa = new PersonPrimaryActivity(act.getType(), ppaId, p.getId(), activityLink);
                personPrimaryActivityQuadTree.put(c.getX(), c.getY(), ppa);

                hasHome = true;
                ++primaryActivityCount;
              }
            } else if (act.getType().equals("work")) {
              if (!(hasWork)) {
                c =
                    ((ActivityFacility)
                            controler
                                .getScenario()
                                .getActivityFacilities()
                                .getFacilities()
                                .get(act.getFacilityId()))
                        .getCoord();
                activityLink =
                    ((ActivityFacility)
                            controler
                                .getScenario()
                                .getActivityFacilities()
                                .getFacilities()
                                .get(act.getFacilityId()))
                        .getLinkId();
                ppaId = Integer.parseInt(p.getId().toString()) * 10 + primaryActivityCount;
                ppa = new PersonPrimaryActivity(act.getType(), ppaId, p.getId(), activityLink);
                personPrimaryActivityQuadTree.put(c.getX(), c.getY(), ppa);

                hasWork = true;
                ++primaryActivityCount;
              }
            } else {
              if ((!(act.getType().equals("education"))) || (hasEducation)) continue;
              c =
                  ((ActivityFacility)
                          controler
                              .getScenario()
                              .getActivityFacilities()
                              .getFacilities()
                              .get(act.getFacilityId()))
                      .getCoord();
              activityLink =
                  ((ActivityFacility)
                          controler
                              .getScenario()
                              .getActivityFacilities()
                              .getFacilities()
                              .get(act.getFacilityId()))
                      .getLinkId();
              log.info("Act Link " + activityLink);
              ppaId = Integer.parseInt(p.getId().toString()) * 10 + primaryActivityCount;
              ppa = new PersonPrimaryActivity(act.getType(), ppaId, p.getId(), activityLink);
              personPrimaryActivityQuadTree.put(c.getX(), c.getY(), ppa);

              hasEducation = true;
              ++primaryActivityCount;
            }
          }
        }

        i += primaryActivityCount;
      }

      // log.info("Global Primary activity count = " + i);
    }

    return personPrimaryActivityQuadTree;
  }
  private void createLink(
      final Network network,
      final OsmWay way,
      final OsmNode fromNode,
      final OsmNode toNode,
      final double length) {
    double nofLanes;
    double laneCapacity;
    double freespeed;
    double freespeedFactor;
    boolean oneway;
    boolean onewayReverse = false;

    // load defaults
    String highway = way.tags.get(TAG_HIGHWAY);
    String railway = way.tags.get(TAG_RAILWAY);
    String ptway = way.tags.get(TAG_PT_WAYS);
    OsmHighwayDefaults defaults;
    if (highway != null) {
      defaults = this.highwayDefaults.get(highway);
      if (defaults == null) {
        this.unknownHighways.add(highway);
        return;
      }
    } else if (railway != null) {
      defaults = this.railwayDefaults.get(railway);
      if (defaults == null) {
        this.unknownRailways.add(railway);
        return;
      }
    } else if (ptway != null) {
      defaults = this.ptDefaults.get(ptway);
      if (defaults == null) {
        this.unknownPTs.add(ptway);
        return;
      }
    } else {
      this.unknownWays.add(way.tags.values().toString());
      return;
    }
    nofLanes = defaults.lanes;
    laneCapacity = defaults.laneCapacity;
    freespeed = defaults.freespeed;
    freespeedFactor = defaults.freespeedFactor;
    oneway = defaults.oneway;

    // check if there are tags that overwrite defaults
    // - check tag "junction"
    if ("roundabout".equals(way.tags.get(TAG_JUNCTION))) {
      // if "junction" is not set in tags, get() returns null and equals() evaluates to false
      oneway = true;
    }
    // - check tag "oneway"
    String onewayTag = way.tags.get(TAG_ONEWAY);
    if (onewayTag != null) {
      if ("yes".equals(onewayTag)) {
        oneway = true;
      } else if ("true".equals(onewayTag)) {
        oneway = true;
      } else if ("1".equals(onewayTag)) {
        oneway = true;
      } else if ("-1".equals(onewayTag)) {
        onewayReverse = true;
        oneway = false;
      } else if ("no".equals(onewayTag)) {
        oneway = false; // may be used to overwrite defaults
      }
    }
    // - check tag "oneway" with trunks, primary and secondary roads
    // 		(if they are marked as such, the default number of lanes should be two instead of one)
    if (highway != null) {
      if (highway.equalsIgnoreCase("trunk")
          || highway.equalsIgnoreCase("primary")
          || highway.equalsIgnoreCase("secondary")) {
        if (oneway && nofLanes == 1.0) {
          nofLanes = 2.0;
        }
      }
    }
    // - ckeck tag "maxspeed"
    String maxspeedTag = way.tags.get(TAG_MAXSPEED);
    if (maxspeedTag != null) {
      try {
        freespeed = Double.parseDouble(maxspeedTag) / 3.6; // convert km/h to m/s
      } catch (NumberFormatException e) {
        if (!this.unknownMaxspeedTags.contains(maxspeedTag)) {
          this.unknownMaxspeedTags.add(maxspeedTag);
          log.warn("Could not parse maxspeed tag:" + e.getMessage() + ". Ignoring it.");
        }
      }
    }
    // - check tag "lanes"
    String lanesTag = way.tags.get(TAG_LANES);
    if (lanesTag != null) {
      try {
        double tmp = Double.parseDouble(lanesTag);
        if (tmp > 0) {
          nofLanes = tmp;
        }
      } catch (Exception e) {
        if (!this.unknownLanesTags.contains(lanesTag)) {
          this.unknownLanesTags.add(lanesTag);
          log.warn("Could not parse lanes tag:" + e.getMessage() + ". Ignoring it.");
        }
      }
    }

    // define the links' capacity and freespeed
    double capacity = nofLanes * laneCapacity;
    if (this.scaleMaxSpeed) {
      freespeed = freespeed * freespeedFactor;
    }

    // define modes allowed on link(s)
    //	basic type:
    Set<String> modes = new HashSet<String>();
    if (highway != null) {
      modes.add("car");
    }
    if (railway != null) {
      modes.add(railway);
    }
    if (ptway != null) {
      modes.add(ptway);
    }
    if (modes.isEmpty()) {
      modes.add("unknownStreetType");
    }
    //	public transport:
    for (OsmRelation relation : this.relations.values()) {
      for (OsmParser.OsmRelationMember member : relation.members) {
        if ((member.type == OsmParser.OsmRelationMemberType.WAY) && (member.refId == way.id)) {
          String mode = relation.tags.get("name");
          // mark that it is a link used by any pt:
          if (mode == null) {
            break;
          } else {
            modes.add("pt");
          }
          if (mode.indexOf(":") > 0
              && mode.indexOf(" ") > 0
              && mode.indexOf(" ") < mode.indexOf(":")) {
            modes.add(mode.toLowerCase().substring(mode.indexOf(" "), mode.indexOf(":")).trim());
          }
          // modes.add(relation.tags.get("name"));
          break;
        }
      }
    }

    // only create link, if both nodes were found, node could be null, since nodes outside a layer
    // were dropped
    Id<Node> fromId = Id.create(fromNode.id, Node.class);
    Id<Node> toId = Id.create(toNode.id, Node.class);
    if (network.getNodes().get(fromId) != null && network.getNodes().get(toId) != null) {
      String origId = Long.toString(way.id);

      if (!onewayReverse) {
        Link l =
            network
                .getFactory()
                .createLink(
                    Id.create(this.id, Link.class),
                    network.getNodes().get(fromId),
                    network.getNodes().get(toId));
        l.setLength(length);
        l.setFreespeed(freespeed);
        l.setCapacity(capacity);
        l.setNumberOfLanes(nofLanes);
        l.setAllowedModes(modes);
        if (l instanceof Link) {
          final String id1 = origId;
          NetworkUtils.setOrigId(((Link) l), id1);
        }
        network.addLink(l);
        this.id++;
      }
      if (!oneway) {
        Link l =
            network
                .getFactory()
                .createLink(
                    Id.create(this.id, Link.class),
                    network.getNodes().get(toId),
                    network.getNodes().get(fromId));
        l.setLength(length);
        l.setFreespeed(freespeed);
        l.setCapacity(capacity);
        l.setNumberOfLanes(nofLanes);
        l.setAllowedModes(modes);
        if (l instanceof Link) {
          final String id1 = origId;
          NetworkUtils.setOrigId(((Link) l), id1);
        }
        network.addLink(l);
        this.id++;
      }
    }
  }
  /* (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);
        }
      }
    }
  }
  public static void main(String[] args) {
    Scenario scenario;
    scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new NetworkReaderMatsimV2(scenario.getNetwork()).readFile(args[0]);
    Network network = scenario.getNetwork();
    Network net = NetworkUtils.createNetwork();
    Set<String> modes = new HashSet<>();
    modes.add(TransportMode.car);
    new TransportModeNetworkFilter(network).filter(net, modes);
    new NetworkCleaner().run(net);
    MatsimRandom.reset(123);
    DrunkDudePathfinder stochasticRouter =
        new DrunkDudePathfinder(
            net,
            new TravelDisutility() {

              @Override
              public double getLinkTravelDisutility(
                  Link link, double time, Person person, Vehicle vehicle) {
                return link.getLength() / link.getFreespeed();
              }

              @Override
              public double getLinkMinimumTravelDisutility(Link link) {
                return link.getLength() / link.getFreespeed();
              }
            },
            new TravelTime() {

              @Override
              public double getLinkTravelTime(
                  Link link, double time, Person person, Vehicle vehicle) {
                return link.getLength() / link.getFreespeed();
              }
            },
            0.5);
    SimpleNetworkPainter networkPainter = new SimpleNetworkPainter(400, 400);
    networkPainter.setNetworkTransformation(network);
    stochasticRouter.setNetworkPainter(networkPainter);
    //        stochasticRouter.calcLeastCostPath(network.getNodes().get(Id.createNodeId("11_311")),
    //                network.getNodes().get(Id.createNodeId("18_566")), 3600, null, null);
    Set<Node> nodeSet = new HashSet<>();
    nodeSet.addAll(net.getNodes().values());
    Node[] nodesArray = nodeSet.toArray(new Node[nodeSet.size()]);

    long currentTimeMillis = -System.currentTimeMillis();
    for (int i = 0; i < 1e3; i++) {
      int[] ints = Sample.sampleMfromN(2, nodesArray.length);
      System.out.println(nodesArray[ints[0]] + " " + nodesArray[ints[1]]);
      stochasticRouter.calcLeastCostPath(
          nodesArray[ints[0]], nodesArray[ints[1]], 3600, null, null);
    }
    currentTimeMillis += System.currentTimeMillis();
    System.out.println(currentTimeMillis);

    Dijkstra dijkstra =
        new Dijkstra(
            net,
            new TravelDisutility() {

              @Override
              public double getLinkTravelDisutility(
                  Link link, double time, Person person, Vehicle vehicle) {
                return link.getLength() / link.getFreespeed();
              }

              @Override
              public double getLinkMinimumTravelDisutility(Link link) {
                return link.getLength() / link.getFreespeed();
              }
            },
            new TravelTime() {

              @Override
              public double getLinkTravelTime(
                  Link link, double time, Person person, Vehicle vehicle) {
                return link.getLength() / link.getFreespeed();
              }
            },
            null);
    currentTimeMillis = -System.currentTimeMillis();
    for (int i = 0; i < 1e3; i++) {
      int[] ints = Sample.sampleMfromN(2, nodesArray.length);
      dijkstra.calcLeastCostPath(nodesArray[ints[0]], nodesArray[ints[1]], 3600, null, null);
    }
    currentTimeMillis += System.currentTimeMillis();
    System.out.println(currentTimeMillis);
  }
  @Override
  public TripRouter instantiateAndConfigureTripRouter(RoutingContext routingContext) {

    TripRouter tripRouter = new TripRouter();

    PlansCalcRouteConfigGroup routeConfigGroup = scenario.getConfig().plansCalcRoute();

    LeastCostPathCalculator routeAlgo =
        leastCostPathCalculatorFactory.createPathCalculator(
            scenario.getNetwork(),
            routingContext.getTravelDisutility(),
            routingContext.getTravelTime());

    FreespeedTravelTimeAndDisutility ptTimeCostCalc =
        new FreespeedTravelTimeAndDisutility(-1.0, 0.0, 0.0);
    LeastCostPathCalculator routeAlgoPtFreeFlow =
        leastCostPathCalculatorFactory.createPathCalculator(
            scenario.getNetwork(), ptTimeCostCalc, ptTimeCostCalc);

    final boolean networkIsMultimodal = NetworkUtils.isMultimodal(scenario.getNetwork());
    if (networkIsMultimodal) {
      // note: LinkImpl has a default allowed mode of "car" so that all links
      // of a monomodal network are actually restricted to car, making the check
      // of multimodality unecessary from a behavioral point of view.
      // However, checking the mode restriction for each link is expensive,
      // so it is not worth doing it if it is not necessary. (td, oct. 2012)
      if (routeAlgo instanceof IntermodalLeastCostPathCalculator) {
        ((IntermodalLeastCostPathCalculator) routeAlgo)
            .setModeRestriction(Collections.singleton(TransportMode.car));
        ((IntermodalLeastCostPathCalculator) routeAlgoPtFreeFlow)
            .setModeRestriction(Collections.singleton(TransportMode.car));
      } else {
        // this is impossible to reach when using the algorithms of org.matsim.*
        // (all implement IntermodalLeastCostPathCalculator)
        log.warn(
            "network is multimodal but least cost path algorithm is not an instance of IntermodalLeastCostPathCalculator!");
      }
    }

    for (String mode : routeConfigGroup.getTeleportedModeFreespeedFactors().keySet()) {
      final RoutingModule routingModule =
          DefaultRoutingModules.createPseudoTransitRouter(
              mode,
              scenario.getPopulation().getFactory(),
              scenario.getNetwork(),
              routeAlgoPtFreeFlow,
              routeConfigGroup.getModeRoutingParams().get(mode));
      tripRouter.setRoutingModule(mode, routingModule);
    }

    for (String mode : routeConfigGroup.getTeleportedModeSpeeds().keySet()) {
      final RoutingModule routingModule =
          DefaultRoutingModules.createTeleportationRouter(
              mode,
              scenario.getPopulation().getFactory(),
              routeConfigGroup.getModeRoutingParams().get(mode));
      final RoutingModule result = tripRouter.setRoutingModule(mode, routingModule);

      if (result != null) {
        log.error("inconsistent router configuration for mode " + mode);
        log.error(
            "One situation which triggers this warning: setting both speed and speedFactor for a mode (this used to be possible).");
        throw new RuntimeException(
            "there was already a module set when trying to set teleporting module for mode "
                + mode
                + ": "
                + result);
      }
    }

    for (String mode : routeConfigGroup.getNetworkModes()) {
      final RoutingModule routingModule =
          DefaultRoutingModules.createNetworkRouter(
              mode, scenario.getPopulation().getFactory(), scenario.getNetwork(), routeAlgo);
      final RoutingModule result = tripRouter.setRoutingModule(mode, routingModule);

      if (result != null) {
        log.error("inconsistent router configuration for mode " + mode);
        throw new RuntimeException(
            "there was already a module set when trying to set network routing module for mode "
                + mode
                + ": "
                + result);
      }

      // The default router will always route on the car network.  A user may, however, have
      // prepared a network with dedicated bicycle
      // links and then expect the router to route on that.  The following test tries to catch that.
      //  If someone improves on this,
      // the test can be removed.  kai, feb'15
      if (networkIsMultimodal) {
        switch (mode) {
          case TransportMode.car:
          case TransportMode.ride:
            break;
          default:
            throw new RuntimeException(
                "you have a multi-modal network and configured "
                    + mode
                    + " to be routed as a network mode.  "
                    + "The present configuration will route this "
                    + "mode on the car network.  This may be ok (e.g. with ``truck'' or ``motorbike''), or not (e.g. with ``bicycle''). "
                    + "Throwing an exception anyways; please use a uni-modal network if you want to keep this configuration.");
        }
      }
    }

    if (scenario.getConfig().transit().isUseTransit()) {
      TransitRouterWrapper routingModule =
          new TransitRouterWrapper(
              transitRouterFactory.get(),
              scenario.getTransitSchedule(),
              scenario.getNetwork(), // use a walk router in case no PT path is found
              DefaultRoutingModules.createTeleportationRouter(
                  TransportMode.transit_walk,
                  scenario.getPopulation().getFactory(),
                  routeConfigGroup.getModeRoutingParams().get(TransportMode.walk)));
      for (String mode : scenario.getConfig().transit().getTransitModes()) {
        // XXX one can't check for inconsistent setting here...
        // because the setting is inconsistent by default (defaults
        // set a teleportation setting for pt routing, which is overriden
        // here) (td, may 2013)
        tripRouter.setRoutingModule(mode, routingModule);
      }
    }
    return tripRouter;
  }