private void storeVehicleTypeInfo() {
    modeVehicleTypes = new HashMap<String, VehicleType>();
    mode2FlowData = new HashMap<>();

    VehicleType car =
        VehicleUtils.getFactory().createVehicleType(Id.create("car", VehicleType.class));
    car.setMaximumVelocity(16.667);
    car.setPcuEquivalents(1.0);
    modeVehicleTypes.put("car", car);

    VehicleType bike =
        VehicleUtils.getFactory().createVehicleType(Id.create("bike", VehicleType.class));
    bike.setMaximumVelocity(4.167);
    bike.setPcuEquivalents(0.25);
    modeVehicleTypes.put("bike", bike);

    VehicleType truck =
        VehicleUtils.getFactory().createVehicleType(Id.create("truck", VehicleType.class));
    truck.setMaximumVelocity(8.33);
    truck.setPcuEquivalents(3.);
    modeVehicleTypes.put("truck", truck);

    for (String mode : travelModes) {
      TravelModesFlowDynamicsUpdator modeUpdator =
          new TravelModesFlowDynamicsUpdator(modeVehicleTypes.get(mode));
      mode2FlowData.put(modeVehicleTypes.get(mode).getId(), modeUpdator);
    }
  }
  public CreateInitialTimeSchedule(
      String networkInFile, double gridDistance, Coord minXY, Coord maxXY, int numberOfAgents) {
    ScenarioImpl sc = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    MatsimNetworkReader netReader = new MatsimNetworkReader(sc);
    netReader.readFile(networkInFile);
    this.net = (NetworkImpl) sc.getNetwork();

    this.tS = CreateStops.createStops(this.net, gridDistance, minXY, maxXY);
    this.veh = VehicleUtils.createVehiclesContainer();
    this.numberOfAgents = numberOfAgents;
  }
  /**
   * Setting up the simulation {@link Scenario}, using a given {@link Config}. In the scenario setup
   * each network link is given both {@code car} and {@code commercial} as mode. Also, each person
   * is assigned a vehicle, which is based on the Gauteng Freeway Improvement Project (GFIP) vehicle
   * toll classes. the following vehicle types are available.
   *
   * <ul>
   *   <li>{@code A2}: Light delivery vehicle with length 7.0m, maximum velocity of 100km/h, and
   *       accounting for 80% of all commercial vehicles;
   *   <li>{@code B}: Short heavy vehicles with length 12.0m, maximum velocity of 90km/h, and
   *       accounting for 15% of all commercial vehicles; and
   *   <li>{@code C}: Long heavy vehicles with length 20.0m, maximum velocity of 90km/h, and
   *       accounting for the remaining 5% of all commercial vehicles.
   * </ul>
   *
   * These vehicle classes are randomly sampled and assigned to the individuals. No cognisance is
   * given to intra- and inter-area traffic (based on the activity chain structure). This
   * <i><b>should</b></i> be refined.
   *
   * @param config typically the {@link Config} resulting from calling the method {@link
   *     #setupConfig(String, Machine)}.
   * @return a scenario in which the network has the necessary {@code commercial} mode; and each
   *     agent has a vehicle with a particular commercial vehicle class.
   */
  public static Scenario setupScenario(Config config) {
    Scenario sc = ScenarioUtils.loadScenario(config);

    /* Ensure that all links take 'commercial' as mode. */
    LOG.warn("Ensuring all links take 'commercial' as mode...");
    Collection<String> modesCollection = Arrays.asList("car", "commercial");
    Set<String> modesSet = new HashSet<>(modesCollection);
    for (Link link : sc.getNetwork().getLinks().values()) {
      link.setAllowedModes(modesSet);
    }
    LOG.warn("Done adding 'commercial' modes.");

    /* Add all VehicleTypes. */
    Vehicles vehicles = sc.getVehicles();
    for (VehicleTypeSA vt : VehicleTypeSA.values()) {
      vehicles.addVehicleType(vt.getVehicleType());
    }

    MatsimRandom.reset(2015093001l);
    for (Person person : sc.getPopulation().getPersons().values()) {
      /* Randomly sample a vehicle type for each person. */
      VehicleType vehicleType = null;
      double r = MatsimRandom.getRandom().nextDouble();
      if (r <= 0.8) {
        vehicleType = VehicleTypeSA.A2.getVehicleType();
      } else if (r <= 0.95) {
        vehicleType = VehicleTypeSA.B.getVehicleType();
      } else {
        vehicleType = VehicleTypeSA.C.getVehicleType();
      }

      Vehicle truck =
          VehicleUtils.getFactory()
              .createVehicle(Id.create(person.getId(), Vehicle.class), vehicleType);
      vehicles.addVehicle(truck);

      /* Link the vehicle type to the person's attributes. */
      sc.getPopulation()
          .getPersonAttributes()
          .putAttribute(person.getId().toString(), "vehicleType", vehicleType.getId().toString());
    }

    return sc;
  }
Exemple #4
0
 public TaxiModule(TaxiData taxiData) {
   this(taxiData, VehicleUtils.getDefaultVehicleType());
 }
  public static void main(String[] args) {

    //		SubpopulationConfig subPopConfig = new SubpopulationConfig();
    //		subPopConfig.run();
    //		Config config = subPopConfig.getPatnaConfig();
    Config config = ConfigUtils.loadConfig(args[0]);
    Scenario sc = ScenarioUtils.loadScenario(config);

    sc.getConfig().qsim().setUseDefaultVehicles(false);
    ((ScenarioImpl) sc).createVehicleContainer();

    Map<String, VehicleType> modesType = new HashMap<String, VehicleType>();
    VehicleType slum_car =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_car", VehicleType.class));
    slum_car.setMaximumVelocity(60.0 / 3.6);
    slum_car.setPcuEquivalents(1.0);
    modesType.put("slum_car", slum_car);
    sc.getVehicles().addVehicleType(slum_car);

    VehicleType nonSlum_car =
        VehicleUtils.getFactory().createVehicleType(Id.create("nonSlum_car", VehicleType.class));
    nonSlum_car.setMaximumVelocity(60.0 / 3.6);
    nonSlum_car.setPcuEquivalents(1.0);
    modesType.put("nonSlum_car", nonSlum_car);
    sc.getVehicles().addVehicleType(nonSlum_car);

    VehicleType slum_motorbike =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_motorbike", VehicleType.class));
    slum_motorbike.setMaximumVelocity(60.0 / 3.6);
    slum_motorbike.setPcuEquivalents(0.25);
    modesType.put("slum_motorbike", slum_motorbike);
    sc.getVehicles().addVehicleType(slum_motorbike);

    VehicleType nonSlum_motorbike =
        VehicleUtils.getFactory()
            .createVehicleType(Id.create("nonSlum_motorbike", VehicleType.class));
    nonSlum_motorbike.setMaximumVelocity(60.0 / 3.6);
    nonSlum_motorbike.setPcuEquivalents(0.25);
    modesType.put("nonSlum_motorbike", nonSlum_motorbike);
    sc.getVehicles().addVehicleType(nonSlum_motorbike);

    VehicleType slum_bike =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_bike", VehicleType.class));
    slum_bike.setMaximumVelocity(15.0 / 3.6);
    slum_bike.setPcuEquivalents(0.25);
    modesType.put("slum_bike", slum_bike);
    sc.getVehicles().addVehicleType(slum_bike);

    VehicleType nonSlum_bike =
        VehicleUtils.getFactory().createVehicleType(Id.create("nonSlum_bike", VehicleType.class));
    nonSlum_bike.setMaximumVelocity(15.0 / 3.6);
    nonSlum_bike.setPcuEquivalents(0.25);
    modesType.put("nonSlum_bike", nonSlum_bike);
    sc.getVehicles().addVehicleType(nonSlum_bike);

    VehicleType slum_walk =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_walk", VehicleType.class));
    slum_walk.setMaximumVelocity(1.5);
    //		walk.setPcuEquivalents(0.10);
    modesType.put("slum_walk", slum_walk);
    sc.getVehicles().addVehicleType(slum_walk);

    VehicleType nonSlum_walk =
        VehicleUtils.getFactory().createVehicleType(Id.create("nonSlum_walk", VehicleType.class));
    nonSlum_walk.setMaximumVelocity(1.5);
    //		walk.setPcuEquivalents(0.10);
    modesType.put("nonSlum_walk", nonSlum_walk);
    sc.getVehicles().addVehicleType(nonSlum_walk);

    VehicleType slum_pt =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_pt", VehicleType.class));
    slum_pt.setMaximumVelocity(40 / 3.6);
    //		pt.setPcuEquivalents(5);
    modesType.put("slum_pt", slum_pt);
    sc.getVehicles().addVehicleType(slum_pt);

    VehicleType nonSlum_pt =
        VehicleUtils.getFactory().createVehicleType(Id.create("nonSlum_pt", VehicleType.class));
    nonSlum_pt.setMaximumVelocity(40 / 3.6);
    //		pt.setPcuEquivalents(5);
    modesType.put("nonSlum_pt", nonSlum_pt);
    sc.getVehicles().addVehicleType(nonSlum_pt);

    for (Person p : sc.getPopulation().getPersons().values()) {
      Id<Vehicle> vehicleId = Id.create(p.getId(), Vehicle.class);
      String travelMode = null;
      for (PlanElement pe : p.getSelectedPlan().getPlanElements()) {
        if (pe instanceof Leg) {
          travelMode = ((Leg) pe).getMode();
          break;
        }
      }
      Vehicle vehicle =
          VehicleUtils.getFactory().createVehicle(vehicleId, modesType.get(travelMode));
      sc.getVehicles().addVehicle(vehicle);
    }

    final Controler controler = new Controler(sc);

    //		IOUtils.deleteDirectory(new File(controler.getConfig().controler().getOutputDirectory()));
    controler
        .getConfig()
        .controler()
        .setOverwriteFileSetting(
            true
                ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles
                : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists);
    controler.setDumpDataAtEnd(true);
    controler.getConfig().controler().setCreateGraphs(true);

    controler.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            addPlanStrategyBinding("ChangeLegMode_slum")
                .toProvider(
                    new javax.inject.Provider<PlanStrategy>() {
                      String[] availableModes_slum = {
                        "slum_bike", "slum_motorbike", "slum_pt", "slum_walk"
                      };

                      @Override
                      public PlanStrategy get() {
                        final Builder builder = new Builder(new RandomPlanSelector<Plan, Person>());
                        builder.addStrategyModule(
                            new ChangeLegMode(
                                controler.getConfig().global().getNumberOfThreads(),
                                availableModes_slum,
                                true));
                        builder.addStrategyModule(new ReRoute(controler.getScenario()));
                        return builder.build();
                      }
                    });
          }
        });

    controler.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            addPlanStrategyBinding("ChangeLegMode_nonSlum")
                .toProvider(
                    new javax.inject.Provider<PlanStrategy>() {
                      String[] availableModes_nonSlum = {
                        "nonSlum_car",
                        "nonSlum_bike",
                        "nonSlum_motorbike",
                        "nonSlum_pt",
                        "nonSlum_walk"
                      };

                      @Override
                      public PlanStrategy get() {
                        final Builder builder = new Builder(new RandomPlanSelector<Plan, Person>());
                        builder.addStrategyModule(
                            new ChangeLegMode(
                                controler.getConfig().global().getNumberOfThreads(),
                                availableModes_nonSlum,
                                true));
                        builder.addStrategyModule(new ReRoute(controler.getScenario()));
                        return builder.build();
                      }
                    });
          }
        });

    //		controler.setScoringFunctionFactory(new
    // SubPopulationScoringFactory(controler.getScenario()));
    controler.run();
  }
/**
 * Calculates a least-cost-path tree using Dijkstra's algorithm for calculating a shortest-path
 * tree, given a node as root of the tree.
 *
 * @author balmermi, mrieser
 */
public class LeastCostPathTree {

  // ////////////////////////////////////////////////////////////////////
  // member variables
  // ////////////////////////////////////////////////////////////////////

  private Node origin1 = null;
  private double dTime = Time.UNDEFINED_TIME;

  private final TravelTime ttFunction;
  private final TravelDisutility tcFunction;
  private HashMap<Id<Node>, NodeData> nodeData = null;

  private final Vehicle VEHICLE =
      VehicleUtils.getFactory()
          .createVehicle(
              Id.create("theVehicle", Vehicle.class), VehicleUtils.getDefaultVehicleType());
  private final Person PERSON = PopulationUtils.createPerson(Id.create("thePerson", Person.class));

  // ////////////////////////////////////////////////////////////////////
  // constructors
  // ////////////////////////////////////////////////////////////////////

  public LeastCostPathTree(TravelTime tt, TravelDisutility tc) {
    this.ttFunction = tt;
    this.tcFunction = tc;
  }

  public void calculate(final Network network, final Node origin, final double time) {
    this.origin1 = origin;
    this.dTime = time;

    this.nodeData = new HashMap<Id<Node>, NodeData>((int) (network.getNodes().size() * 1.1), 0.95f);
    NodeData d = new NodeData();
    d.time = time;
    d.cost = 0;
    this.nodeData.put(origin.getId(), d);

    ComparatorCost comparator = new ComparatorCost(this.nodeData);
    PriorityQueue<Node> pendingNodes = new PriorityQueue<Node>(500, comparator);
    relaxNode(origin, pendingNodes);
    while (!pendingNodes.isEmpty()) {
      Node n = pendingNodes.poll();
      relaxNode(n, pendingNodes);
    }
  }

  // ////////////////////////////////////////////////////////////////////
  // inner classes
  // ////////////////////////////////////////////////////////////////////

  public static class NodeData {
    private Id<Node> prevId = null;
    private double cost = Double.MAX_VALUE;
    private double time = 0;

    /*package*/ void visit(
        final Id<Node> comingFromNodeId, final double cost1, final double time1) {
      this.prevId = comingFromNodeId;
      this.cost = cost1;
      this.time = time1;
    }

    public double getCost() {
      return this.cost;
    }

    public double getTime() {
      return this.time;
    }

    public Id<Node> getPrevNodeId() {
      return this.prevId;
    }
  }

  /*package*/ static class ComparatorCost implements Comparator<Node> {
    protected Map<Id<Node>, ? extends NodeData> nodeData;

    ComparatorCost(final Map<Id<Node>, ? extends NodeData> nodeData) {
      this.nodeData = nodeData;
    }

    @Override
    public int compare(final Node n1, final Node n2) {
      double c1 = getCost(n1);
      double c2 = getCost(n2);
      if (c1 < c2) return -1;
      if (c1 > c2) return +1;
      return n1.getId().compareTo(n2.getId());
    }

    protected double getCost(final Node node) {
      return this.nodeData.get(node.getId()).getCost();
    }
  }

  // ////////////////////////////////////////////////////////////////////
  // get methods
  // ////////////////////////////////////////////////////////////////////

  public final Map<Id<Node>, NodeData> getTree() {
    return this.nodeData;
  }

  /**
   * @return Returns the root of the calculated tree, or <code>null</code> if no tree was calculated
   *     yet.
   */
  public final Node getOrigin() {
    return this.origin1;
  }

  public final double getDepartureTime() {
    return this.dTime;
  }

  // ////////////////////////////////////////////////////////////////////
  // private methods
  // ////////////////////////////////////////////////////////////////////

  private void relaxNode(final Node n, PriorityQueue<Node> pendingNodes) {
    NodeData nData = nodeData.get(n.getId());
    double currTime = nData.getTime();
    double currCost = nData.getCost();
    for (Link l : n.getOutLinks().values()) {
      Node nn = l.getToNode();
      NodeData nnData = nodeData.get(nn.getId());
      if (nnData == null) {
        nnData = new NodeData();
        this.nodeData.put(nn.getId(), nnData);
      }
      double visitCost =
          currCost + tcFunction.getLinkTravelDisutility(l, currTime, PERSON, VEHICLE);
      double visitTime = currTime + ttFunction.getLinkTravelTime(l, currTime, PERSON, VEHICLE);

      if (visitCost < nnData.getCost()) {
        pendingNodes.remove(nn);
        nnData.visit(n.getId(), visitCost, visitTime);
        additionalComputationsHook(l, currTime);
        pendingNodes.add(nn);
      }
    }
  }

  protected void additionalComputationsHook(Link link, double currTime) {
    // left empty for inheritance
  }

  // ////////////////////////////////////////////////////////////////////
  // main method
  // ////////////////////////////////////////////////////////////////////

  public static void main(String[] args) {
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario).readFile("../../input/network.xml");

    TravelTimeCalculator ttc =
        new TravelTimeCalculator(
            network, 60, 30 * 3600, scenario.getConfig().travelTimeCalculator());
    LeastCostPathTree st =
        new LeastCostPathTree(
            ttc.getLinkTravelTimes(),
            new RandomizingTimeDistanceTravelDisutility.Builder(TransportMode.car)
                .createTravelDisutility(
                    ttc.getLinkTravelTimes(), scenario.getConfig().planCalcScore()));
    Node origin = network.getNodes().get(Id.create(1, Node.class));
    st.calculate(network, origin, 8 * 3600);
    Map<Id<Node>, NodeData> tree = st.getTree();
    for (Map.Entry<Id<Node>, NodeData> e : tree.entrySet()) {
      Id<Node> id = e.getKey();
      NodeData d = e.getValue();
      if (d.getPrevNodeId() != null) {
        System.out.println(id + "\t" + d.getTime() + "\t" + d.getCost() + "\t" + d.getPrevNodeId());
      } else {
        System.out.println(id + "\t" + d.getTime() + "\t" + d.getCost() + "\t" + "0");
      }
    }
  }
}
Exemple #7
0
  public static void main(final String[] args) throws FileNotFoundException, IOException {

    //////////////////
    // OPEN CONFIG FILE
    //////////////////

    JFileChooser fc;
    int state;
    String GTFSCONFIGNAME = null;
    if (args.length == 1) {
      GTFSCONFIGNAME = args[0];
    } else {
      fc = new JFileChooser();
      fc.setDialogTitle("Please select GTFS config file");
      fc.setFileFilter(
          new FileFilter() {
            @Override
            public String getDescription() {
              return "GTFS config file *.xml";
            }

            @Override
            public boolean accept(File f) {
              return f.isDirectory() || f.getName().toLowerCase(Locale.ROOT).endsWith(".xml");
            }
          });
      state = fc.showOpenDialog(null);
      if (state == JFileChooser.APPROVE_OPTION) {
        GTFSCONFIGNAME = fc.getSelectedFile().getAbsolutePath();
      } else if (state == JFileChooser.CANCEL_OPTION) return;
    }

    if (GTFSCONFIGNAME == null) return;

    Config config = ConfigUtils.loadConfig(GTFSCONFIGNAME);

    String[] rts = config.getParam("gtfs", "roots").split(",");
    File[] roots = new File[rts.length];
    for (int i = 0; i < roots.length; i++) roots[i] = new File(rts[i]);

    // (File[] roots, String[] modes, Network network, String[] serviceIds, String
    // outCoordinateSystem)
    GTFS2MATSimTransitSchedule gtfsTTC =
        new GTFS2MATSimTransitSchedule(
            roots,
            config.getParam("gtfs", "modes").split(","),
            ScenarioUtils.loadScenario(config).getNetwork(),
            config.getParam("gtfs", "service").split(","),
            config.getParam("gtfs", "outCoordinateSystem"));

    ///////////////
    // RUN CONVERTER
    ///////////////
    TransitSchedule outputSchedule = gtfsTTC.getTransitSchedule();

    /////////////////
    // CREATE VEHICLES
    /////////////////

    Vehicles outputVehicles = VehicleUtils.createVehiclesContainer();
    CreateMultipleVehicleTypesForSchedule vehicleConverter =
        new CreateMultipleVehicleTypesForSchedule(outputSchedule, outputVehicles);

    String VEHICLETYPESFILE = null;
    fc = new JFileChooser();
    fc.setDialogTitle("Please select a table of vehicle types");
    fc.setFileFilter(
        new FileFilter() {
          @Override
          public String getDescription() {
            return "Table file *.txt";
          }

          @Override
          public boolean accept(File f) {
            return f.isDirectory() || f.getName().toLowerCase(Locale.ROOT).endsWith(".txt");
          }
        });
    state = fc.showOpenDialog(null);
    if (state == JFileChooser.APPROVE_OPTION) {
      VEHICLETYPESFILE = fc.getSelectedFile().getAbsolutePath();
    } else if (state == JFileChooser.CANCEL_OPTION) return;
    if (VEHICLETYPESFILE == null) return;

    vehicleConverter.ReadVehicleTypes(VEHICLETYPESFILE);

    String ROUTEVEHCILEMAPFILE = null;
    fc = new JFileChooser();
    fc.setDialogTitle("Please select a table of route vehicle mapping");
    fc.setFileFilter(
        new FileFilter() {
          @Override
          public String getDescription() {
            return "Table file *.txt";
          }

          @Override
          public boolean accept(File f) {
            return f.isDirectory() || f.getName().toLowerCase(Locale.ROOT).endsWith(".txt");
          }
        });
    state = fc.showOpenDialog(null);
    if (state == JFileChooser.APPROVE_OPTION) {
      ROUTEVEHCILEMAPFILE = fc.getSelectedFile().getAbsolutePath();
    } else if (state == JFileChooser.CANCEL_OPTION) return;
    if (ROUTEVEHCILEMAPFILE == null) return;

    vehicleConverter.ReadRouteVehicleMapping(ROUTEVEHCILEMAPFILE);

    vehicleConverter.run();

    String VEHICLEOUTPUTFILE = null;
    fc = new JFileChooser();
    fc.setDialogTitle("Save vehicles file");
    state = fc.showSaveDialog(null);
    if (state == JFileChooser.APPROVE_OPTION) {
      VEHICLEOUTPUTFILE = fc.getSelectedFile().getAbsolutePath();
    } else if (state == JFileChooser.CANCEL_OPTION) return;
    if (VEHICLEOUTPUTFILE == null) return;

    vehicleConverter.exportVehicles(VEHICLEOUTPUTFILE);

    /////////////////////////
    // EXPORT TRANSIT SCHEDULE
    /////////////////////////

    final String SCHEDULEOUTPUTNAME = config.getParam("gtfs", "outputFile");

    TransitScheduleWriterV1 writer = new TransitScheduleWriterV1(outputSchedule);
    writer.write(SCHEDULEOUTPUTNAME);
  }