Esempio n. 1
0
  public static void main(String[] args) throws IOException {

    Config c = ConfigUtils.createConfig();
    ConfigUtils.loadConfig(c, RAW_INPUT + "output_config.xml.gz");

    Scenario sc = ScenarioUtils.createScenario(c);
    //		Network net = sc.getNetwork();
    new MatsimNetworkReader(sc.getNetwork()).readFile(RAW_INPUT + "/output_network.xml.gz");
    new PopulationReader(sc).readFile(RAW_INPUT + "output_plans.xml.gz");
    //		dropDepTimes(sc.getPopulation());

    c.controler().setOutputDirectory(NEW_DIR + "output/");
    c.network().setInputFile(NEW_DIR + "input/network.xml.gz");
    c.plans().setInputFile(NEW_DIR + "input/population.xml.gz");

    new NetworkWriter(sc.getNetwork()).write(c.network().getInputFile());
    new PopulationWriter(sc.getPopulation(), sc.getNetwork()).write(c.plans().getInputFile());
    new ConfigWriter(c).write(NEW_DIR + "input/config.xml");

    c.controler().setLastIteration(0);

    Controler cntr = new Controler(sc);
    cntr.getConfig()
        .controler()
        .setOverwriteFileSetting(
            OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles);
    cntr.run();

    Analyzer.main(
        new String[] {
          NEW_DIR + "/output/ITERS/it.0/0.events.xml.gz",
          "/Users/laemmel/arbeit/papers/2015/TRBwFZJ/hybridsim_trb2016/analysis/runagain-vehicles_plot_data"
        });
  }
Esempio n. 2
0
  /** @param args */
  public static void main(String[] args) {

    String input = args[0];
    String output = args[1];

    /* Read the network. */
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario.getNetwork()).readFile(input);

    /* Transform each node. */
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, "EPSG:25832");
    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84,TransformationFactory.DHDN_GK4);

    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation("EPSG:25832",TransformationFactory.WGS84);
    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation(TransformationFactory.DHDN_GK4,TransformationFactory.WGS84);

    for (Node node : scenario.getNetwork().getNodes().values()) {
      ((Node) node).setCoord(ct.transform(node.getCoord()));
    }

    /* Write the resulting network. */
    new NetworkWriter(scenario.getNetwork()).write(output);
  }
Esempio n. 3
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();
  }
Esempio n. 4
0
  public static void main(String args[]) throws IOException {
    String netFile = args[0];
    String zoneFile = args[1];
    String zoneIdKey = args[2];
    int nThreads = Integer.parseInt(args[3]);
    String out = args[4];

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

    logger.info("Loading network...");
    MatsimNetworkReader reader = new MatsimNetworkReader(scenario.getNetwork());
    reader.parse(netFile);

    logger.info("Loading zones...");
    ZoneCollection zones = ZoneGeoJsonIO.readFromGeoJSON(zoneFile, zoneIdKey);

    TTMatrixGenerator generator = new TTMatrixGenerator();
    NumericMatrix m = generator.generate(scenario.getNetwork(), zones, zoneIdKey, nThreads);

    logger.info("Writing zones...");
    NumericMatrixXMLWriter writer = new NumericMatrixXMLWriter();
    writer.write(m, out);
    logger.info("Done.");
  }
  private void initializeTwoWayCarsharingEndWalkLeg(Leg leg, double now) {

    this.state = MobsimAgent.State.LEG;
    Route route = leg.getRoute();

    Link link = mapTW.get(scenario.getNetwork().getLinks().get(leg.getRoute().getEndLinkId()));
    mapTW.remove(scenario.getNetwork().getLinks().get(leg.getRoute().getEndLinkId()));
    initializeCSWalkLeg(
        "walk_rb", now, link, scenario.getNetwork().getLinks().get(route.getEndLinkId()));
  }
Esempio n. 6
0
  private void setLinksMinMax() {

    for (Id<Link> linkId : scenario.getNetwork().getLinks().keySet()) {
      if ((scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getX())
          < xCoordMinLinkNode) {
        xCoordMinLinkNode =
            scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getX();
      }
      if ((scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getY())
          < yCoordMinLinkNode) {
        yCoordMinLinkNode =
            scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getY();
      }
      if ((scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getX())
          > xCoordMaxLinkNode) {
        xCoordMaxLinkNode =
            scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getX();
      }
      if ((scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getY())
          > yCoordMaxLinkNode) {
        yCoordMaxLinkNode =
            scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getY();
      }
    }
  }
  private final void convertPseudoNetwork() {
    List<Id> nodeIds = new ArrayList<Id>(scenario.getNetwork().getNodes().keySet());
    for (Id id : nodeIds) {
      scenario.getNetwork().removeNode(id);
    }
    new CreatePseudoNetwork(scenario.getTransitSchedule(), scenario.getNetwork(), "")
        .createNetwork();

    for (Link l : scenario.getNetwork().getLinks().values()) {
      l.setCapacity(WagonSimConstants.DEFAULT_CAPACITY);
      l.setFreespeed(WagonSimConstants.DEFAULT_FREESPEED);
    }
  }
Esempio n. 8
0
 public boolean loadNetFromFile(String path) {
   Config config = ConfigUtils.createConfig();
   Scenario sc = ScenarioUtils.createScenario(config);
   try {
     new MatsimNetworkReader(sc.getNetwork()).readFile(path);
     board.setNetwork((NetworkImpl) sc.getNetwork());
     board.repaint();
   } catch (Exception e) {
     e.printStackTrace();
     return false;
   }
   return true;
 }
  /**
   * Makes properties changes to a network read from a file (second argument) according to a .CSV
   * file (first argument) and writes the result in other file (third argument)
   *
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {
    if (args.length == 4) {
      Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
      MatsimNetworkReader matsimNetworkReader = new MatsimNetworkReader(scenario.getNetwork());
      matsimNetworkReader.readFile(args[0]);
      Network network = scenario.getNetwork();

      if (args[1].equals("-l")) changePropertiesPerLinkCSVFile(network, args[2]);
      else if (args[1].equals("-g")) changePropertiesGroupLinksCSVFile(network, args[2]);
      NetworkWriter networkWriter = new NetworkWriter(network);
      networkWriter.write(args[3]);
    }
  }
Esempio n. 10
0
  {
    nwr.readFile(
        "/Users/fouriep/IdeaProjects/matsim/matsim/examples/siouxfalls-2014/Siouxfalls_network_PT.xml");
    network = scenario.getNetwork();
    //		nca = new IntraMinDeltaOutLinksNCA(scenario.getNetwork());
    //		nca = new IntraMaxNCA(scenario.getNetwork(),"getCapacityTimesSpeed",null,null);
    nca =
        new MinmizeNumberOfOutlinksNCA(scenario.getNetwork(), "getCapacityTimesSpeed", null, null);
    nca.run();

    //		new ClusterReader().readClusters("~/Desktop/test.txt", scenario.getNetwork(), nca);
    colorsForDisplay = new int[nca.getPointersToClusterLevels().size()];
    getRandomColors((int) nca.getClusterSteps());
  }
Esempio n. 11
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;
  }
Esempio n. 12
0
  private void setLinksToZones() {

    for (Id<Link> linkId : scenario.getNetwork().getLinks().keySet()) {

      // split up the link into link segments with the following length
      double partLength = 0.25 * noiseParams.getRelevantRadius();
      int parts = (int) ((scenario.getNetwork().getLinks().get(linkId).getLength()) / (partLength));

      double fromX = scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getX();
      double fromY = scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord().getY();
      double toX = scenario.getNetwork().getLinks().get(linkId).getToNode().getCoord().getX();
      double toY = scenario.getNetwork().getLinks().get(linkId).getToNode().getCoord().getY();
      double vectorX = toX - fromX;
      double vectorY = toY - fromY;

      // collect the coordinates of this link
      List<Coord> coords = new ArrayList<Coord>();
      coords.add(scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord());
      coords.add(scenario.getNetwork().getLinks().get(linkId).getToNode().getCoord());
      for (int i = 1; i < parts; i++) {
        double x = fromX + (i * ((1. / (parts)) * vectorX));
        double y = fromY + (i * ((1. / (parts)) * vectorY));
        Coord coordTmp = new Coord(x, y);
        coords.add(coordTmp);
      }

      // get zone grid cells for these coordinates
      List<Tuple<Integer, Integer>> relevantTuples = new ArrayList<Tuple<Integer, Integer>>();
      for (Coord coord : coords) {
        Tuple<Integer, Integer> tupleTmp = getZoneTupleForLinks(coord);
        if (!(relevantTuples.contains(tupleTmp))) {
          relevantTuples.add(tupleTmp);
        }
      }

      // go through these zone grid cells and save the link Id
      for (Tuple<Integer, Integer> tuple : relevantTuples) {
        if (zoneTuple2listOfLinkIds.containsKey(tuple)) {
          List<Id<Link>> linkIds = zoneTuple2listOfLinkIds.get(tuple);
          linkIds.add(linkId);
          zoneTuple2listOfLinkIds.put(tuple, linkIds);
        } else {
          List<Id<Link>> linkIds = new ArrayList<>();
          linkIds.add(linkId);
          zoneTuple2listOfLinkIds.put(tuple, linkIds);
        }
      }
    }
  }
Esempio n. 13
0
 public static void main(String[] args) {
   Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
   String basedir = "C:/Users/Joschka/Documents/shared-svn/projects/vw_rufbus/scenario/input/";
   new MatsimNetworkReader(scenario.getNetwork()).readFile(basedir + "network.xml");
   for (Link link : scenario.getNetwork().getLinks().values()) {
     double speed = link.getFreespeed();
     if (speed < 10) link.setFreespeed(0.75 * speed);
     else if (speed < 20) link.setFreespeed(0.7 * speed);
     else if (speed < 30) {
       if (link.getNumberOfLanes() < 2) link.setFreespeed(0.7 * speed);
       else link.setFreespeed(0.75 * speed);
     } else link.setFreespeed(0.7 * speed);
   }
   new NetworkWriter(scenario.getNetwork()).write(basedir + "networks.xml");
 }
  public static void main(final String[] args) throws Exception {
    final String inputEventsFile = args[0];
    final String inputNetworkFile = args[1];
    final String outputXyFile = args[2];

    final Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(sc.getNetwork()).readFile(inputNetworkFile);

    final BufferedWriter writer = IOUtils.getBufferedWriter(outputXyFile);
    final EventsManager events = EventsUtils.createEventsManager();
    events.addHandler(new Handler(sc.getNetwork(), writer));

    new MatsimEventsReader(events).readFile(inputEventsFile);
    writer.close();
  }
Esempio n. 15
0
  private void replaceDoubtfulLegsByOtherMode() {
    for (Person p : scenario.getPopulation().getPersons().values()) {
      for (Plan plan : p.getPlans()) {

        Leg lastleg = null;
        Activity lastActivity = null;
        boolean personb = random.nextBoolean();
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Activity) {
            if (lastActivity == null) {
              lastActivity = (Activity) pe;
            } else {
              Coord lastCoord;
              if (lastActivity.getCoord() != null) {
                lastCoord = lastActivity.getCoord();
              } else {
                Link lastLink = scenario.getNetwork().getLinks().get(lastActivity.getLinkId());
                lastCoord = lastLink.getCoord();
              }
              Coord currentCoord;
              if (((Activity) pe).getCoord() != null) {
                currentCoord = ((Activity) pe).getCoord();
              } else {
                currentCoord =
                    scenario.getNetwork().getLinks().get(((Activity) pe).getLinkId()).getCoord();
              }

              double distance = CoordUtils.calcDistance(lastCoord, currentCoord);

              if (distance > 3000 && lastleg.getMode().equals("walk")) {
                lastleg.setMode("pt");
              } else if (distance > 20000 && lastleg.getMode().equals("bike")) {
                lastleg.setMode("pt");
              } else if (distance < 2000 && (lastleg.getMode().equals("pt"))) {
                if (personb == true) lastleg.setMode("walk");
                else lastleg.setMode("bike");
              }

              lastActivity = (Activity) pe;
            }

          } else if (pe instanceof Leg) {
            lastleg = (Leg) pe;
          }
        }
      }
    }
  }
 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
   Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
   new MatsimNetworkReader(scenario.getNetwork())
       .parse("./data/MATSim-Sin-2.0/input/network/singapore7.xml");
   PublicTranportTeleportAnalizer publicTranportTeleportAnalizer =
       new PublicTranportTeleportAnalizer();
   EventsManager events = (EventsManager) EventsUtils.createEventsManager();
   events.addHandler(publicTranportTeleportAnalizer);
   new MatsimEventsReader(events)
       .readFile("./data/MATSim-Sin-2.0/output/ITERS/it.50/50.events.xml.gz");
   System.out.println("Events read");
   int numPersons = 0, numPersonsTeleported = 0, numPtStages = 0, numPtTeleportedStages = 0;
   Map<Id<Link>, Double> linkWeights = new HashMap<Id<Link>, Double>();
   Collection<Id<Link>> linkIds = new ArrayList<Id<Link>>();
   Collection<Double> startTimes = new ArrayList<Double>();
   Collection<Double> endTimes = new ArrayList<Double>();
   for (List<PTStage> stages : publicTranportTeleportAnalizer.publicTransportStages.values()) {
     numPersons++;
     boolean teleported = false;
     for (PTStage stage : stages) {
       numPtStages++;
       if (stage.teleported) {
         numPtTeleportedStages++;
         teleported = true;
         linkWeights.put(
             stage.linkId,
             (linkWeights.get(stage.linkId) == null ? 0 : linkWeights.get(stage.linkId)) + 1);
         linkIds.add(stage.linkId);
         startTimes.add(stage.beginInstant);
         endTimes.add(stage.beginTravelInstant);
       }
     }
     if (teleported) numPersonsTeleported++;
   }
   System.out.println(
       numPersons + ":" + numPersonsTeleported + " " + numPtStages + ":" + numPtTeleportedStages);
   VariableSizeSelectionNetworkPainter networkPainter =
       new VariableSizeSelectionNetworkPainter(scenario.getNetwork());
   networkPainter.setlinkWeights(linkWeights);
   JFrame window = new SimpleNetworkWindow("Links where people is waiting", networkPainter);
   window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   window.setVisible(true);
   /*DynamicVariableSizeSelectionNetworkPainter networkPainter2 = new DynamicVariableSizeSelectionNetworkPainter(scenario.getNetwork());
   networkPainter2.setlinkWeights(linkIds, startTimes, endTimes);
   JFrame window2 = new SimpleDynamicNetworkWindow("Links where people is waiting dynamic", networkPainter2);
   window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   window2.setVisible(true);*/
 }
 public static void main(String[] args) {
   Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
   new MatsimNetworkReader(scenario)
       .readFile("../../../shared-svn/projects/vw_rufbus/scenario/input/networkptcc.xml");
   int pop = 1000;
   Random rand = MatsimRandom.getRandom();
   for (int i = 0; i < pop; i++) {
     int hx = 603906 - 1500 + rand.nextInt(3000);
     int hy = 5791651 - 1500 + rand.nextInt(3000);
     Coord home = new Coord(hx, hy);
     int wx = 621155 - 1500 + rand.nextInt(3000);
     int wy = 5810010 - 1500 + rand.nextInt(3000);
     Coord work = new Coord(wx, wy);
     Person p = createPerson(scenario, home, work, i);
     scenario.getPopulation().addPerson(p);
   }
   for (int i = 1000; i < pop * 2; i++) {
     int hx = 603906 - 1500 + rand.nextInt(3000);
     int hy = 5791651 - 1500 + rand.nextInt(3000);
     int wx = 621155 - 1500 + rand.nextInt(3000);
     int wy = 5810010 - 1500 + rand.nextInt(3000);
     Coord work = new Coord(hx, hy);
     Coord home = new Coord(wx, wy);
     Person p = createPerson(scenario, home, work, i);
     scenario.getPopulation().addPerson(p);
   }
   new PopulationWriter(scenario.getPopulation(), scenario.getNetwork())
       .write("../../../shared-svn/projects/vw_rufbus/scenario/input/taxibuspassengers.xml");
 }
  /*
   * o--o--o----1----o----2------o-----3----o---d1---o
   * 		  \					 \  |  /
   * 			\				  |	| |
   * 			 \				  |	4 |
   * 			  5				  |	| |
   * 			   \			 /	|  \
   * 				 \______________o
   * 								|
   * 								d2
   * 								|
   * 								o
   *
   */
  private void createTolledNetwork() {

    NetworkImpl network = (NetworkImpl) sc.getNetwork();

    // nodes between o-d1 (all horizonal links)
    double x = -100;
    Node no = network.createAndAddNode(Id.createNodeId("o"), new Coord(x, (double) 0));
    Node n1 = network.createAndAddNode(Id.createNodeId(1), new Coord((double) 0, (double) 0));
    Node n2 = network.createAndAddNode(Id.createNodeId(2), new Coord((double) 1000, (double) 0));
    Node n3 = network.createAndAddNode(Id.createNodeId(3), new Coord((double) 2000, (double) 0));
    Node n4 = network.createAndAddNode(Id.createNodeId(4), new Coord((double) 3000, (double) 0));
    Node nd1 =
        network.createAndAddNode(Id.createNodeId("d1"), new Coord((double) 3100, (double) 0));

    lo = network.createAndAddLink(Id.createLinkId("o"), no, n1, 100, 15, 3600, 1);
    network.createAndAddLink(Id.createLinkId(1), n1, n2, 1000, 15, 3600, 1);
    network.createAndAddLink(Id.createLinkId(2), n2, n3, 1000, 15, 3600, 1);
    network.createAndAddLink(Id.createLinkId(3), n3, n4, 1000, 15, 3600, 1);
    ld1 = network.createAndAddLink(Id.createLinkId("d1"), n4, nd1, 100, 15, 3600, 1);

    double y1 = -1000;
    Node n6 = network.createAndAddNode(Id.createNodeId(6), new Coord((double) 2000, y1));
    double y = -1100;
    Node nd2 = network.createAndAddNode(Id.createNodeId("d2"), new Coord((double) 2000, y));

    // bottleneck link
    network.createAndAddLink(Id.createLinkId(4), n3, n6, 600, 15, 600, 1);
    ld2 = network.createAndAddLink(Id.createLinkId("d2"), n6, nd2, 100, 15, 1500, 1);

    // an alternative link with higher disutility
    network.createAndAddLink(Id.createLinkId(5), n1, n6, 12750, 15, 2700, 1);

    new NetworkWriter(network).write(outputDir + "/input/input_network.xml");
  }
  @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;
  }
 public DCScoringFunctionFactory(
     Scenario scenario, DestinationChoiceBestResponseContext lcContext) {
   super(scenario.getConfig().planCalcScore(), scenario.getNetwork());
   this.scenario = scenario;
   this.lcContext = lcContext;
   log.info("creating DCScoringFunctionFactory");
 }
Esempio n. 21
0
  public static void main(String[] args) {
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Scenario scenario2 = ScenarioUtils.createScenario(ConfigUtils.createConfig());

    new MatsimNetworkReader(scenario.getNetwork())
        .readFile(
            "C:/Users/Joschka/Documents/shared-svn/projects/vw_rufbus/scenario/network/versions/network_trainonly.xml");
    new MatsimNetworkReader(scenario2.getNetwork())
        .readFile(
            "C:/Users/Joschka/Documents/shared-svn/projects/vw_rufbus/scenario/network/pt/braunschweig/bs-network.xml");
    MergeNetworks.merge(scenario.getNetwork(), "", scenario2.getNetwork());

    new NetworkWriter(scenario.getNetwork())
        .write(
            "C:/Users/Joschka/Documents/shared-svn/projects/vw_rufbus/scenario/network/versions/networkpt-feb.xml");
  }
Esempio n. 22
0
  public MeanQueueLengthCalculator() throws Exception {
    scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario).readFile(networkFile);

    linkInfos = new HashMap<Id, LinkInfo>();

    counts = new HashMap<Id, AtomicInteger>();
    sumCountsPerHour = new HashMap<Id, AtomicInteger>();
    meanCounts = new HashMap<Id, double[]>();

    for (Link link : scenario.getNetwork().getLinks().values()) {
      linkInfos.put(link.getId(), new LinkInfo(link.getId()));

      counts.put(link.getId(), new AtomicInteger());
      sumCountsPerHour.put(link.getId(), new AtomicInteger());
      meanCounts.put(link.getId(), new double[hours]);
    }

    log.info("start reading events file...");
    EventsManager eventsManager = (EventsManager) EventsUtils.createEventsManager();
    eventsManager.addHandler(this);

    MatsimEventsReader eventsReader = new MatsimEventsReader(eventsManager);
    eventsReader.readFile(eventsFile);
    log.info("done.");

    for (LinkInfo linkInfo : linkInfos.values()) {
      getLinkStatistic(linkInfo);
    }

    log.info("start writing file...");
    writeFile();
    log.info("done.");
  }
  private void initializeOneWayCarsharingStartWalkLeg(Leg leg, double now) {

    this.state = MobsimAgent.State.LEG;
    Route route = leg.getRoute();
    OneWayCarsharingRDWithParkingStation station =
        findClosestAvailableOWCar(route.getStartLinkId());

    if (station == null) {
      this.state = MobsimAgent.State.ABORT;
      this.simulation
          .getEventsManager()
          .processEvent(new NoVehicleCarSharingEvent(now, route.getStartLinkId(), "ow"));

      return;
    }
    startStationOW = station;
    owVehId = station.getIDs().get(0);
    this.carSharingVehicles.getOneWayVehicles().removeVehicle(station, owVehId);

    initializeCSWalkLeg(
        "walk_ow_sb",
        now,
        scenario.getNetwork().getLinks().get(route.getStartLinkId()),
        startStationOW.getLink());
  }
Esempio n. 24
0
  public boolean loadNetFromOSM(final String path, final String crs) {
    // REVISAR UTM33N a UTM19N
    //        String UTM19N_PROJCS =
    // "PROJCS[\"WGS_1984_UTM_Zone_19N\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"latitude_of_origin\",0],PARAMETER[\"central_meridian\",-69],PARAMETER[\"scale_factor\",0.9996],PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]";
    //	String crs = UTM19N_PROJCS; // the coordinate reference system to be used.

    this.crs = crs;
    String osm = path;

    Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network net = sc.getNetwork();

    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84, crs);

    OsmNetworkReader onr = new OsmNetworkReader(net, ct); // constructs a new openstreetmap reader
    try {
      onr.parse(osm); // starts the conversion from osm to matsim
    } catch (UncheckedIOException e) {
      e.printStackTrace();
      return false;
    }
    // at this point we already have a matsim network...
    new NetworkCleaner()
        .run(net); // but may be there are isolated (not connected) links. The network cleaner
    // removes those links
    board.setNetwork((NetworkImpl) net);
    board.repaint();
    return true;
  }
 @Override
 public PlanStrategy createPlanStrategy(Scenario scenario, EventsManager eventsManager) {
   PlanStrategy strategy =
       new PlanStrategyImpl(
           new PathSizeLogitSelector(scenario.getConfig().planCalcScore(), scenario.getNetwork()));
   return strategy;
 }
Esempio n. 26
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);
  }
Esempio n. 27
0
  private void writeFile() throws Exception {
    FileOutputStream fos = null;
    OutputStreamWriter osw = null;
    BufferedWriter bw = null;
    fos = new FileOutputStream(outFile);
    osw = new OutputStreamWriter(fos, charset);
    bw = new BufferedWriter(osw);

    for (Link link : scenario.getNetwork().getLinks().values()) {
      StringBuffer sb = new StringBuffer();
      sb.append(link.getId());

      double[] meanArray = meanCounts.get(link.getId());
      for (double mean : meanArray) {
        sb.append(separator);
        sb.append(mean);
      }
      bw.write(sb.toString());
      bw.write("\n");
    }

    bw.close();
    osw.close();
    fos.close();
  }
  private void initializeOneWayCarsharingCarLeg(Link l, double now) {
    this.state = MobsimAgent.State.LEG;

    PlanElement pe = this.getCurrentPlanElement();

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

    if (endStationOW == null) {

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

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

      Link destinationLink = endStationOW.getLink();
      // create route for the car part of the onewaycarsharing trip
      initializeCSVehicleLeg("onewaycarsharing", now, l, destinationLink);
    }
  }
  private OneWayCarsharingRDWithParkingStation findClosestAvailableOWCar(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);
    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.getNumberOfVehicles() > 0) {
        closest = station;
        distanceSearch =
            CoordUtils.calcEuclideanDistance(link.getCoord(), station.getLink().getCoord());
      }
    }
    // owvehiclesLocation.removeVehicle(closest.getLink());
    return closest;
  }
  /**
   * @param internalizeEmissionOrCongestion emission congestion or both Total external costs
   *     includes only emission and caused congestion costs. This is basically toll on each link
   */
  public Map<Id<Link>, Double> getLinkToTotalExternalCost(
      final Scenario sc, final String internalizeEmissionOrCongestion) {

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

    if (internalizeEmissionOrCongestion.equalsIgnoreCase("ei")) return getLink2EmissionToll(sc);
    else if (internalizeEmissionOrCongestion.equalsIgnoreCase("ci"))
      return getLink2CongestionToll(sc).get(simEndTime);
    else if (internalizeEmissionOrCongestion.equalsIgnoreCase("eci")) {

      Map<Id<Link>, Double> link2delaycost = getLink2CongestionToll(sc).get(simEndTime);
      Map<Id<Link>, Double> link2emissioncost = getLink2EmissionToll(sc);

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

      for (Link l : sc.getNetwork().getLinks().values()) {
        Id<Link> linkId = l.getId();

        if (link2delaycost.containsKey(linkId) && link2emissioncost.containsKey(linkId)) {
          totalCost.put(linkId, link2delaycost.get(linkId) + link2emissioncost.get(linkId));
        } else if (link2emissioncost.containsKey(linkId)) {
          totalCost.put(linkId, link2emissioncost.get(linkId));
        } else totalCost.put(linkId, link2delaycost.get(linkId));
      }
      return totalCost;
    } else
      throw new RuntimeException(
          "Do not recognize the external costs option. Available options are ei, ci or eci. Aborting ...");
  }