Exemplo n.º 1
0
  public void convertTransitSchedule(String file) {

    Config config = ConfigUtils.createConfig();
    config.scenario().setUseTransit(true);
    config.scenario().setUseVehicles(true);
    Scenario scenario = ScenarioUtils.createScenario(config);

    TransitScheduleReader ts = new TransitScheduleReader(scenario);
    ts.readFile(file);

    PointFeatureFactory.Builder builder = new PointFeatureFactory.Builder();
    builder.setName("nodes");
    builder.addAttribute("id", String.class);
    PointFeatureFactory factory = builder.create();

    List<SimpleFeature> features = new ArrayList<SimpleFeature>();

    for (TransitStopFacility stop : scenario.getTransitSchedule().getFacilities().values()) {
      features.add(factory.createPoint(MGC.coord2Coordinate(stop.getCoord())));
    }

    ShapeFileWriter.writeGeometries(
        features,
        "C:/Users/Daniel/Documents/work/shared-svn/studies/countries/cl/Kai_und_Daniel/Visualisierungen/stops.shp");
  }
  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;
  }
Exemplo n.º 3
0
 ArtificiallyConnectedStopFacility(TransitStopFacility facility) {
   myNode =
       networkFactory.createNode(
           Id.create(prefix + facility.getId(), Node.class), facility.getCoord());
   myLink = getNewLink(myNode, myNode);
   facility.setLinkId(myLink.getId());
 }
Exemplo n.º 4
0
 private ArtificiallyConnectedStopFacility getArtificiallyConnectedStopFacility(
     TransitStopFacility facility) {
   if (!artificiallyConnectedStopFacilities.containsKey(facility.getId())) {
     artificiallyConnectedStopFacilities.put(
         facility.getId(), new ArtificiallyConnectedStopFacility(facility));
   }
   return artificiallyConnectedStopFacilities.get(facility.getId());
 }
Exemplo n.º 5
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;
   }
 }
 private TransitStopFacility findStopWithLargestDistance(ArrayList<TransitStopFacility> stops) {
   Coord startCoord = stops.get(0).getCoord();
   double largestDistance = 0;
   TransitStopFacility stopWithLargestDistance = stops.get(0);
   for (TransitStopFacility transitStopFacility : stops) {
     double currentDistance = CoordUtils.calcDistance(startCoord, transitStopFacility.getCoord());
     if (currentDistance > largestDistance) {
       largestDistance = currentDistance;
       stopWithLargestDistance = transitStopFacility;
     }
   }
   return stopWithLargestDistance;
 }
Exemplo n.º 7
0
  /**
   * Adding TransportMode.pt flags to all links referred by transit schedule
   *
   * @param transitSchedule The transit schedule.
   * @param network The network to be tagged.
   * @return
   */
  public static Network tagTransitLinksInNetwork(TransitSchedule transitSchedule, Network network) {

    log.info("Tagging pt network links");

    if (transitSchedule == null) {
      log.info("No transit schedule given. Returning unmodified network...");
      return network;
    }

    for (TransitStopFacility stopFacitlity : transitSchedule.getFacilities().values()) {
      Set<String> allowedModes =
          new TreeSet<String>(network.getLinks().get(stopFacitlity.getLinkId()).getAllowedModes());
      allowedModes.add(TransportMode.pt);
      network.getLinks().get(stopFacitlity.getLinkId()).setAllowedModes(allowedModes);
    }

    for (TransitLine transitLine : transitSchedule.getTransitLines().values()) {
      for (TransitRoute transitRoute : transitLine.getRoutes().values()) {
        NetworkRoute route = transitRoute.getRoute();

        Set<String> allowedModes;

        allowedModes =
            new TreeSet<String>(network.getLinks().get(route.getStartLinkId()).getAllowedModes());
        allowedModes.add(TransportMode.pt);
        network.getLinks().get(route.getStartLinkId()).setAllowedModes(allowedModes);

        for (Id linkId : route.getLinkIds()) {
          allowedModes = new TreeSet<String>(network.getLinks().get(linkId).getAllowedModes());
          allowedModes.add(TransportMode.pt);
          network.getLinks().get(linkId).setAllowedModes(allowedModes);
        }

        allowedModes =
            new TreeSet<String>(network.getLinks().get(route.getEndLinkId()).getAllowedModes());
        allowedModes.add(TransportMode.pt);
        network.getLinks().get(route.getEndLinkId()).setAllowedModes(allowedModes);
      }
    }

    int taggedLinks = 0;
    for (Link link : network.getLinks().values()) {
      if (link.getAllowedModes().contains(TransportMode.pt)) {
        taggedLinks++;
      }
    }

    log.info("Finished - " + taggedLinks + " links were tagged");

    return network;
  }
  private List<Geometry> createGeometryFromStops(
      ArrayList<TransitStopFacility> stops, TransitStopFacility remoteStop) {
    List<Geometry> geometries = new LinkedList<Geometry>();

    ArrayList<Coordinate> coords = new ArrayList<Coordinate>();
    for (TransitStopFacility stop : stops) {
      if (stop.equals(remoteStop)) {
        // terminate current line string
        coords.add(new Coordinate(stop.getCoord().getX(), stop.getCoord().getY(), 0.0));
        Coordinate[] coordinates = coords.toArray(new Coordinate[coords.size()]);
        Geometry lineString = new GeometryFactory().createLineString(coordinates);
        geometries.add(lineString);
        // create new line string
        coords = new ArrayList<Coordinate>();
        coords.add(new Coordinate(stop.getCoord().getX(), stop.getCoord().getY(), 0.0));
      } else {
        coords.add(new Coordinate(stop.getCoord().getX(), stop.getCoord().getY(), 0.0));
      }
    }
    // add first stop to close the circle
    coords.add(new Coordinate(stops.get(0).getCoord().getX(), stops.get(0).getCoord().getY(), 0.0));

    Coordinate[] coordinates = coords.toArray(new Coordinate[coords.size()]);
    Geometry lineString = new GeometryFactory().createLineString(coordinates);
    geometries.add(lineString);
    return geometries;
  }
  private TransitStopFacility drawRandomStop(
      Geometry buffer, PRouteProvider pRouteProvider, Set<Id> stopsUsed) {
    List<TransitStopFacility> choiceSet = new LinkedList<TransitStopFacility>();

    // find choice-set
    for (TransitStopFacility stop : pRouteProvider.getAllPStops()) {
      if (!stopsUsed.contains(stop.getId())) {
        if (buffer.contains(MGC.coord2Point(stop.getCoord()))) {
          choiceSet.add(stop);
        }
      }
    }

    return pRouteProvider.drawRandomStopFromList(choiceSet);
  }
Exemplo n.º 10
0
 void createAgentGroupNearTransitstrops(
     Scenario scenario, double distance, String transitScheduleFile) {
   new TransitScheduleReader(scenario).readFile(transitScheduleFile);
   for (Person p : scenario.getPopulation().getPersons().values()) {
     if (scenario
             .getPopulation()
             .getPersonAttributes()
             .getAttribute(p.getId().toString(), "subpopulation")
         != null) {
       return;
     }
     ArrayList<Boolean> isIt = new ArrayList<>();
     for (Plan plan : p.getPlans()) {
       for (PlanElement pe : plan.getPlanElements()) {
         if (pe instanceof Activity) {
           boolean setAct = false;
           Coord ac = ((Activity) pe).getCoord();
           for (TransitStopFacility stop :
               scenario.getTransitSchedule().getFacilities().values()) {
             double dist = CoordUtils.calcDistance(stop.getCoord(), ac);
             if (dist <= distance) {
               setAct = true;
               break;
             }
           }
           isIt.add(setAct);
         }
       }
     }
     boolean truth = true;
     for (Boolean t : isIt) {
       if (!t) truth = false;
     }
     if (truth) {
       scenario
           .getPopulation()
           .getPersonAttributes()
           .putAttribute(p.getId().toString(), "subpopulation", "schedulePt");
     } else {
       scenario
           .getPopulation()
           .getPersonAttributes()
           .putAttribute(p.getId().toString(), "subpopulation", "teleportPt");
       this.teleportPtUsers.add(p.getId());
     }
   }
 }
Exemplo n.º 11
0
  /**
   * Link the pt-stations in the schedule to the closest network links. Thereby modifies
   * this.schedule.
   */
  protected void linkStationsToNetwork() {
    log.info("Linking pt stations to network...");

    Counter counter = new Counter("route # ");
    Set<TransitStopFacility> newFacilities = new HashSet<>();
    for (TransitStopFacility facility : this.schedule.getFacilities().values()) {

      final Id<Link> closestLink = findClosestLink(facility);
      if (closestLink != null) {
        //	link stop-facilities to the respective links.
        List<Id<TransitStopFacility>> localLinkedFacilities = new ArrayList<>();
        facility.setLinkId(closestLink);
        localLinkedFacilities.add(facility.getId());

        //	if street-link has opposite direction or if we searched for all links in area, then split
        // stop-position before linking.
        final List<Id<Link>> oppositeDirectionLinks = getOppositeDirection(closestLink);
        if (oppositeDirectionLinks != null && !oppositeDirectionLinks.isEmpty()) {
          TransitStopFacility[] newStopFacilities =
              multiplyStop(facility, oppositeDirectionLinks.size());
          for (int i = 0; i < oppositeDirectionLinks.size(); i++) {
            newStopFacilities[i + 1].setLinkId(oppositeDirectionLinks.get(i));
            localLinkedFacilities.add(newStopFacilities[i + 1].getId());
            newFacilities.add(newStopFacilities[i + 1]);
          }
        }

        linkedStopFacilitiesTree.put(facility.getId(), localLinkedFacilities);
      }

      counter.incCounter();
    }
    for (TransitStopFacility facility : newFacilities) {
      this.schedule.addStopFacility(facility);
    }
    counter.printCounter();

    log.info("Linking pt stations to network... done.");

    for (List<Id<TransitStopFacility>> facilityList : linkedStopFacilitiesTree.values()) {
      for (Id<TransitStopFacility> facilityId : facilityList) {
        linkedStopFacilities.add(facilityId);
      }
    }
  }
Exemplo n.º 12
0
 @Override
 public String toString() {
   return "Id "
       + transitStopFacility.getId()
       + ", "
       + numberOfTransfers
       + " transfers from "
       + indexOfFirstTransfer;
 }
  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;
  }
Exemplo n.º 14
0
  private LeastCostPathCalculator.Path getShortestPath(Node startNode, TransitRouteStop toStop) {
    LeastCostPathCalculator.Path shortestPath = null;

    for (Id<TransitStopFacility> toStopFacilityId :
        linkedStopFacilitiesTree.get(toStop.getStopFacility().getId())) {
      TransitStopFacility facility = this.schedule.getFacilities().get(toStopFacilityId);
      Id<Link> linkId = facility.getLinkId();
      Link link = this.network.getLinks().get(linkId);
      Node endNode = link.getFromNode();
      LeastCostPathCalculator.Path tempShortestPath =
          this.router.calcLeastCostPath(startNode, endNode, "", "");
      if (tempShortestPath != null
          && (shortestPath == null || (tempShortestPath.travelCost < shortestPath.travelCost))) {
        shortestPath = tempShortestPath;
        toStop.setStopFacility(this.schedule.getFacilities().get(toStopFacilityId));
      }
    }

    return shortestPath;
  }
  @Override
  public PPlan run(Cooperative cooperative) {

    PPlan oldPlan = cooperative.getBestPlan();
    ArrayList<TransitStopFacility> currentStopsToBeServed = oldPlan.getStopsToBeServed();

    TransitStopFacility baseStop = currentStopsToBeServed.get(0);
    TransitStopFacility remoteStop = this.findStopWithLargestDistance(currentStopsToBeServed);
    double bufferSizeBasedOnRatio =
        CoordUtils.calcDistance(baseStop.getCoord(), remoteStop.getCoord()) * this.ratio;

    List<Geometry> lineStrings = this.createGeometryFromStops(currentStopsToBeServed, remoteStop);
    Geometry buffer =
        this.createBuffer(
            lineStrings, Math.max(this.bufferSize, bufferSizeBasedOnRatio), this.excludeTermini);

    Set<Id> stopsUsed = this.getStopsUsed(oldPlan.getLine().getRoutes().values());
    TransitStopFacility newStop =
        this.drawRandomStop(buffer, cooperative.getRouteProvider(), stopsUsed);

    if (newStop == null) {
      return null;
    }

    ArrayList<TransitStopFacility> newStopsToBeServed =
        this.addStopToExistingStops(baseStop, remoteStop, currentStopsToBeServed, newStop);

    // create new plan
    PPlan newPlan = new PPlan(cooperative.getNewRouteId(), this.getName());
    newPlan.setNVehicles(1);
    newPlan.setStartTime(oldPlan.getStartTime());
    newPlan.setEndTime(oldPlan.getEndTime());
    newPlan.setStopsToBeServed(newStopsToBeServed);

    newPlan.setLine(cooperative.getRouteProvider().createTransitLine(cooperative.getId(), newPlan));

    return newPlan;
  }
  private void addNewStopBetweenTwoNearestExistingStop(
      ArrayList<TransitStopFacility> stops, TransitStopFacility stop) {
    // find nearest stop
    double smallestDistance = Double.MAX_VALUE;
    TransitStopFacility stopWithSmallestDistance = stops.get(0);
    TransitStopFacility stopWithSecondSmallestDistance = stops.get(0);
    for (TransitStopFacility transitStopFacility : stops) {
      double currentDistance =
          CoordUtils.calcDistance(stop.getCoord(), transitStopFacility.getCoord());
      if (currentDistance < smallestDistance) {
        smallestDistance = currentDistance;
        stopWithSecondSmallestDistance = stopWithSmallestDistance;
        stopWithSmallestDistance = transitStopFacility;
      }
    }

    // find index to insert
    int index =
        Math.min(
            stops.indexOf(stopWithSecondSmallestDistance), stops.indexOf(stopWithSmallestDistance));

    // insert
    stops.add(index + 1, stop);
  }
Exemplo n.º 17
0
  public static TransitSchedule removeStopsNotUsed(TransitSchedule transitSchedule) {

    log.info("Removing stops not used");
    TransitSchedule tS = TransitScheduleCleaner.makeTransitScheduleModifiable(transitSchedule);
    printStatistic(tS);

    Set<Id> stopsInUse = new TreeSet<Id>();
    Set<Id> stopsToBeRemoved = new TreeSet<Id>();

    for (TransitLine transitLine : tS.getTransitLines().values()) {
      for (TransitRoute transitRoute : transitLine.getRoutes().values()) {
        for (TransitRouteStop stop : transitRoute.getStops()) {
          stopsInUse.add(stop.getStopFacility().getId());
        }
      }
    }

    for (TransitStopFacility transitStopFacility : tS.getFacilities().values()) {
      if (!stopsInUse.contains(transitStopFacility.getId())) {
        stopsToBeRemoved.add(transitStopFacility.getId());
      }
    }

    StringBuffer sB = new StringBuffer();

    for (Id transitStopFacilityId : stopsToBeRemoved) {
      tS.getFacilities().remove(transitStopFacilityId);
      sB.append(transitStopFacilityId.toString() + ", ");
    }

    printStatistic(tS);
    log.info(
        "Removed " + stopsToBeRemoved.size() + " stops from transitSchedule: " + sB.toString());

    return tS;
  }
  private final void convertStations(OTTDataContainer dataContainer, Network infraNetwork) {
    TransitScheduleFactory factory = scenario.getTransitSchedule().getFactory();

    // get station ids
    Set<Id> stationIds = new HashSet<Id>();
    for (Locomotive locomotive : dataContainer.locomotives.values()) {
      for (StationData stationData : locomotive.trips.values()) {
        stationIds.add(stationData.stationId);
      }
    }

    for (Id stationId : stationIds) {
      Node node = infraNetwork.getNodes().get(stationId);
      if (node != null) {
        TransitStopFacility stopFacility =
            factory.createTransitStopFacility(stationId, node.getCoord(), false);
        stopFacility.setName(node.getId().toString());
        scenario.getTransitSchedule().addStopFacility(stopFacility);
      } else {
        throw new RuntimeException(
            "node id=" + stationId.toString() + " not found in the network. Bailing out.");
      }
    }
  }
Exemplo n.º 19
0
 /**
  * Create and add to schedule new stops with the id-endings "_1" to "_numberOfCopies" by copying
  * the provided stopFacility.
  *
  * @param stopFacility which will be copied. The original becomes the first element of the
  *     returned array.
  * @param numberOfCopies of stopFacility which are created.
  * @return TransitStopFacilities stopFacility, and copies stop_1 to stop_numberOfCopies
  */
 private TransitStopFacility[] multiplyStop(TransitStopFacility stopFacility, int numberOfCopies) {
   TransitStopFacility[] facilities = new TransitStopFacility[numberOfCopies + 1];
   facilities[0] = stopFacility;
   for (int i = 1; i <= numberOfCopies; i++) {
     // Copy facility at stopFacility:
     Id<TransitStopFacility> idNewFacility =
         Id.create(stopFacility.getId().toString() + "_" + i, TransitStopFacility.class);
     TransitStopFacility newFacility =
         this.scheduleFactory.createTransitStopFacility(
             idNewFacility, stopFacility.getCoord(), stopFacility.getIsBlockingLane());
     newFacility.setName(stopFacility.getName());
     // Add new facility to schedule and to array:
     facilities[i] = newFacility;
   }
   return facilities;
 }
Exemplo n.º 20
0
  private CreateStopsForAllCarLinks(
      Network net, PConfigGroup pConfigGroup, TransitSchedule realTransitSchedule) {
    this.net = net;
    this.pConfigGroup = pConfigGroup;

    this.linkId2StopFacilityMap = new LinkedHashMap<>();

    Set<Id<TransitStopFacility>> stopsWithoutLinkIds = new TreeSet<>();

    if (realTransitSchedule != null) {
      for (TransitStopFacility stopFacility : realTransitSchedule.getFacilities().values()) {
        if (stopFacility.getLinkId() != null) {
          if (this.linkId2StopFacilityMap.get(stopFacility.getLinkId()) != null) {
            log.error(
                "There is more than one stop registered on link "
                    + stopFacility.getLinkId()
                    + ". "
                    + this.linkId2StopFacilityMap.get(stopFacility.getLinkId()).getId()
                    + " stays registered as paratransit stop. Will ignore stop "
                    + stopFacility.getId());
          } else {
            this.linkId2StopFacilityMap.put(stopFacility.getLinkId(), stopFacility);
          }
        } else {
          stopsWithoutLinkIds.add(stopFacility.getId());
        }
      }
    }

    if (stopsWithoutLinkIds.size() > 0) {
      log.warn(
          "There are "
              + stopsWithoutLinkIds.size()
              + " stop facilities without link id, namely: "
              + stopsWithoutLinkIds.toString());
    }
  }
Exemplo n.º 21
0
 private void setConnectedStopFacilitiesToIsBlocking() {
   Set<TransitStopFacility> facilitiesToExchange = new HashSet<>();
   for (TransitStopFacility oldFacility : this.schedule.getFacilities().values()) {
     if (this.network
         .getLinks()
         .get(oldFacility.getLinkId())
         .getAllowedModes()
         .contains(TransportMode.car)) {
       TransitStopFacility newFacility =
           this.scheduleFactory.createTransitStopFacility(
               oldFacility.getId(), oldFacility.getCoord(), true);
       newFacility.setName(oldFacility.getName());
       newFacility.setLinkId(oldFacility.getLinkId());
       newFacility.setStopPostAreaId(oldFacility.getStopPostAreaId());
       facilitiesToExchange.add(newFacility);
     }
   }
   for (TransitStopFacility facility : facilitiesToExchange) {
     TransitStopFacility facilityToRemove = this.schedule.getFacilities().get(facility.getId());
     this.schedule.removeStopFacility(facilityToRemove);
     this.schedule.addStopFacility(facility);
   }
 }
  public void testTransitRouteCopy() {
    Config config = super.loadConfig(null);
    config.scenario().setUseTransit(true);
    config.scenario().setUseVehicles(true);
    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(config);

    Id<Node> nodeId1 = Id.create("1", Node.class);
    Id<Node> nodeId2 = Id.create("2", Node.class);
    Id<Node> nodeId3 = Id.create("3", Node.class);
    Id<Link> linkId1 = Id.create("1", Link.class);
    Id<Link> linkId2 = Id.create("2", Link.class);

    // build network
    Network network = scenario.getNetwork();
    NetworkFactory nBuilder = network.getFactory();
    Node node1 = nBuilder.createNode(nodeId1, scenario.createCoord(0, 0));
    Node node2 = nBuilder.createNode(nodeId2, scenario.createCoord(1000, 0));
    Node node3 = nBuilder.createNode(nodeId3, scenario.createCoord(2000, 0));
    network.addNode(node1);
    network.addNode(node2);
    network.addNode(node3);
    Link link1 = nBuilder.createLink(linkId1, node1, node2);
    Link link2 = nBuilder.createLink(linkId2, node2, node3);
    network.addLink(link1);
    network.addLink(link2);

    // build schedule
    TransitSchedule schedule = scenario.getTransitSchedule();
    TransitScheduleFactory sBuilder = schedule.getFactory();

    TransitStopFacility stopF1 =
        sBuilder.createTransitStopFacility(
            Id.create("1", TransitStopFacility.class), scenario.createCoord(1000.0, 0), false);
    TransitStopFacility stopF2 =
        sBuilder.createTransitStopFacility(
            Id.create("2", TransitStopFacility.class), scenario.createCoord(2000.0, 0), false);
    stopF1.setLinkId(link1.getId());
    stopF2.setLinkId(link2.getId());
    schedule.addStopFacility(stopF1);
    schedule.addStopFacility(stopF2);

    TransitLine tLine1 = sBuilder.createTransitLine(Id.create("1", TransitLine.class));

    TransitRouteStop stop1 = sBuilder.createTransitRouteStop(stopF1, 0, 0);
    TransitRouteStop stop2 = sBuilder.createTransitRouteStop(stopF2, 100, 100);
    ArrayList<TransitRouteStop> stops = new ArrayList<TransitRouteStop>();
    stops.add(stop1);
    stops.add(stop2);

    NetworkRoute netRoute = new LinkNetworkRouteImpl(link1.getId(), link2.getId());
    netRoute.setLinkIds(link1.getId(), Collections.<Id<Link>>emptyList(), link2.getId());
    TransitRoute tRoute1 =
        sBuilder.createTransitRoute(Id.create("1", TransitRoute.class), netRoute, stops, "bus");

    tRoute1.addDeparture(sBuilder.createDeparture(Id.create("1", Departure.class), 7.0 * 3600));
    tLine1.addRoute(tRoute1);
    schedule.addTransitLine(tLine1);

    // build vehicles
    new CreateVehiclesForSchedule(schedule, scenario.getVehicles()).run();

    // build population
    Population population = scenario.getPopulation();
    PopulationFactory pBuilder = population.getFactory();
    Person person1 = pBuilder.createPerson(Id.create("1", Person.class));
    Plan plan = pBuilder.createPlan();
    Activity homeAct = pBuilder.createActivityFromLinkId("h", linkId1);
    homeAct.setEndTime(7.0 * 3600);
    plan.addActivity(homeAct);
    Leg leg = pBuilder.createLeg(TransportMode.pt);
    ExperimentalTransitRoute tRoute = new ExperimentalTransitRoute(stopF1, tLine1, tRoute1, stopF2);
    leg.setRoute(tRoute);
    plan.addLeg(leg);
    plan.addActivity(pBuilder.createActivityFromLinkId("w", linkId2));
    person1.addPlan(plan);
    population.addPerson(person1);

    // prepare config
    config.controler().setFirstIteration(0);
    config.controler().setLastIteration(1);

    ActivityParams params = new ActivityParams("h");
    params.setTypicalDuration(16.0 * 3600);
    config.planCalcScore().addActivityParams(params);
    params = new ActivityParams("w");
    params.setTypicalDuration(8.0 * 3600);
    config.planCalcScore().addActivityParams(params);

    StrategySettings tam = new StrategySettings(Id.create(1, StrategySettings.class));
    tam.setStrategyName("TimeAllocationMutator");
    tam.setWeight(1.0);
    config.strategy().addStrategySettings(tam);

    // run
    Controler controler = new Controler(scenario);
    controler.getConfig().controler().setWriteEventsInterval(0);
    controler.setCreateGraphs(false);
    controler.run();

    // checks
    assertEquals(1, population.getPersons().size());
    assertEquals(2, person1.getPlans().size());
    assertEquals(
        ExperimentalTransitRoute.class,
        ((Leg) person1.getPlans().get(0).getPlanElements().get(1)).getRoute().getClass());
    assertEquals(
        ExperimentalTransitRoute.class,
        ((Leg) person1.getPlans().get(1).getPlanElements().get(1)).getRoute().getClass());
  }
 @Override
 public boolean getExitAtStop(final TransitStopFacility stop) {
   ExperimentalTransitRoute route = (ExperimentalTransitRoute) getCurrentLeg().getRoute();
   return route.getEgressStopId().equals(stop.getId());
 }
 @Override
 public double getSimValue(TransitStopFacility link, int startTimeS, int endTimeS, TYPE type) {
   return this.getOccupancyVolumeForStopAndTime(link.getId(), startTimeS);
 }
Exemplo n.º 25
0
  @Override
  public PPlan run(Operator operator) {
    PPlan newPlan;

    int triesPerformed = 0;

    int maxNumberOfTries = 100;
    do {
      triesPerformed++;

      // get a valid start time
      double startTime =
          this.timeProvider.getRandomTimeInInterval(
              0 * 3600.0, 24 * 3600.0 - operator.getMinOperationTime());
      double endTime =
          this.timeProvider.getRandomTimeInInterval(
              startTime + operator.getMinOperationTime(), 24 * 3600.0);

      if (startTime == endTime) {
        endTime += this.timeSlotSize;
      }

      while (startTime + operator.getMinOperationTime() > endTime) {
        endTime += this.timeSlotSize;
      }

      if (startTime + operator.getMinOperationTime() > endTime) {
        log.warn(
            "Already increased the time of operation by one time slot in order to meet the minimum time of operation criteria of "
                + operator.getMinOperationTime());
        log.warn("Start time is: " + startTime);
        log.warn("End time is: " + endTime);
        log.warn("Will continue anyway...");
      }

      TransitStopFacility stop1 =
          operator.getRouteProvider().getRandomTransitStop(operator.getCurrentIteration());
      TransitStopFacility stop2 =
          operator.getRouteProvider().getRandomTransitStop(operator.getCurrentIteration());

      while (CoordUtils.calcDistance(stop1.getCoord(), stop2.getCoord())
          < this.minInitialStopDistance) {
        stop2 = operator.getRouteProvider().getRandomTransitStop(operator.getCurrentIteration());
      }

      ArrayList<TransitStopFacility> stopsToBeServed = new ArrayList<>();
      stopsToBeServed.add(stop1);
      stopsToBeServed.add(stop2);

      newPlan =
          new PPlan(operator.getNewPlanId(), this.getStrategyName(), PConstants.founderPlanId);
      newPlan.setStopsToBeServed(stopsToBeServed);
      newPlan.setStartTime(startTime);
      newPlan.setEndTime(endTime);
      newPlan.setNVehicles(1);
      newPlan.setStopsToBeServed(stopsToBeServed);

      newPlan.setLine(
          operator.getRouteProvider().createTransitLineFromOperatorPlan(operator.getId(), newPlan));

    } while (operator.getFranchise().planRejected(newPlan) && triesPerformed < maxNumberOfTries);

    if (!(triesPerformed < maxNumberOfTries)) {
      log.warn(
          "Exceeded the maximum number of tries ("
              + maxNumberOfTries
              + ") to find a new plan for operator "
              + operator.getId()
              + ". Returning null");
      return null;
    }

    return newPlan;
  }