@Override
  public ScoringFunction createNewScoringFunction(Person person) {
    SumScoringFunction scoringFunctionAccumulator = new SumScoringFunction();

    SumScoringFunction.BasicScoring scoringFunction;
    if (usingConfigParamsForScoring) {
      scoringFunction = new DCActivityWOFacilitiesScoringFunction(person, this.lcContext);
      scoringFunctionAccumulator.addScoringFunction(
          new CharyparNagelActivityScoring(this.lcContext.getParams()));
      // forgetting the previous line (which we did at some point) is not picked up by any test
      // within the locationchoice contrib. kai, oct'14
    } else {
      scoringFunction = new DCActivityScoringFunction(person.getSelectedPlan(), this.lcContext);
    }
    scoringFunctionAccumulator.addScoringFunction(scoringFunction);
    scoringFunctionAccumulator.addScoringFunction(
        new CharyparNagelLegScoring(
            CharyparNagelScoringParameters.getBuilder(scenario.getConfig().planCalcScore())
                .create(),
            scenario.getNetwork()));
    scoringFunctionAccumulator.addScoringFunction(
        new CharyparNagelAgentStuckScoring(
            CharyparNagelScoringParameters.getBuilder(scenario.getConfig().planCalcScore())
                .create()));
    return scoringFunctionAccumulator;
  }
Exemple #2
0
  /**
   * Tests the setup with a traffic light that shows all the time green in the 0th iteration. After
   * the mobsim is run the signal settings are changed thus in the 1st iteration the signal should
   * be red in sec [0,99] and green in [100,2000]
   */
  @Test
  public void testModifySignalControlDataOnsetOffset() {
    // configure and load standard scenario
    Fixture fixture = new Fixture();
    Scenario scenario = fixture.createAndLoadTestScenario(false);
    scenario.getConfig().controler().setFirstIteration(0);
    scenario.getConfig().controler().setLastIteration(1);
    scenario.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory());

    Controler controler = new Controler(scenario);
    controler.getConfig().controler().setCreateGraphs(false);
    controler.addControlerListener(
        new AfterMobsimListener() {

          @Override
          public void notifyAfterMobsim(AfterMobsimEvent event) {
            Scenario scenario = event.getServices().getScenario();
            int dropping = 0;
            int onset = 100;
            for (SignalSystemControllerData intersectionSignal :
                ((SignalsData) scenario.getScenarioElement(SignalsData.ELEMENT_NAME))
                    .getSignalControlData()
                    .getSignalSystemControllerDataBySystemId()
                    .values()) {

              for (SignalPlanData plan : intersectionSignal.getSignalPlanData().values()) {
                plan.setCycleTime(2000);
                for (SignalGroupSettingsData data :
                    plan.getSignalGroupSettingsDataByGroupId().values()) {
                  data.setDropping(dropping);
                  data.setOnset(onset);
                }
              }
            }
          }
        });

    controler.addControlerListener(
        new IterationStartsListener() {

          @Override
          public void notifyIterationStarts(IterationStartsEvent event) {
            event.getServices().getEvents().addHandler(new EventsLogger());

            TestLink2EnterEventHandler enterHandler = new TestLink2EnterEventHandler();
            if (0 == event.getIteration()) {
              enterHandler.link2EnterTime = 38.0;
            }

            if (1 == event.getIteration()) {
              enterHandler.link2EnterTime = 100.0;
              SignalGroupStateChangedEventHandler signalsHandler0 =
                  new TestSignalGroupStateChangedHandler();
              event.getServices().getEvents().addHandler(signalsHandler0);
            }
          }
        });

    controler.run();
  }
 public EventsToTravelDiaries(Scenario scenario) {
   this.network = scenario.getNetwork();
   isTransitScenario = scenario.getConfig().transit().isUseTransit();
   if (isTransitScenario) {
     this.transitSchedule = scenario.getTransitSchedule();
     this.walkSpeed = new TransitRouterConfig(scenario.getConfig()).getBeelineWalkSpeed();
   }
 }
 public DestinationChoice(Scenario scenario) {
   super(scenario.getConfig().global());
   if (DestinationChoiceConfigGroup.Algotype.bestResponse.equals(
       ((DestinationChoiceConfigGroup) scenario.getConfig().getModule("locationchoice"))
           .getAlgorithm())) {
     throw new RuntimeException(
         "best response location choice not supported as part of LocationChoice. "
             + "Use BestReplyLocationChoice instead, but be aware that as of now some Java coding is necessary to do that. kai, feb'13");
   }
   this.scenario = scenario;
   initLocal();
 }
  @Override
  public TripRouter instantiateAndConfigureTripRouter(RoutingContext routingContext) {

    TripRouter instance = this.delegateFactory.instantiateAndConfigureTripRouter(routingContext);

    Network network = this.scenario.getNetwork();
    PopulationFactory populationFactory = this.scenario.getPopulation().getFactory();
    ModeRouteFactory modeRouteFactory =
        ((PopulationFactoryImpl) populationFactory).getModeRouteFactory();

    MultiModalConfigGroup multiModalConfigGroup =
        (MultiModalConfigGroup) scenario.getConfig().getModule(MultiModalConfigGroup.GROUP_NAME);
    Set<String> simulatedModes =
        CollectionUtils.stringToSet(multiModalConfigGroup.getSimulatedModes());
    for (String mode : simulatedModes) {

      if (instance.getRegisteredModes().contains(mode)) {
        log.warn("A routing algorithm for " + mode + " is already registered. It is replaced!");
      }

      TravelTime travelTime = this.multimodalTravelTimes.get(mode);
      if (travelTime == null) {
        throw new RuntimeException(
            "No travel time object was found for mode " + mode + "! Aborting.");
      }

      Network subNetwork = multimodalSubNetworks.get(mode);
      if (subNetwork == null) {
        subNetwork = NetworkImpl.createNetwork();
        Set<String> restrictions = new HashSet<>();
        restrictions.add(mode);
        TransportModeNetworkFilter networkFilter = new TransportModeNetworkFilter(network);
        networkFilter.filter(subNetwork, restrictions);
        this.multimodalSubNetworks.put(mode, subNetwork);
      }

      /*
       * We cannot use the travel disutility object from the routingContext since it
       * has not been created for the modes used here.
       */
      TravelDisutility travelDisutility =
          this.travelDisutilityFactory.createTravelDisutility(
              travelTime, scenario.getConfig().planCalcScore());
      LeastCostPathCalculator routeAlgo =
          this.leastCostPathCalculatorFactory.createPathCalculator(
              subNetwork, travelDisutility, travelTime);
      RoutingModule legRouterWrapper =
          DefaultRoutingModules.createNetworkRouter(mode, populationFactory, subNetwork, routeAlgo);
      instance.setRoutingModule(mode, legRouterWrapper);
    }

    return instance;
  }
  @Test
  public void test() {
    Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    sc.getConfig().scenario().setUseTransit(true);
    sc.getConfig().scenario().setUseVehicles(true);
    EventsManager manager = EventsUtils.createEventsManager(sc.getConfig());

    WagonSimQSimFactory factory = new WagonSimQSimFactory(new ObjectAttributes(), null);
    Mobsim sim = factory.createMobsim(sc, manager);
    Assert.assertNotNull(sim);
    Assert.assertTrue(sim instanceof QSim);
    //		QSim qSim = (QSim) sim;
  }
 @Override
 public PlanStrategy createPlanStrategy(Scenario scenario, EventsManager eventsManager) {
   PlanStrategy strategy =
       new PlanStrategyImpl(
           new PathSizeLogitSelector(scenario.getConfig().planCalcScore(), scenario.getNetwork()));
   return strategy;
 }
  private PlansCalcRouteWithTollOrNot testee(
      final Scenario scenario, final RoadPricingScheme toll) {
    return Injector.createInjector(
            scenario.getConfig(),
            new AbstractModule() {
              @Override
              public void install() {
                bind(RoadPricingScheme.class).toInstance(toll);
                bind(Scenario.class).toInstance(scenario);
                addTravelTimeBinding(TransportMode.car).to(FreeSpeedTravelTime.class);
                bind(PlansCalcRouteWithTollOrNot.class);
                install(new ScenarioElementsModule());
                addTravelDisutilityFactoryBinding(TransportMode.car)
                    .toInstance(
                        new RandomizingTimeDistanceTravelDisutility.Builder(TransportMode.car));
                install(new TripRouterModule());
                addControlerListenerBinding().to(RoadPricingControlerListener.class);

                // add the events handler to calculate the tolls paid by agents
                bind(CalcPaidToll.class).in(Singleton.class);
                addEventHandlerBinding().to(CalcPaidToll.class);

                bind(CalcAverageTolledTripLength.class).in(Singleton.class);
                addEventHandlerBinding().to(CalcAverageTolledTripLength.class);
              }
            })
        .getInstance(PlansCalcRouteWithTollOrNot.class);
  }
  public FreeFloatingParkingPersonDriverAgentImpl(
      final Person person,
      final Plan plan,
      final Netsim simulation,
      final Scenario scenario,
      final MatsimServices controler,
      ParkingModuleWithFreeFloatingCarSharing parkingModule) {
    this.person = person;
    this.simulation = simulation;
    this.controler = controler;
    this.plan = plan;
    this.scenario = scenario;
    this.parkingModule = parkingModule;

    beelineFactor =
        ((PlansCalcRouteConfigGroup) scenario.getConfig().getModule("planscalcroute"))
            .getBeelineDistanceFactors()
            .get("walk");
    walkSpeed =
        (((PlansCalcRouteConfigGroup) controler.getConfig().getModule("planscalcroute"))
            .getTeleportedModeSpeeds()
            .get("walk"));

    List<? extends PlanElement> planElements = this.plan.getPlanElements();
    if (planElements.size() > 0) {
      this.currentPlanElementIndex = 0;
      Activity firstAct = (Activity) planElements.get(0);
      this.currentLinkId = firstAct.getLinkId();
      this.state = MobsimAgent.State.ACTIVITY;
      calculateAndSetDepartureTime(firstAct);
    }
    throw new RuntimeException(
        "Should this class still be in use?  I think there is a delegated version of this, isn't there?  "
            + "This one here causes additional refactoring work. kai, feb'16");
  }
 /*
  * return 0 if files are read and 1 if k values are created.
  * This is important to know for reading (case 0) or computation of maxDCScore (case 1)
  */
 public int run() {
   DestinationChoiceConfigGroup dccg =
       (DestinationChoiceConfigGroup)
           scenario.getConfig().getModule(DestinationChoiceConfigGroup.GROUP_NAME);
   String pkValuesFileName = dccg.getpkValuesFile();
   String fkValuesFileName = dccg.getfkValuesFile();
   String maxEpsValuesFileName = dccg.getMaxEpsFile();
   if (pkValuesFileName != null && fkValuesFileName != null && maxEpsValuesFileName != null) {
     ObjectAttributesXmlReader persKValuesReader =
         new ObjectAttributesXmlReader(this.personsKValues);
     ObjectAttributesXmlReader facKValuesReader =
         new ObjectAttributesXmlReader(this.facilitiesKValues);
     try {
       persKValuesReader.parse(pkValuesFileName);
       facKValuesReader.parse(fkValuesFileName);
       log.info("reading kvals from files:\n" + pkValuesFileName + "\n" + fkValuesFileName);
       return 0;
     } catch (UncheckedIOException e) {
       // reading was not successful
       log.error(
           "unsuccessful reading kvals from files!\nThe values are now computed"
               + " and following files are not considered!:\n"
               + pkValuesFileName
               + "\n"
               + fkValuesFileName);
       this.assignKValues();
       return 1;
     }
   } else {
     this.assignKValues();
     return 1;
   }
 }
Exemple #11
0
  private void initWithinDayReplanning(Scenario scenario) {
    TravelDisutility travelDisutility =
        withinDayControlerListener
            .getTravelDisutilityFactory()
            .createTravelDisutility(
                withinDayControlerListener.getTravelTimeCollector(),
                scenario.getConfig().planCalcScore());
    RoutingContext routingContext =
        new RoutingContextImpl(
            travelDisutility, withinDayControlerListener.getTravelTimeCollector());

    LeaveLinkIdentifierFactory duringLegIdentifierFactory =
        new LeaveLinkIdentifierFactory(
            withinDayControlerListener.getLinkReplanningMap(),
            withinDayControlerListener.getMobsimDataProvider());

    StuckAgentsFilterFactory stuckAgentsFilterFactory =
        new StuckAgentsFilterFactory(withinDayControlerListener, scenario.getNetwork());
    duringLegIdentifierFactory.addAgentFilterFactory(stuckAgentsFilterFactory);

    CurrentLegMicroReplannerFactory duringLegReplannerFactory =
        new CurrentLegMicroReplannerFactory(
            scenario,
            withinDayControlerListener.getWithinDayEngine(),
            withinDayControlerListener.getWithinDayTripRouterFactory(),
            routingContext,
            this.controler);
    duringLegReplannerFactory.addIdentifier(duringLegIdentifierFactory.createIdentifier());

    withinDayControlerListener
        .getWithinDayEngine()
        .addDuringLegReplannerFactory(duringLegReplannerFactory);
  }
  public static void main(String[] args) throws Exception {
    Config config = ConfigUtils.loadConfig(configFile, new EmissionsConfigGroup());

    Scenario scenario = ScenarioUtils.loadScenario(config);

    // following is only for backward compatibility in which vehicle description is null;
    // for the new scenarios, setting vehicle description should be preferred.; Amit, sep 2016.
    EmissionsConfigGroup ecg =
        (EmissionsConfigGroup) scenario.getConfig().getModule(EmissionsConfigGroup.GROUP_NAME);
    ecg.setUsingVehicleTypeIdAsVehicleDescription(true);

    EmissionModule emissionModule = new EmissionModule(scenario);
    emissionModule.createLookupTables();
    emissionModule.createEmissionHandler();

    EventsManager eventsManager = EventsUtils.createEventsManager();
    eventsManager.addHandler(emissionModule.getWarmEmissionHandler());
    eventsManager.addHandler(emissionModule.getColdEmissionHandler());

    EventWriterXML emissionEventWriter = new EventWriterXML(emissionEventOutputFile);
    emissionModule.getEmissionEventsManager().addHandler(emissionEventWriter);

    MatsimEventsReader matsimEventsReader = new MatsimEventsReader(eventsManager);
    matsimEventsReader.readFile(eventsFile);

    emissionEventWriter.closeFile();

    emissionModule.writeEmissionInformation(emissionEventOutputFile);
  }
  /**
   * @param sc
   * @return link to caused congestion costs which is basically equal to the toll.
   */
  public Map<Double, Map<Id<Link>, Double>> getLink2CongestionToll(final Scenario sc) {

    Map<Double, Map<Id<Link>, Double>> linkTolls = new HashMap<>();

    Config config = sc.getConfig();

    double vttsCar =
        ((config.planCalcScore().getModes().get(TransportMode.car).getMarginalUtilityOfTraveling()
                    / 3600)
                + (config.planCalcScore().getPerforming_utils_hr() / 3600))
            / (config.planCalcScore().getMarginalUtilityOfMoney());

    int lastIt = config.controler().getLastIteration();
    String eventsFile =
        config.controler().getOutputDirectory()
            + "/ITERS/it."
            + lastIt
            + "/"
            + lastIt
            + ".events.xml.gz";

    CausedDelayAnalyzer delayAnalyzer = new CausedDelayAnalyzer(eventsFile, sc, noOfTimeBin);
    delayAnalyzer.run();
    Map<Double, Map<Id<Link>, Double>> linkDelays = delayAnalyzer.getTimeBin2LinkId2Delay();

    for (double d : linkDelays.keySet()) {
      Map<Id<Link>, Double> tolls = new HashMap<>();
      for (Id<Link> linkid : linkDelays.get(d).keySet()) {
        tolls.put(linkid, linkDelays.get(d).get(linkid) * vttsCar);
      }
      linkTolls.put(d, tolls);
    }
    return linkTolls;
  }
 public DCScoringFunctionFactory(
     Scenario scenario, DestinationChoiceBestResponseContext lcContext) {
   super(scenario.getConfig().planCalcScore(), scenario.getNetwork());
   this.scenario = scenario;
   this.lcContext = lcContext;
   log.info("creating DCScoringFunctionFactory");
 }
Exemple #15
0
  public static void main(final String[] args) {

    String zoneMappingFilename =
        "/Volumes/Data/projects/sviDosierungsanlagen/scenarios/kreuzlingen/l41_ZoneNo_TAZ_mapping.csv";
    String networkFilename =
        "/Volumes/Data/projects/sviDosierungsanlagen/scenarios/kreuzlingen/matsim/network.cleaned.xml";
    String vehTrajectoryFilename = "/Users/cello/Desktop/VehTrajectory.dat";

    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario.getNetwork()).readFile(networkFilename);

    ZoneIdToIndexMapping zoneMapping = new ZoneIdToIndexMapping();
    new ZoneIdToIndexMappingReader(zoneMapping).readFile(zoneMappingFilename);

    DynamicTravelTimeMatrix matrix = new DynamicTravelTimeMatrix(600, 30 * 3600.0);
    //		new VehicleTrajectoriesReader(new CalculateTravelTimeMatrixFromVehTrajectories(matrix),
    // zoneMapping).readFile(vehTrajectoryFilename);

    TravelTimeCalculator ttcalc =
        new TravelTimeCalculator(
            scenario.getNetwork(), scenario.getConfig().travelTimeCalculator());
    new VehicleTrajectoriesReader(
            new CalculateLinkTravelTimesFromVehTrajectories(ttcalc, scenario.getNetwork()),
            zoneMapping)
        .readFile(vehTrajectoryFilename);
    matrix.dump();
  }
  private OneWayCarsharingRDWithParkingStation findClosestAvailableParkingSpace(Link link) {

    // find the closest available car in the quad tree(?) reserve it (make it unavailable)
    // if no cars within certain radius return null

    double distanceSearch =
        Double.parseDouble(
            scenario
                .getConfig()
                .getModule("OneWayCarsharing")
                .getParams()
                .get("searchDistanceOneWayCarsharing"));

    Collection<OneWayCarsharingRDWithParkingStation> location =
        this.carSharingVehicles
            .getOneWayVehicles()
            .getQuadTree()
            .getDisk(link.getCoord().getX(), link.getCoord().getY(), distanceSearch);
    if (location.isEmpty()) return null;

    OneWayCarsharingRDWithParkingStation closest = null;
    for (OneWayCarsharingRDWithParkingStation station : location) {
      if (CoordUtils.calcEuclideanDistance(link.getCoord(), station.getLink().getCoord())
              < distanceSearch
          && station.getNumberOfAvailableParkingSpaces() > 0) {
        closest = station;
        distanceSearch =
            CoordUtils.calcEuclideanDistance(link.getCoord(), station.getLink().getCoord());
      }
    }

    // owvehiclesLocation.removeVehicle(closest.getLink());
    return closest;
  }
 @Inject
 public Cache(final Scenario scenario) {
   this(
       scenario.getNetwork(),
       ConfigUtils.addOrGetModule(
           scenario.getConfig(),
           LazyScheduleBasedMatrixConfigGroup.GROUP_NAME,
           LazyScheduleBasedMatrixConfigGroup.class));
 }
    @Override
    public FixedGroupsIdentifier get() {
      final Config config = scenario.getConfig();
      final CliquesConfigGroup cliquesConf =
          (CliquesConfigGroup) config.getModule(CliquesConfigGroup.GROUP_NAME);

      return config.households().getInputFile() != null
          ? new FixedGroupsIdentifier(((ScenarioImpl) scenario).getHouseholds())
          : FixedGroupsIdentifierFileParser.readCliquesFile(cliquesConf.getInputFile());
    }
 public InsertRandomActivity(
     final Scenario scenario,
     QuadTree shopFacilityQuadTree,
     QuadTree leisureFacilityQuadTree,
     Provider<TripRouter> tripRouterProvider) {
   super(scenario.getConfig().global().getNumberOfThreads());
   this.scenario = scenario;
   this.shopFacilityQuadTree = shopFacilityQuadTree;
   this.leisureFacilityQuadTree = leisureFacilityQuadTree;
   this.tripRouterProvider = tripRouterProvider;
 }
 public void runJDEQSim(Scenario scenario) {
   EventsManagerImpl events = new EventsManagerImpl();
   events.addHandler(new PersonEventCollector());
   events.initProcessing();
   new JDEQSimulation(
           ConfigUtils.addOrGetModule(
               scenario.getConfig(), JDEQSimConfigGroup.NAME, JDEQSimConfigGroup.class),
           scenario,
           events)
       .run();
   events.finishProcessing();
 }
 public static TripRouterFactory createRichTripRouterFactoryImpl(final Scenario scenario) {
   return Injector.createInjector(
           scenario.getConfig(),
           new TripRouterFactoryModule(),
           new AbstractModule() {
             @Override
             public void install() {
               bind(Scenario.class).toInstance(scenario);
             }
           })
       .getInstance(TripRouterFactory.class);
 }
  public Map<Id<Link>, Double> getLink2EmissionToll(final Scenario sc) {
    int lastIt = sc.getConfig().controler().getLastIteration();
    String emissionEventsFile =
        sc.getConfig().controler().getOutputDirectory()
            + "/ITERS/it."
            + lastIt
            + "/"
            + lastIt
            + ".emission.events.xml.gz";
    EmissionLinkAnalyzer emissionAnalyzer =
        new EmissionLinkAnalyzer(
            sc.getConfig().qsim().getEndTime(), emissionEventsFile, noOfTimeBin);
    emissionAnalyzer.preProcessData();
    emissionAnalyzer.postProcessData();
    SortedMap<Double, Map<Id<Link>, SortedMap<String, Double>>> link2TotalEmissions =
        emissionAnalyzer.getLink2TotalEmissions();

    Map<Id<Link>, Double> linkEmissionCosts = new HashMap<Id<Link>, Double>();

    if (noOfTimeBin != 1)
      throw new RuntimeException(
          "This method is not yet adapted to more than 1 time bin. Aborting ....");

    for (double d : link2TotalEmissions.keySet()) {
      for (Id<Link> link : sc.getNetwork().getLinks().keySet()) {
        double emissionsCosts = 0;
        for (EmissionCostFactors ecf : EmissionCostFactors.values()) {
          String str = ecf.toString();

          if (!str.equals("CO2_TOTAL") || considerCO2Costs) {
            if (link2TotalEmissions.get(d).get(link) != null
                && link2TotalEmissions.get(d).get(link).get(str) != null)
              emissionsCosts += ecf.getCostFactor() * link2TotalEmissions.get(d).get(link).get(str);
          } // else do nothing
        }
        linkEmissionCosts.put(link, emissionsCosts);
      }
    }
    return linkEmissionCosts;
  }
  @Override
  public GroupPlanStrategy get() {
    final GroupPlanStrategy strategy = instantiateStrategy(sc.getConfig());

    final GroupReplanningConfigGroup configGroup =
        (GroupReplanningConfigGroup)
            sc.getConfig().getModule(GroupReplanningConfigGroup.GROUP_NAME);
    strategy.addStrategyModule(
        new MutateActivityLocationsToLocationsOfOthersModule(
            sc.getConfig().global().getNumberOfThreads(),
            sc.getPopulation(),
            configGroup.getLocationChoiceActivityType()));

    strategy.addStrategyModule(
        GroupPlanStrategyFactoryUtils.createJointTripAwareTourModeUnifierModule(
            sc.getConfig(), tripRouterFactory));

    strategy.addStrategyModule(
        GroupPlanStrategyFactoryUtils.createReRouteModule(
            sc.getConfig(), planRoutingAlgorithmFactory, tripRouterFactory));

    strategy.addStrategyModule(
        GroupPlanStrategyFactoryUtils.createRecomposeJointPlansModule(
            sc.getConfig(),
            ((JointPlans) sc.getScenarioElement(JointPlans.ELEMENT_NAME)).getFactory(),
            planLinkIdentifier));

    return strategy;
  }
  private TwoWayCSStation findClosestAvailableTWCar(Id<Link> linkId) {

    // find the closest available car in the quad tree(?) reserve it (make it unavailable)
    // if no cars within certain radius return null
    Link link = scenario.getNetwork().getLinks().get(linkId);

    Collection<TwoWayCSStation> location =
        this.carSharingVehicles
            .getRoundTripVehicles()
            .getQuadTree()
            .getDisk(
                link.getCoord().getX(),
                link.getCoord().getY(),
                Double.parseDouble(
                    scenario
                        .getConfig()
                        .getModule("TwoWayCarsharing")
                        .getParams()
                        .get("searchDistanceTwoWayCarsharing")));
    if (location.isEmpty()) return null;
    double distanceSearch =
        Double.parseDouble(
            scenario
                .getConfig()
                .getModule("TwoWayCarsharing")
                .getParams()
                .get("searchDistanceTwoWayCarsharing"));
    TwoWayCSStation closest = null;
    for (TwoWayCSStation station : location) {
      if (CoordUtils.calcEuclideanDistance(link.getCoord(), station.getLink().getCoord())
              < distanceSearch
          && station.getNumberOfVehicles() > 0) {
        closest = station;
        distanceSearch =
            CoordUtils.calcEuclideanDistance(link.getCoord(), station.getLink().getCoord());
      }
    }

    return closest;
  }
 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;
 }
  public AllCSModesPersonDriverAgentImpl(
      final Person person,
      final Plan plan,
      final Netsim simulation,
      final Scenario scenario,
      CarSharingVehicles carSharingVehicles,
      TripRouter tripRouter) {
    this.person = person;
    this.simulation = simulation;
    this.plan = plan;
    this.scenario = scenario;

    this.carSharingVehicles = carSharingVehicles;

    this.tripRouter = tripRouter;

    beelineFactor =
        ((PlansCalcRouteConfigGroup) scenario.getConfig().getModule("planscalcroute"))
            .getBeelineDistanceFactors()
            .get("walk");
    walkSpeed =
        (((PlansCalcRouteConfigGroup) scenario.getConfig().getModule("planscalcroute"))
            .getTeleportedModeSpeeds()
            .get("walk"));
    // carsharingVehicleLocations = new ArrayList<ActivityFacility>();
    mapTW = new HashMap<Link, Link>();
    mapOW = new HashMap<Link, Link>();
    List<? extends PlanElement> planElements = this.plan.getPlanElements();
    if (planElements.size() > 0) {
      this.currentPlanElementIndex = 0;
      Activity firstAct = (Activity) planElements.get(0);
      this.currentLinkId = firstAct.getLinkId();
      this.state = MobsimAgent.State.ACTIVITY;
      calculateAndSetDepartureTime(firstAct);
    }
    throw new RuntimeException(
        "Should this class still be in use?  I think there is a delegated version of this, isn't there?  "
            + "This one here causes additional refactoring work. kai, feb'16");
  }
 @Inject
 public LazyScheduleBasedMatrixRoutingModule(
     final Cache cache,
     final Scenario scenario,
     final TransitRouter router,
     @Named(TransportMode.transit_walk) final RoutingModule walkRouter) {
   this(
       cache,
       ConfigUtils.addOrGetModule(
           scenario.getConfig(),
           LazyScheduleBasedMatrixConfigGroup.GROUP_NAME,
           LazyScheduleBasedMatrixConfigGroup.class),
       scenario,
       router,
       walkRouter);
 }
  private void createConfig() {

    Config config = sc.getConfig();

    config.controler().setOutputDirectory(outputDir + "/output/" + congestionImpl);
    config.controler().setFirstIteration(0);
    config.controler().setLastIteration(20);
    config.controler().setWriteEventsInterval(10);
    config.controler().setMobsim("qsim");
    config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists);

    config.qsim().setEndTime(9 * 3600.);

    StrategySettings reRoute = new StrategySettings(ConfigUtils.createAvailableStrategyId(config));
    reRoute.setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.ReRoute.name());
    reRoute.setWeight(0.10);
    config.strategy().addStrategySettings(reRoute);
    config.strategy().setFractionOfIterationsToDisableInnovation(0.7);

    StrategySettings changeExpBeta =
        new StrategySettings(ConfigUtils.createAvailableStrategyId(config));
    changeExpBeta.setStrategyName("ChangeExpBeta");
    changeExpBeta.setWeight(0.9);
    config.strategy().addStrategySettings(changeExpBeta);

    ActivityParams o1 = new ActivityParams("o1");
    ActivityParams o2 = new ActivityParams("o2");
    ActivityParams d1 = new ActivityParams("d1");
    ActivityParams d2 = new ActivityParams("d2");

    o1.setTypicalDuration(8 * 3600);
    o2.setTypicalDuration(8 * 3600);
    d1.setTypicalDuration(8 * 3600);
    d2.setTypicalDuration(8 * 3600);

    config.planCalcScore().addActivityParams(o1);
    config.planCalcScore().addActivityParams(o2);
    config.planCalcScore().addActivityParams(d1);
    config.planCalcScore().addActivityParams(d2);

    new ConfigWriter(config).write(outputDir + "/input/input_config.xml.gz");
  }
  @Override
  public TripRouter get() {
    final TripRouter tripRouter = defaultFactory.get();

    final 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(),
                scenario
                    .getConfig()
                    .plansCalcRoute()
                    .getModeRoutingParams()
                    .get(TransportMode.walk)));

    tripRouter.setRoutingModule(TransportMode.pt, routingModule);

    return tripRouter;
  }
  public static void run(Scenario scenario) {
    Config config = scenario.getConfig();
    log.info("setting up multi modal simulation");

    MultiModalConfigGroup multiModalConfigGroup =
        ConfigUtils.addOrGetModule(
            config, MultiModalConfigGroup.GROUP_NAME, MultiModalConfigGroup.class);

    // set Route Factories
    //		LinkNetworkRouteFactory factory = new LinkNetworkRouteFactory();
    //        for (String mode :
    // CollectionUtils.stringToArray(multiModalConfigGroup.getSimulatedModes())) {
    //			((PopulationFactoryImpl) scenario.getPopulation().getFactory()).setRouteFactory(mode,
    // factory);
    //		}

    if (multiModalConfigGroup.isCreateMultiModalNetwork()) {
      log.info("Creating multi modal network.");
      new MultiModalNetworkCreator(multiModalConfigGroup).run(scenario.getNetwork());
    }

    if (multiModalConfigGroup.isEnsureActivityReachability()) {
      log.info(
          "Relocating activities that cannot be reached by the transport modes of their from- and/or to-legs...");
      EnsureActivityReachability ensureActivityReachability =
          new EnsureActivityReachability(scenario);
      ensureActivityReachability.run(scenario.getPopulation());
      ensureActivityReachability.printRelocateCount();
    }

    if (multiModalConfigGroup.isDropNonCarRoutes()) {
      log.info(
          "Dropping existing routes of modes which are simulated with the multi modal mobsim.");
      new NonCarRouteDropper(multiModalConfigGroup).run(scenario.getPopulation());
    }
  }