/**
  * @param schedule
  * @return
  */
 public static TransitSchedule removeRoutesWithOnlyOneRouteStop(TransitSchedule schedule) {
   log.info("Removing transitRoutes with only one stop...");
   TransitSchedule tS = TransitScheduleCleaner.makeTransitScheduleModifiable(schedule);
   Set<Id> routeIds;
   for (TransitLine line : tS.getTransitLines().values()) {
     routeIds = new HashSet<Id>();
     for (TransitRoute route : line.getRoutes().values()) {
       // a transitRoute with only one stop makes no sense
       if (route.getStops().size() < 2) {
         routeIds.add(route.getId());
       }
     }
     // remove identified routes
     for (Id id : routeIds) {
       line.removeRoute(line.getRoutes().get(id));
     }
     // log only if something has been done
     if (routeIds.size() > 0) {
       log.info(
           "Following TransitRoutes are removed from TransitLine: "
               + line.getId()
               + ". "
               + routeIds.toString());
     }
   }
   return tS;
 }
  public static TransitSchedule removeRoutesWithoutDepartures(TransitSchedule transitSchedule) {

    log.info("Removing all routes without any departure");
    TransitSchedule tS = TransitScheduleCleaner.makeTransitScheduleModifiable(transitSchedule);
    printStatistic(tS);

    StringBuffer sB = new StringBuffer();
    int nOfRouteRemoved = 0;

    for (TransitLine line : tS.getTransitLines().values()) {
      List<TransitRoute> routesToRemove = new LinkedList<TransitRoute>();

      for (TransitRoute route : line.getRoutes().values()) {
        if (route.getDepartures().size() == 0) {
          routesToRemove.add(route);
        }
      }

      for (TransitRoute transitRoute : routesToRemove) {
        line.removeRoute(transitRoute);
        sB.append(line.getId() + "-" + transitRoute.getId());
        sB.append(", ");
        nOfRouteRemoved++;
      }
    }

    printStatistic(tS);
    log.info("Removed " + nOfRouteRemoved + " routes from transitSchedule: " + sB.toString());

    return tS;
  }
 public WaitTimeStuckCalculator(
     final Population population,
     final TransitSchedule transitSchedule,
     final int timeSlot,
     final int totalTime) {
   this.population = population;
   this.timeSlot = timeSlot;
   for (TransitLine line : transitSchedule.getTransitLines().values())
     for (TransitRoute route : line.getRoutes().values()) {
       double[] sortedDepartures = new double[route.getDepartures().size()];
       int d = 0;
       for (Departure departure : route.getDepartures().values())
         sortedDepartures[d++] = departure.getDepartureTime();
       Arrays.sort(sortedDepartures);
       Map<Id<TransitStopFacility>, WaitTimeData> stopsMap =
           new HashMap<Id<TransitStopFacility>, WaitTimeData>(100);
       Map<Id<TransitStopFacility>, double[]> stopsScheduledMap =
           new HashMap<Id<TransitStopFacility>, double[]>(100);
       for (TransitRouteStop stop : route.getStops()) {
         stopsMap.put(
             stop.getStopFacility().getId(), new WaitTimeDataArray(totalTime / timeSlot + 1));
         double[] cacheWaitTimes = new double[totalTime / timeSlot + 1];
         for (int i = 0; i < cacheWaitTimes.length; i++) {
           double endTime = timeSlot * (i + 1);
           if (endTime > 24 * 3600) endTime -= 24 * 3600;
           cacheWaitTimes[i] = Time.UNDEFINED_TIME;
           SORTED_DEPARTURES:
           for (double departure : sortedDepartures) {
             double arrivalTime =
                 departure
                     + (stop.getArrivalOffset() != Time.UNDEFINED_TIME
                         ? stop.getArrivalOffset()
                         : stop.getDepartureOffset());
             if (arrivalTime >= endTime) {
               cacheWaitTimes[i] = arrivalTime - endTime;
               break SORTED_DEPARTURES;
             }
           }
           if (cacheWaitTimes[i] == Time.UNDEFINED_TIME)
             cacheWaitTimes[i] =
                 sortedDepartures[0]
                     + 24 * 3600
                     + (stop.getArrivalOffset() != Time.UNDEFINED_TIME
                         ? stop.getArrivalOffset()
                         : stop.getDepartureOffset())
                     - endTime;
         }
         stopsScheduledMap.put(stop.getStopFacility().getId(), cacheWaitTimes);
       }
       Tuple<Id<TransitLine>, Id<TransitRoute>> key =
           new Tuple<Id<TransitLine>, Id<TransitRoute>>(line.getId(), route.getId());
       waitTimes.put(key, stopsMap);
       scheduledWaitTimes.put(key, stopsScheduledMap);
     }
 }
 @Override
 public boolean getEnterTransitRoute(
     final TransitLine line,
     final TransitRoute transitRoute,
     final List<TransitRouteStop> stopsToCome,
     TransitVehicle transitVehicle) {
   ExperimentalTransitRoute route = (ExperimentalTransitRoute) getCurrentLeg().getRoute();
   if (line.getId().equals(route.getLineId())) {
     return containsId(stopsToCome, route.getEgressStopId());
   } else {
     return false;
   }
 }
 private static Population getPopulationTypesTransitLine(Scenario scenario, String[] args) {
   scenario.getConfig().transit().setUseTransit(true);
   (new TransitScheduleReader(scenario)).readFile(args[4]);
   TransitLine line =
       scenario.getTransitSchedule().getTransitLines().get(Id.create(args[5], TransitLine.class));
   MutableScenario sc = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
   Population population = PopulationUtils.createPopulation(sc.getConfig(), sc.getNetwork());
   for (Person person : scenario.getPopulation().getPersons().values())
     if (isRelatedWithLine(person, line))
       population.addPerson(new PersonImplPops(person, Id.create(line.getId(), Population.class)));
     else population.addPerson(new PersonImplPops(person, PersonImplPops.DEFAULT_POP_ID));
   return population;
 }
  private final void createVehicleLinkSpeedAttributes() {
    for (TransitLine transitLine : scenario.getTransitSchedule().getTransitLines().values()) {
      for (TransitRoute transitRoute : transitLine.getRoutes().values()) {
        Set<Id> vehIds = new HashSet<Id>();
        for (Departure departure : transitRoute.getDepartures().values()) {
          vehIds.add(departure.getVehicleId());
        }

        Iterator<TransitRouteStop> iterator = transitRoute.getStops().iterator();
        double departure = iterator.next().getDepartureOffset();
        while (iterator.hasNext()) {
          TransitRouteStop routeStop = iterator.next();
          double arrival = routeStop.getArrivalOffset();
          Link link = scenario.getNetwork().getLinks().get(routeStop.getStopFacility().getLinkId());
          double speed = link.getLength() / (arrival - departure);
          if (speed >= 200.0) {
            System.out.println(
                "line="
                    + transitLine.getId()
                    + ";route="
                    + transitRoute.getId()
                    + "stop="
                    + routeStop.getStopFacility().getId()
                    + ": lLenth="
                    + link.getLength()
                    + ";arr="
                    + arrival
                    + ";dep="
                    + departure
                    + "");
          }

          for (Id vehId : vehIds) {
            this.vehicleAttributes.putAttribute(vehId.toString(), link.getId().toString(), speed);
          }

          departure = routeStop.getDepartureOffset();
        }
      }
    }
  }
  private final void convertSchedules(
      OTTDataContainer dataContainer, ObjectAttributes trainTypes, boolean isPerformance) {
    TransitScheduleFactory scheduleFactory = scenario.getTransitSchedule().getFactory();
    VehiclesFactory vehiclesFactory = ((ScenarioImpl) scenario).getVehicles().getFactory();

    VehicleType vehicleType =
        vehiclesFactory.createVehicleType(new IdImpl(WagonSimConstants.DEFAULT_VEHICLE_TYPE));
    VehicleCapacity vehicleCapacity = vehiclesFactory.createVehicleCapacity();
    // we do not use this capacity. Therefore it should infinite, otherwise this capacity may exceed
    // before ``our'' capacities are exceeded // dr, oct'13
    vehicleCapacity.setSeats(999999);
    vehicleCapacity.setStandingRoom(999999);
    // we defined the vehicle-enter/leave-time is implicit included in transfer-times which
    // are defined in the transitrouterconfig (for handling see
    // WagonSimTripRouterFactoryImpl#WagonSimRouterWrapper)
    // dr, oct'13
    vehicleType.setAccessTime(0);
    vehicleType.setEgressTime(0);
    vehicleType.setCapacity(vehicleCapacity);
    ((ScenarioImpl) scenario).getVehicles().addVehicleType(vehicleType);

    Date startDate = extractStartDate(dataContainer, isPerformance);
    System.out.println("startDate=" + startDate.toString());

    for (Locomotive locomotive : dataContainer.locomotives.values()) {

      Departure departure = null;
      List<TransitRouteStop> transitRouteStops = new ArrayList<TransitRouteStop>();
      for (StationData stationData : locomotive.trips.values()) {

        TransitStopFacility stopFacility =
            scenario.getTransitSchedule().getFacilities().get(stationData.stationId);
        if (stopFacility == null) {
          throw new RuntimeException(
              "locomotive id="
                  + locomotive.id
                  + ": station id="
                  + stationData.stationId
                  + " not found. Bailing out.");
        }

        double arrivalDelay = Double.NaN;
        double departureDelay = Double.NaN;
        if (departure == null) {
          double lineDepartureOffset =
              (stationData.departure.getTime() - startDate.getTime()) / 1000.0;
          if (!isPerformance) {
            lineDepartureOffset -= stationData.delayDeparture;
          }
          departure = scheduleFactory.createDeparture(locomotive.id, lineDepartureOffset);
          arrivalDelay = 0.0;
        } else {
          arrivalDelay =
              (stationData.arrival.getTime() - startDate.getTime()) / 1000.0
                  - departure.getDepartureTime();
          if (!isPerformance) {
            arrivalDelay -= stationData.delayArrival;
          }
        }
        departureDelay =
            (stationData.departure.getTime() - startDate.getTime()) / 1000.0
                - departure.getDepartureTime();
        if (!isPerformance) {
          departureDelay -= stationData.delayDeparture;
        }

        if (departureDelay < arrivalDelay) {
          throw new RuntimeException(
              "locomotive id="
                  + locomotive.id
                  + ": arrival="
                  + stationData.arrival.toString()
                  + " does not fit with departure="
                  + stationData.departure.toString()
                  + ". ("
                  + departureDelay
                  + "<"
                  + arrivalDelay
                  + ") Bailing out.");
        }

        TransitRouteStop stop =
            scheduleFactory.createTransitRouteStop(stopFacility, arrivalDelay, departureDelay);
        stop.setAwaitDepartureTime(true);
        transitRouteStops.add(stop);
      }

      if (transitRouteStops.size() > 1) {

        // check if train type is given
        if (trainTypes.getAttribute(locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED)
            == null) {
          throw new RuntimeException(
              "locomotive id="
                  + locomotive.id
                  + ": type="
                  + locomotive.type
                  + " is not defined by the train type table. Bailing out.");
        }

        TransitLine line = scheduleFactory.createTransitLine(locomotive.id);
        scenario.getTransitSchedule().addTransitLine(line);
        TransitRoute route =
            scheduleFactory.createTransitRoute(
                line.getId(), null, transitRouteStops, TransportMode.pt);
        line.addRoute(route);

        Vehicle vehicle = vehiclesFactory.createVehicle(route.getId(), vehicleType);
        ((ScenarioImpl) scenario).getVehicles().addVehicle(vehicle);
        departure.setVehicleId(vehicle.getId());
        route.addDeparture(departure);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(), WagonSimConstants.TRAIN_TYPE, locomotive.type);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_SPEED,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_WEIGHT,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_WEIGHT));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_LENGTH,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_LENGTH));

        // the next day
        vehicle = vehiclesFactory.createVehicle(new IdImpl(route.getId() + ".1"), vehicleType);
        ((ScenarioImpl) scenario).getVehicles().addVehicle(vehicle);
        departure =
            scheduleFactory.createDeparture(
                vehicle.getId(), departure.getDepartureTime() + 24 * 3600);
        departure.setVehicleId(vehicle.getId());
        route.addDeparture(departure);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(), WagonSimConstants.TRAIN_TYPE, locomotive.type);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_SPEED,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_WEIGHT,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_WEIGHT));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_LENGTH,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_LENGTH));

        // the day after the next day
        vehicle = vehiclesFactory.createVehicle(new IdImpl(route.getId() + ".2"), vehicleType);
        ((ScenarioImpl) scenario).getVehicles().addVehicle(vehicle);
        departure =
            scheduleFactory.createDeparture(
                vehicle.getId(), departure.getDepartureTime() + 24 * 3600);
        departure.setVehicleId(vehicle.getId());
        route.addDeparture(departure);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(), WagonSimConstants.TRAIN_TYPE, locomotive.type);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_SPEED,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_WEIGHT,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_WEIGHT));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_LENGTH,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_LENGTH));
      } else if (transitRouteStops.size() == 1) {
        System.out.println(
            "locomotive id="
                + locomotive.id
                + ": only one station given. Therefore, no transitLine created.");
      } else {
        System.out.println(
            "locomotive id="
                + locomotive.id
                + ": no station is given. Therefore, no transitLine created.");
      }
    }
  }