@Test
  public void testLegAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final Plan plan = population.getFactory().createPlan();
    person.addPlan(plan);
    final Leg leg = population.getFactory().createLeg("SUV");
    plan.addActivity(
        population.getFactory().createActivityFromLinkId("speech", Id.createLinkId(1)));
    plan.addLeg(leg);
    plan.addActivity(population.getFactory().createActivityFromLinkId("tweet", Id.createLinkId(2)));

    leg.getAttributes().putAttribute("mpg", 0.000001d);

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));
    final Leg readLeg = (Leg) readPerson.getSelectedPlan().getPlanElements().get(1);

    Assert.assertEquals(
        "Unexpected Double attribute in " + readLeg.getAttributes(),
        leg.getAttributes().getAttribute("mpg"),
        readLeg.getAttributes().getAttribute("mpg"));
  }
Example #2
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;
  }
  @Test
  public void testPersonAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    person.getAttributes().putAttribute("brain", false);
    person.getAttributes().putAttribute("party", "republican");

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));

    Assert.assertEquals(
        "Unexpected boolean attribute in " + readPerson.getAttributes(),
        person.getAttributes().getAttribute("brain"),
        readPerson.getAttributes().getAttribute("brain"));

    Assert.assertEquals(
        "Unexpected String attribute in " + readPerson.getAttributes(),
        person.getAttributes().getAttribute("party"),
        readPerson.getAttributes().getAttribute("party"));
  }
  @Test
  public void testCoord3dIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final Plan plan = population.getFactory().createPlan();
    person.addPlan(plan);
    plan.addActivity(population.getFactory().createActivityFromCoord("speech", new Coord(0, 0)));
    plan.addActivity(
        population.getFactory().createActivityFromCoord("tweet", new Coord(0, 0, -100)));

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));
    final Activity readSpeach = (Activity) readPerson.getSelectedPlan().getPlanElements().get(0);
    final Activity readTweet = (Activity) readPerson.getSelectedPlan().getPlanElements().get(1);

    Assert.assertFalse(
        "did not expect Z value in " + readSpeach.getCoord(), readSpeach.getCoord().hasZ());

    Assert.assertTrue("did expect T value in " + readTweet.getCoord(), readTweet.getCoord().hasZ());

    Assert.assertEquals(
        "unexpected Z value in " + readTweet.getCoord(),
        -100,
        readTweet.getCoord().getZ(),
        MatsimTestUtils.EPSILON);
  }
Example #5
0
 public Population geographicallyFilterPopulation(
     final Population origPopulation, final ObjectAttributes personAttributes) {
   Population filteredPopulation = PopulationUtils.createPopulation(ConfigUtils.createConfig());
   Counter counter = new Counter(" person # ");
   boolean actInArea;
   for (Person p : origPopulation.getPersons().values()) {
     counter.incCounter();
     if (p.getSelectedPlan() != null) {
       actInArea = false;
       for (PlanElement pe : p.getSelectedPlan().getPlanElements()) {
         if (!actInArea && pe instanceof ActivityImpl) {
           ActivityImpl act = (ActivityImpl) pe;
           if (inArea(act.getCoord())) {
             actInArea = true;
           }
         }
       }
       if (actInArea) {
         filteredPopulation.addPerson(p);
         filteredAgents.put(p.getId(), p);
       } else {
         personAttributes.removeAllAttributes(p.toString());
       }
     }
   }
   return filteredPopulation;
 }
  @Test
  public void testActivityAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final Plan plan = population.getFactory().createPlan();
    person.addPlan(plan);
    final Activity act = population.getFactory().createActivityFromCoord("speech", new Coord(0, 0));
    plan.addActivity(act);

    act.getAttributes().putAttribute("makes sense", false);
    act.getAttributes().putAttribute("length", 1895L);

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));
    final Activity readAct = (Activity) readPerson.getSelectedPlan().getPlanElements().get(0);

    Assert.assertEquals(
        "Unexpected boolean attribute in " + readAct.getAttributes(),
        act.getAttributes().getAttribute("makes sense"),
        readAct.getAttributes().getAttribute("makes sense"));

    Assert.assertEquals(
        "Unexpected Long attribute in " + readAct.getAttributes(),
        act.getAttributes().getAttribute("length"),
        readAct.getAttributes().getAttribute("length"));
  }
Example #7
0
  public final void createPersonQuadTree() {
    log.info("TEST");
    double minx = (1.0D / 0.0D);
    double miny = (1.0D / 0.0D);
    double maxx = (-1.0D / 0.0D);
    double maxy = (-1.0D / 0.0D);

    for (ActivityFacility f : this.scenario.getActivityFacilities().getFacilities().values()) {
      if (f.getCoord().getX() < minx) minx = f.getCoord().getX();
      if (f.getCoord().getY() < miny) miny = f.getCoord().getY();
      if (f.getCoord().getX() > maxx) maxx = f.getCoord().getX();
      if (f.getCoord().getY() > maxy) maxy = f.getCoord().getY();
    }
    minx -= 1.0D;
    miny -= 1.0D;
    maxx += 1.0D;
    maxy += 1.0D;
    QuadTree<Person> personQuadTree = new QuadTree<>(minx, miny, maxx, maxy);
    for (Person p : this.scenario.getPopulation().getPersons().values()) {
      Coord c =
          ((ActivityFacility)
                  this.scenario
                      .getActivityFacilities()
                      .getFacilities()
                      .get(
                          PopulationUtils.getFirstActivity(((Plan) p.getSelectedPlan()))
                              .getFacilityId()))
              .getCoord();
      personQuadTree.put(c.getX(), c.getY(), p);
    }
    log.info("PersonQuadTree has been created");
    this.personQuadTree = personQuadTree;
  }
  private void repareDriverTrips(final JointTrip toRemove, final JointPlan plan) {
    final List<TripStructureUtils.Trip> subtrips =
        getDriverTrip(toRemove, plan.getIndividualPlan(toRemove.getDriverId()));
    final List<PlanElement> newTrip = new ArrayList<PlanElement>();
    newTrip.add(PopulationUtils.createLeg(TransportMode.car));

    // "state" variables, changed in the loop:
    // - keeps track of the passengers currently in the vehicle.
    //   Pick-up or drop-offs are created at each change
    Set<Id> currentPassengers = Collections.<Id>emptySet();
    for (TripStructureUtils.Trip subtrip : subtrips) {
      final Leg leg = getDriverLegIfItIs(subtrip);
      final Route route = leg == null ? null : leg.getRoute();

      final Set<Id> newPassengers =
          route != null
              ? new HashSet<Id>(((DriverRoute) route).getPassengersIds())
              : Collections.<Id>emptySet();
      // note that no check of the mode is done...
      if (!newPassengers.equals(currentPassengers)) {
        newTrip.add(
            PopulationUtils.createActivityFromLinkId(
                JointActingTypes.INTERACTION,
                route != null ? route.getStartLinkId() : subtrip.getOriginActivity().getLinkId()));

        // as the spatial structure of the trip is modified, it is possible
        // that some pre-existing subtours are removed. Thus, a driver that may
        // have walked to a pick up (because at the same location as its departure)
        // may then have to drive to pick up the second passenger directly if
        // the first passenger was removed. Setting all non-driver legs
        // to car ensures to have a consistent mode chain.
        // XXX It could be done in a smarter way, so that if no subtour is removed, no modification
        // is done
        // For instance, when removing an "intern" trip, first PU and last DO are
        // left untouched, and thus access and egress leg need not be touched.
        newTrip.add(leg != null ? leg : PopulationUtils.createLeg(TransportMode.car));
        currentPassengers = newPassengers;
      }
    }

    TripRouter.insertTrip(
        plan.getIndividualPlan(toRemove.getDriverId()),
        subtrips.get(0).getOriginActivity(),
        newTrip,
        subtrips.get(subtrips.size() - 1).getDestinationActivity());
  }
  // package protected for tests
  final void removePassengerTrip(final JointTrip toRemove, final JointPlan jointPlan) {
    final Plan passengerPlan = jointPlan.getIndividualPlan(toRemove.getPassengerId());

    final Trip tripWithLeg =
        getTripWithLeg(passengerPlan, toRemove.getPassengerLeg(), stagesWithJointTypes);

    TripRouter.insertTrip(
        passengerPlan,
        tripWithLeg.getOriginActivity(),
        Collections.singletonList(PopulationUtils.createLeg(TransportMode.pt)),
        tripWithLeg.getDestinationActivity());
  }
Example #10
0
 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;
 }
  @Before
  public void setUp() throws Exception {

    scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());

    this.population = scenario.getPopulation();
    Person person = PopulationUtils.getFactory().createPerson(DEFAULT_PERSON_ID);
    this.population.addPerson(person);
    Plan plan = PersonUtils.createAndAddPlan(person, true);
    PopulationUtils.createAndAddActivityFromCoord(plan, "act1", new Coord(100.0, 100.0));
    PopulationUtils.createAndAddLeg(plan, "undefined");
    PopulationUtils.createAndAddActivityFromCoord(plan, "act2", new Coord(200.0, 200.0));
    PopulationUtils.createAndAddLeg(plan, "undefined");
    PopulationUtils.createAndAddActivityFromCoord(plan, "act3", new Coord(200.0, 200.0));
    PopulationUtils.createAndAddLeg(plan, "undefined");
    PopulationUtils.createAndAddActivityFromCoord(plan, "act4", new Coord(200.0, 200.0));
    PopulationUtils.createAndAddLeg(plan, "undefined");
    PopulationUtils.createAndAddActivityFromCoord(plan, "act5", new Coord(200.0, 200.0));
    plan.setScore(12.);

    this.network = scenario.getNetwork();
    Node fromNode =
        this.network
            .getFactory()
            .createNode(Id.create("123456", Node.class), new Coord(100.0, 100.0));
    this.network.addNode(fromNode);
    Node toNode =
        this.network
            .getFactory()
            .createNode(Id.create("789012", Node.class), new Coord(200.0, 200.0));
    this.network.addNode(toNode);
    Link link = this.network.getFactory().createLink(DEFAULT_LINK_ID, fromNode, toNode);
    link.setLength(Math.sqrt(20000.0));
    link.setFreespeed(13.333);
    link.setCapacity(2000);
    link.setNumberOfLanes(1);
    this.network.addLink(link);
  }
Example #12
0
  @Test
  public void testEmptyPersonAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    // just check everything works without attributes (dtd validation etc)
    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);
  }
Example #13
0
  /**
   * TODO: write test.
   *
   * @param persons
   * @param outputPlansFileName
   * @param network
   */
  public static void writePersons(
      Collection<? extends Person> persons, String outputPlansFileName, Network network) {
    PopulationWriter popWriter =
        new PopulationWriter(
            PopulationUtils.createPopulation(
                ((MutableScenario) null).getConfig(), ((MutableScenario) null).getNetwork()),
            network);
    popWriter.writeStartPlans(outputPlansFileName);

    for (Person person : persons) {
      popWriter.writePerson(person);
    }

    popWriter.writeEndPlans();
  }
Example #14
0
  /**
   * Test that really the already selected plan is returned.
   *
   * @author mrieser
   */
  public void testSelected() {
    Person person = PopulationUtils.createPerson(Id.create(1, Person.class));
    PlanImpl plan1 = PersonUtils.createAndAddPlan(person, false);
    PlanImpl plan2 = PersonUtils.createAndAddPlan(person, true);
    plan2.setScore(10.0);
    PlanImpl plan3 = PersonUtils.createAndAddPlan(person, false);
    plan3.setScore(-50.0);
    KeepSelected selector = new KeepSelected();

    // test default selected plan
    assertEquals(plan2, selector.selectPlan(person));

    // test selected plan with negative score
    person.setSelectedPlan(plan3);
    assertEquals(plan3, selector.selectPlan(person));

    // test selected plan with undefined score
    person.setSelectedPlan(plan1);
    assertEquals(plan1, selector.selectPlan(person));
  }
Example #15
0
  @Test
  public void testPopulationAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    population.getAttributes().putAttribute("type", "candidates");
    population.getAttributes().putAttribute("number", 2);

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    Assert.assertEquals(
        "Unexpected numeric attribute in " + readScenario.getPopulation().getAttributes(),
        population.getAttributes().getAttribute("number"),
        readScenario.getPopulation().getAttributes().getAttribute("number"));

    Assert.assertEquals(
        "Unexpected String attribute in " + readScenario.getPopulation().getAttributes(),
        population.getAttributes().getAttribute("type"),
        readScenario.getPopulation().getAttributes().getAttribute("type"));
  }
Example #16
0
 // Constructors
 public BasePersonImpl(Id<Person> id) {
   delegate = PopulationUtils.createPerson(id);
 }
  @Test
  public void testPruneSmallestJointPlan() {
    final JointPlans jointPlans = new JointPlans();
    final Map<Id<Person>, Plan> smallJp = new HashMap<>();
    final Map<Id<Person>, Plan> bigJp = new HashMap<>();

    final ReplanningGroup group = new ReplanningGroup();

    Id<Person> id = Id.createPersonId(1);
    {
      final Person person = PopulationUtils.createPerson(id);
      group.addPerson(person);
      {
        final Plan plan = jointPlans.getFactory().createIndividualPlan(person);
        plan.setScore(1d);
        person.addPlan(plan);
        bigJp.put(id, plan);
      }
      {
        final Plan plan = jointPlans.getFactory().createIndividualPlan(person);
        plan.setScore(0d);
        person.addPlan(plan);
        smallJp.put(id, plan);
      }
    }

    id = Id.createPersonId(2);
    {
      final Person person = PopulationUtils.createPerson(id);
      group.addPerson(person);
      {
        final Plan plan = jointPlans.getFactory().createIndividualPlan(person);
        plan.setScore(0d);
        person.addPlan(plan);
        bigJp.put(id, plan);
      }
      {
        final Plan plan = jointPlans.getFactory().createIndividualPlan(person);
        plan.setScore(1d);
        person.addPlan(plan);
        smallJp.put(id, plan);
      }
    }

    id = Id.createPersonId(3);
    {
      final Person person = PopulationUtils.createPerson(id);
      group.addPerson(person);
      {
        final Plan plan = jointPlans.getFactory().createIndividualPlan(person);
        plan.setScore(1d);
        person.addPlan(plan);
        bigJp.put(id, plan);
      }
      {
        final Plan plan = jointPlans.getFactory().createIndividualPlan(person);
        plan.setScore(0d);
        person.addPlan(plan);
      }
    }

    jointPlans.addJointPlan(jointPlans.getFactory().createJointPlan(bigJp));
    jointPlans.addJointPlan(jointPlans.getFactory().createJointPlan(smallJp));

    test(new ConflictSolverTestsFixture(jointPlans, group, smallJp.values()));
  }
/**
 * 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");
      }
    }
  }
}
Example #19
0
  /**
   * @param args
   * @throws FactoryException
   */
  public static void main(String[] args) throws FactoryException {
    String popFile = args[0];
    String facFile = args[1];
    String netFile = args[2];
    int n = Integer.parseInt(args[3]);
    String outDir = args[4];

    Logger logger = Logger.getLogger(DemoScenario.class);

    MathTransform transform = CRS.findMathTransform(CRSUtils.getCRS(31467), CRSUtils.getCRS(3857));

    Config config = ConfigUtils.createConfig();
    Scenario scenario = ScenarioUtils.createScenario(config);
    /*
     * remove foreign persons and extract subsample
     */
    logger.info("Loading persons...");
    MatsimPopulationReader pReader = new MatsimPopulationReader(scenario);
    pReader.readFile(popFile);
    logger.info("Done.");

    logger.info("Removing foreign persons...");
    Set<Id<Person>> remove = new HashSet<>();
    for (Id<Person> id : scenario.getPopulation().getPersons().keySet()) {
      if (id.toString().startsWith("foreign")) {
        remove.add(id);
      }
    }

    int cnt = 0;
    for (Id<Person> id : remove) {
      if (scenario.getPopulation().getPersons().remove(id) != null) {
        cnt++;
      }
    }
    logger.info(String.format("Done. Removed %s foreign persons.", cnt));

    logger.info("Drawing population subsample...");
    List<Person> persons = new ArrayList<>(scenario.getPopulation().getPersons().values());
    Collections.shuffle(persons);
    Population population = PopulationUtils.createPopulation(config);
    cnt = 0;
    for (int i = 0; i < n; i++) {
      population.addPerson(persons.get(i));
    }
    logger.info("Done.");

    logger.info("Bluring activity end times...");
    Random random = new XORShiftRandom();
    for (Person person : population.getPersons().values()) {
      for (Plan plan : person.getPlans()) {
        for (int i = 0; i < plan.getPlanElements().size(); i += 2) {
          Activity act = (Activity) plan.getPlanElements().get(i);
          double endTim = act.getEndTime() - 15 * 60 + (random.nextDouble() * 30 * 60);
          act.setEndTime(endTim);
          double startTim = act.getStartTime() - 15 * 60 + (random.nextDouble() * 30 * 60);
          act.setStartTime(startTim);
        }
      }
    }
    logger.info("Done.");

    logger.info("Writing population...");
    PopulationWriter pWriter = new PopulationWriter(population);
    pWriter.write(String.format("%s/plans.xml.gz", outDir));
    logger.info("Done.");
    /*
     * filter only used facilities
     */
    logger.info("Loading facilities...");
    MatsimFacilitiesReader fReader = new MatsimFacilitiesReader(scenario);
    fReader.readFile(facFile);
    logger.info("Done.");

    logger.info("Removing unsused facilities...");
    Set<Id<ActivityFacility>> unused =
        new HashSet<>(scenario.getActivityFacilities().getFacilities().keySet());
    for (Person person : population.getPersons().values()) {
      for (Plan plan : person.getPlans()) {
        for (int i = 0; i < plan.getPlanElements().size(); i += 2) {
          Activity act = (Activity) plan.getPlanElements().get(i);
          unused.remove(act.getFacilityId());
        }
      }
    }
    logger.info("Done.");

    logger.info("Transforming facility coordinates...");
    for (ActivityFacility fac : scenario.getActivityFacilities().getFacilities().values()) {
      double[] points = new double[] {fac.getCoord().getX(), fac.getCoord().getY()};
      try {
        transform.transform(points, 0, points, 0, 1);
      } catch (TransformException e) {
        e.printStackTrace();
      }

      ((ActivityFacilityImpl) fac).setCoord(new Coord(points[0], points[1]));
    }
    logger.info("Done.");

    logger.info("Writing facilities...");
    FacilitiesWriter fWrtier = new FacilitiesWriter(scenario.getActivityFacilities());
    fWrtier.write(String.format("%s/facilities.xml.gz", outDir));
    logger.info("Done.");
    /*
     * clean network from foreign links
     */
    logger.info("Loading network...");
    MatsimNetworkReader nReader = new MatsimNetworkReader(scenario);
    nReader.readFile(netFile);
    logger.info("Done.");

    logger.info("Removing foreign links...");
    Set<Id<Link>> linksRemove = new HashSet<>();
    for (Id<Link> id : scenario.getNetwork().getLinks().keySet()) {
      if (id.toString().contains(".l")) {
        linksRemove.add(id);
      }
    }

    for (Id<Link> id : linksRemove) {
      scenario.getNetwork().removeLink(id);
    }
    logger.info("Done.");

    logger.info("Removing foreign nodes...");
    Set<Id<Node>> nodesRemove = new HashSet<>();
    for (Id<Node> id : scenario.getNetwork().getNodes().keySet()) {
      if (id.toString().contains(".n")) {
        nodesRemove.add(id);
      }
    }

    for (Id<Node> id : nodesRemove) {
      scenario.getNetwork().removeNode(id);
    }
    logger.info("Done.");

    logger.info("Transforming node coordinates...");
    for (Node node : scenario.getNetwork().getNodes().values()) {
      double[] points = new double[] {node.getCoord().getX(), node.getCoord().getY()};
      try {
        transform.transform(points, 0, points, 0, 1);
      } catch (TransformException e) {
        e.printStackTrace();
      }

      ((NodeImpl) node).setCoord(new Coord(points[0], points[1]));
    }
    logger.info("Done.");

    logger.info("Writing network...");
    NetworkWriter nWriter = new NetworkWriter(scenario.getNetwork());
    nWriter.write(String.format("%s/network.xml.gz", outDir));
    logger.info("Done.");
  }
  @Test
  @Ignore
  public void testAveraging() {
    // yy this test is probably not doing anything with respect to some of the newer statistics,
    // such as money. kai, mar'14

    KNAnalysisEventsHandler testee = new KNAnalysisEventsHandler(this.scenario);

    EventsManager events = EventsUtils.createEventsManager();
    events.addHandler(testee);

    Leg leg = PopulationUtils.createLeg(TransportMode.car);
    leg.setDepartureTime(Time.parseTime("07:10:00"));
    leg.setTravelTime(Time.parseTime("07:30:00") - leg.getDepartureTime());
    testee.handleEvent(
        new PersonDepartureEvent(
            leg.getDepartureTime(), DEFAULT_PERSON_ID, DEFAULT_LINK_ID, leg.getMode()));
    testee.handleEvent(
        new PersonArrivalEvent(
            leg.getDepartureTime() + leg.getTravelTime(),
            DEFAULT_PERSON_ID,
            DEFAULT_LINK_ID,
            leg.getMode()));

    leg = PopulationUtils.createLeg(TransportMode.car);
    leg.setDepartureTime(Time.parseTime("07:00:00"));
    leg.setTravelTime(Time.parseTime("07:10:00") - leg.getDepartureTime());
    testee.handleEvent(
        new PersonDepartureEvent(
            leg.getDepartureTime(), DEFAULT_PERSON_ID, DEFAULT_LINK_ID, leg.getMode()));
    testee.handleEvent(
        new PersonArrivalEvent(
            leg.getDepartureTime() + leg.getTravelTime(),
            DEFAULT_PERSON_ID,
            DEFAULT_LINK_ID,
            leg.getMode()));

    leg = PopulationUtils.createLeg(TransportMode.car);
    leg.setDepartureTime(Time.parseTime("31:12:00"));
    leg.setTravelTime(Time.parseTime("31:22:00") - leg.getDepartureTime());
    testee.handleEvent(
        new PersonDepartureEvent(
            leg.getDepartureTime(), DEFAULT_PERSON_ID, DEFAULT_LINK_ID, leg.getMode()));
    testee.handleEvent(
        new PersonArrivalEvent(
            leg.getDepartureTime() + leg.getTravelTime(),
            DEFAULT_PERSON_ID,
            DEFAULT_LINK_ID,
            leg.getMode()));

    leg = PopulationUtils.createLeg(TransportMode.car);
    leg.setDepartureTime(Time.parseTime("30:12:00"));
    leg.setTravelTime(Time.parseTime("30:12:01") - leg.getDepartureTime());
    testee.handleEvent(
        new PersonDepartureEvent(
            leg.getDepartureTime(), DEFAULT_PERSON_ID, DEFAULT_LINK_ID, leg.getMode()));
    testee.handleEvent(
        new PersonArrivalEvent(
            leg.getDepartureTime() + leg.getTravelTime(),
            DEFAULT_PERSON_ID,
            DEFAULT_LINK_ID,
            leg.getMode()));

    this.runTest(testee);
  }