private SimpleFeature createFeature(
      Link link,
      GeometryFactory geofac,
      PolygonFeatureFactory factory,
      List<CountSimComparison> countSimLinkLeaveComparisonList,
      Double linkDelay1,
      Double linkDelay2) {
    Coordinate[] coords = PolygonFeatureGenerator.createPolygonCoordsForLink(link, 20.0);
    Object[] attribs = new Object[10 + 5 * (numberOfHours + 1) + 1];
    attribs[0] = link.getId().toString();
    attribs[1] = link.getFromNode().getId().toString();
    attribs[2] = link.getToNode().getId().toString();
    attribs[3] = link.getLength();
    attribs[4] = link.getFreespeed();
    attribs[5] = link.getCapacity();
    attribs[6] = link.getNumberOfLanes();
    attribs[7] = link.getNumberOfLanes();
    attribs[8] = ((LinkImpl) link).getType();
    // total delay caused by the link
    attribs[9] = linkDelay1;
    attribs[10] = linkDelay2;

    int i = 11;

    double sumAbsLinkLeaveDif = 0.0;
    double absLinkLeaveDif = 0.0;
    double sumAbsLinkLeaveRun1 = 0.0;
    double sumAbsLinkLeaveRun2 = 0.0;
    for (CountSimComparison csc : countSimLinkLeaveComparisonList) {
      // analyze only the selected time period
      if (csc.getHour() > firstHour && csc.getHour() <= lastHour) {
        // csc contains the number of link leave events in the time period between csc.getHour()-1
        // and csc.getHour()
        absLinkLeaveDif = csc.getSimulationValue() - csc.getCountValue();

        attribs[i] = csc.getCountValue();
        attribs[i + numberOfHours + 1] = csc.getSimulationValue();
        attribs[i + 2 * (numberOfHours + 1)] = absLinkLeaveDif;
        attribs[i + 3 * (numberOfHours + 1)] =
            (absLinkLeaveDif / link.getCapacity()) * 100; // in percent
        attribs[i + 4 * (numberOfHours + 1)] = absLinkLeaveDif * link.getLength();

        sumAbsLinkLeaveDif += absLinkLeaveDif;
        sumAbsLinkLeaveRun1 += csc.getCountValue();
        sumAbsLinkLeaveRun2 += csc.getSimulationValue();
        i++;
      }
    }
    attribs[10 + numberOfHours + 1] = sumAbsLinkLeaveRun1;
    attribs[10 + 2 * (numberOfHours + 1)] = sumAbsLinkLeaveRun2;
    attribs[10 + 3 * (numberOfHours + 1)] =
        sumAbsLinkLeaveDif; // C: meanAbsLinkLeaveDif = sumAbsLinkLeaveDif/5
    // mean (error/capacity) in percent per hour, i.e flow difference of the morning peak divided by
    // the maximal link capacity in this time period
    attribs[10 + 4 * (numberOfHours + 1)] = (sumAbsLinkLeaveDif / (link.getCapacity() * 5)) * 100;
    attribs[10 + 5 * (numberOfHours + 1)] =
        sumAbsLinkLeaveDif * link.getLength(); // alternative: meanAbsLinkLeaveDif*link.getLength();

    return factory.createPolygon(coords, attribs, link.getId().toString());
  }
 @Override
 public double getLinkMinimumTravelDisutility(Link link) {
   if (this.marginalUtlOfDistance == 0.0) {
     return (link.getLength() / link.getFreespeed()) * this.travelCostFactor;
   }
   return (link.getLength() / link.getFreespeed()) * this.travelCostFactor
       - this.marginalUtlOfDistance * link.getLength();
 }
 @Override
 public double getLinkTravelDisutility(
     final Link link, final double time, final Person person, final Vehicle vehicle) {
   if (this.marginalUtlOfDistance == 0.0) {
     return (link.getLength() / link.getFreespeed(time)) * this.travelCostFactor;
   }
   return (link.getLength() / link.getFreespeed(time)) * this.travelCostFactor
       - this.marginalUtlOfDistance * link.getLength();
 }
Пример #4
0
  @Override
  public double getLinkTravelDisutility(Link link, double time, Person person, Vehicle vehicle) {
    double travelTime = this.timeCalculator.getLinkTravelTime(link, time, person, vehicle);

    double marginalUtilityOfPerforming_util_s =
        -1.0
            * params.getScoringParameters(person)
                .marginalUtilityOfPerforming_s; // make negativ for router: it is lost
    double marginalUtilityOfTime_util_s =
        params.getScoringParameters(person).modeParams.get(this.mode).marginalUtilityOfTraveling_s
            + marginalUtilityOfPerforming_util_s;
    double marginalUtilityOfDistance_util_m =
        params.getScoringParameters(person).modeParams.get(this.mode).marginalUtilityOfDistance_m;
    double monetaryDistanceRate =
        params.getScoringParameters(person).modeParams.get(this.mode).monetaryDistanceCostRate;
    double marginalUtilityOfMoney = params.getScoringParameters(person).marginalUtilityOfMoney;
    final double marginalUtilityOfDistanceFromMoney_util_m =
        monetaryDistanceRate * marginalUtilityOfMoney; // [money/m]*[util/money]

    // Needs to be positive:
    return -1.0
        * (marginalUtilityOfTime_util_s * travelTime
            + (marginalUtilityOfDistance_util_m + marginalUtilityOfDistanceFromMoney_util_m)
                * link.getLength());
  }
  private void computeDelays(AfterMobsimEvent event) {

    TravelTime travelTime = event.getServices().getLinkTravelTimes();
    int timeBinSize =
        this.congestionInfo.getScenario().getConfig().travelTimeCalculator().getTraveltimeBinSize();

    for (Link link : this.congestionInfo.getScenario().getNetwork().getLinks().values()) {

      Map<Integer, Double> time2avgDelay = new HashMap<>();
      double freespeedTravelTime = link.getLength() / link.getFreespeed();

      int timeBinCounter = 0;
      for (int endTime = timeBinSize;
          endTime
              <= this.congestionInfo.getScenario().getConfig().travelTimeCalculator().getMaxTime();
          endTime = endTime + timeBinSize) {
        double avgDelay =
            travelTime.getLinkTravelTime(link, (endTime - timeBinSize / 2.), null, null)
                - freespeedTravelTime;
        time2avgDelay.put(timeBinCounter, avgDelay);
        timeBinCounter++;
      }

      if (this.congestionInfo.getlinkInfos().containsKey(link.getId())) {
        this.congestionInfo.getlinkInfos().get(link.getId()).setTime2avgDelay(time2avgDelay);
      } else {
        LinkInfo linkInfo = new LinkInfo(link.getId());
        linkInfo.setTime2avgDelay(time2avgDelay);
        this.congestionInfo.getlinkInfos().put(link.getId(), linkInfo);
      }
    }
  }
  // calculate generalized travel costs
  @Override
  public double getLinkTravelDisutility(
      final Link link, final double time, final Person person, final Vehicle vehicle) {
    Household household = this.personHouseholdMapping.getHousehold(person.getId());
    Income income = household.getIncome();
    double incomePerDay;
    if (income.getIncomePeriod().equals(IncomePeriod.year)) {
      // assumption: 240 working days per year
      incomePerDay = income.getIncome() / 240;
    } else {
      throw new UnsupportedOperationException("Can't calculate income per day");
    }

    double betaCost = betaIncomeCar / incomePerDay;
    double distance = link.getLength();
    double distanceCost = this.distanceCostFactor * distance;

    double travelTime = this.timeCalculator.getLinkTravelTime(link, time, person, vehicle);

    double generalizedDistanceCost = betaCost * distanceCost;
    double generalizedTravelTimeCost = this.betaTravelTime * travelTime;

    if (this.distanceCostFactor == 0.0) {
      return generalizedTravelTimeCost;
    }

    double generalizedTravelCost = generalizedDistanceCost + generalizedTravelTimeCost;
    return generalizedTravelCost;
  }
 private static double calculateFreespeedTravelTimeToNode(Network network, Path path, Node node) {
   double travelTime = 0.0;
   for (Link l : path.links) {
     travelTime += l.getLength() / l.getFreespeed();
   }
   return travelTime;
 }
Пример #8
0
 private Path convertNodeListtoPath(List<Node> nodelist, List<Link> linklist) {
   double traveltime = 0;
   for (Link l : linklist) {
     traveltime += l.getLength() / l.getFreespeed();
   }
   return new Path(nodelist, linklist, traveltime, 0);
 }
 @Override
 public double getLinkTravelDisutility(
     final Link link, final double time, final Person person, final Vehicle vehicle) {
   double disutility = 0.0;
   disutility +=
       this.marginalCostOfTime * this.travelTime.getLinkTravelTime(link, time, person, vehicle);
   disutility += this.marginalCostOfDistance * link.getLength();
   disutility += this.scc.getLinkTravelDisutility(link, time, person, vehicle);
   return disutility;
 }
Пример #10
0
 public void handleEvent(LinkLeaveEvent leave) {
   Double enterTime = this.enterTimes.remove(leave.getPersonId().toString());
   if (enterTime != null) {
     Link l = this.network.getLinks().get(leave.getLinkId());
     if (l != null) {
       this.lengthSum += l.getLength() / 1000.0;
       this.timeSum += (leave.getTime() - enterTime.doubleValue()) / 3600.0;
     }
   }
 }
Пример #11
0
  @Override
  public double getLinkMinimumTravelDisutility(Link link) {
    double constantPerforming = -6.0 / 3600.0; // this is a hack! TODO: take from config
    double marginalUtilityOfTime_util_s =
        params.getScoringParameters(null).modeParams.get(this.mode).marginalUtilityOfTraveling_s
            + constantPerforming;
    double marginalUtilityOfDistance_util_m =
        params.getScoringParameters(null).modeParams.get(this.mode).marginalUtilityOfDistance_m;
    double monetaryDistanceRate =
        params.getScoringParameters(null).modeParams.get(this.mode).monetaryDistanceCostRate;
    double marginalUtilityOfMoney = params.getScoringParameters(null).marginalUtilityOfMoney;
    final double marginalUtilityOfDistanceFromMoney_util_m =
        monetaryDistanceRate * marginalUtilityOfMoney; // [money/m]*[util/money]

    // Needs to be positive:
    return -1.0
        * (marginalUtilityOfTime_util_s * (link.getLength() / link.getFreespeed())
            + (marginalUtilityOfDistance_util_m + marginalUtilityOfDistanceFromMoney_util_m)
                * link.getLength());
  }
  private final void createVehicleLinkSpeedAttributes() {
    for (TransitLine transitLine : scenario.getTransitSchedule().getTransitLines().values()) {
      for (TransitRoute transitRoute : transitLine.getRoutes().values()) {
        Set<Id> vehIds = new HashSet<Id>();
        for (Departure departure : transitRoute.getDepartures().values()) {
          vehIds.add(departure.getVehicleId());
        }

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

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

          departure = routeStop.getDepartureOffset();
        }
      }
    }
  }
Пример #13
0
 public void add() {
   List<Link> links = ((BusLaneAdderPanel) layersPanels.get(PanelIds.ONE)).getLinks();
   Node prevNode = links.get(0).getFromNode();
   for (Link link : links)
     if (!link.getAllowedModes().contains("bus")) {
       exitSave();
       JOptionPane.showMessageDialog(this, "Wrong path, network saved");
     }
   for (int i = 0; i < links.size(); i++) {
     Link link = links.get(i);
     Node node = null;
     if (link.getNumberOfLanes() == 1) {
       Set<String> modes = new HashSet<String>();
       modes.add("bus");
       link.setAllowedModes(modes);
       node = link.getToNode();
     } else {
       Node oldNode = link.getToNode();
       if (i == links.size() - 1 || oldNode.getInLinks().size() + oldNode.getOutLinks().size() > 2)
         node = oldNode;
       else {
         node =
             network
                 .getFactory()
                 .createNode(
                     Id.createNodeId("fl" + oldNode.getId().toString()), oldNode.getCoord());
         network.addNode(node);
       }
       LinkImpl newLink =
           (LinkImpl)
               network
                   .getFactory()
                   .createLink(Id.createLinkId("fl" + link.getId().toString()), prevNode, node);
       Set<String> modes = new HashSet<String>();
       modes.add("car");
       newLink.setAllowedModes(modes);
       newLink.setCapacity(link.getCapacity());
       newLink.setFreespeed(link.getFreespeed());
       newLink.setLength(link.getLength());
       newLink.setNumberOfLanes(link.getNumberOfLanes() - 1);
       newLink.setOrigId(((LinkImpl) link).getOrigId());
       newLink.setType(((LinkImpl) link).getType());
       network.addLink(newLink);
       Set<String> modes2 = new HashSet<String>();
       modes2.add("bus");
       link.setAllowedModes(modes2);
       link.setCapacity(900);
       link.setNumberOfLanes(1);
     }
     prevNode = node;
   }
   ((BusLaneAdderPanel) layersPanels.get(PanelIds.ONE)).clearSelection();
 }
  private TransitRoute createRoute(
      Id<TransitRoute> routeID, TransitStopFacility startStop, TransitStopFacility endStop) {

    FreespeedTravelTimeAndDisutility tC = new FreespeedTravelTimeAndDisutility(-6.0, 0.0, 0.0);
    LeastCostPathCalculator routingAlgo = new Dijkstra(this.net, tC, tC);

    Node startNode = this.net.getLinks().get(startStop.getLinkId()).getToNode();
    Node endNode = this.net.getLinks().get(endStop.getLinkId()).getFromNode();

    int startTime = 0 * 3600;

    // get Route
    Path path = routingAlgo.calcLeastCostPath(startNode, endNode, startTime, null, null);
    NetworkRoute route = new LinkNetworkRouteImpl(startStop.getLinkId(), endStop.getLinkId());
    route.setLinkIds(
        startStop.getLinkId(), NetworkUtils.getLinkIds(path.links), endStop.getLinkId());

    // get stops at Route
    List<TransitRouteStop> stops = new LinkedList<TransitRouteStop>();

    // first stop
    TransitRouteStop routeStop =
        this.tS.getFactory().createTransitRouteStop(startStop, startTime, startTime);
    stops.add(routeStop);

    // additional stops
    for (Link link : path.links) {
      startTime += link.getLength() / link.getFreespeed();
      if (this.tS.getFacilities().get(link.getId()) == null) {
        continue;
      }
      routeStop =
          this.tS
              .getFactory()
              .createTransitRouteStop(
                  this.tS.getFacilities().get(link.getId()), startTime, startTime);
      stops.add(routeStop);
    }

    // last stop
    startTime +=
        this.net.getLinks().get(endStop.getLinkId()).getLength()
            / this.net.getLinks().get(endStop.getLinkId()).getFreespeed();
    routeStop = this.tS.getFactory().createTransitRouteStop(endStop, startTime, startTime);
    stops.add(routeStop);

    // register departure
    TransitRoute transitRoute =
        this.tS.getFactory().createTransitRoute(routeID, route, stops, "pt");

    return transitRoute;
  }
Пример #15
0
  public static void main(String[] args) {
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario.getNetwork());
    networkReader.readFile(args[0]);

    int numberOfLinks = 0;
    double length = 0.0;
    double length1 = 0.0;
    double length2 = 0.0;
    double length3 = 0.0;
    Node previousNode1 = null;
    Node previousNode2 = null;
    for (Link l : scenario.getNetwork().getLinks().values()) {
      if (previousNode1 != null) {

        if (l.getFromNode().getId() != previousNode2.getId()
            && l.getToNode().getId() != previousNode1.getId()) {
          numberOfLinks++;
          length += l.getLength();
          if (l.getFreespeed() > 24.99) {
            length1 += l.getLength();
          } else if (l.getFreespeed() < 13.88) {
            length3 += l.getLength();

          } else length2 += l.getLength();
        }
      } else {
        numberOfLinks++;
        length += l.getLength();
        if (l.getFreespeed() > 24.99) {
          length1 += l.getLength();
        } else if (l.getFreespeed() < 13.88) {
          length3 += l.getLength();

        } else length2 += l.getLength();
      }
      previousNode1 = l.getFromNode();
      previousNode2 = l.getToNode();
    }
    System.out.println(numberOfLinks);
    System.out.println(length / 1000);
    System.out.println(length1 / 1000);
    System.out.println(length2 / 1000);
    System.out.println(length3 / 1000);
  }
  public static double getSearchTime(AgentWithParking aem, Id parkingId) {
    Link currentLink = aem.getCurrentLink();
    double travelTime =
        ZHScenarioGlobal.ttMatrix.getTravelTime(aem.getMessageArrivalTime(), currentLink.getId());
    double speed = currentLink.getLength() / travelTime;

    Id linkOfParking = AgentWithParking.parkingManager.getLinkOfParking(parkingId);
    double distance =
        GeneralLib.getDistance(
            ZHScenarioGlobal.scenario.getNetwork().getLinks().get(linkOfParking).getCoord(),
            currentLink.getCoord());

    double searchTime =
        distance / speed * ZHScenarioGlobal.loadDoubleParam("Dummy_SearchTimeFactor");
    return searchTime;
  }
Пример #17
0
  public double getEnergyConsumptionForLinkInJoule(
      Vehicle vehicle, double timeSpentOnLink, Link link) {
    double speedOfVehicleOnLinkInKmPerHour =
        Vehicle.getAverageSpeedOfVehicleOnLinkInMetersPerSecond(timeSpentOnLink, link)
            / 1000
            * 3600;

    if (speedOfVehicleOnLinkInKmPerHour > maxAllowedSpeedInNetworkInKmPerHour) {
      return 0;
    }

    return energyConsumptionTable.getEnergyConsumptionInJoule(
        vehicle.getVehicleClassId(),
        speedOfVehicleOnLinkInKmPerHour,
        link.getFreespeed(),
        link.getLength());
  }
Пример #18
0
  public void convertNet2Shape(Network net, String crs, String outputFile) {

    SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
    typeBuilder.setCRS(MGC.getCRS(crs));
    typeBuilder.setName("link feature");
    typeBuilder.add("Line String", LineString.class);
    typeBuilder.add("id", String.class);
    typeBuilder.add("length", Double.class);
    typeBuilder.add("freespeed", Double.class);
    typeBuilder.add("capacity", Double.class);
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(typeBuilder.buildFeatureType());

    List<SimpleFeature> features = new ArrayList<SimpleFeature>();

    for (Link link : net.getLinks().values()) {

      Coord from = link.getFromNode().getCoord();
      Coord to = link.getToNode().getCoord();

      SimpleFeature feature =
          builder.buildFeature(
              link.getId().toString(),
              new Object[] {
                new GeometryFactory()
                    .createLineString(
                        new Coordinate[] {MGC.coord2Coordinate(from), MGC.coord2Coordinate(to)}),
                link.getId().toString(),
                link.getLength(),
                link.getFreespeed(),
                link.getCapacity()
              });
      features.add(feature);
    }

    ShapeFileWriter.writeGeometries(features, outputFile);
  }
 @Override
 public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) {
   return link.getLength() / link.getFreespeed(time);
 }
Пример #20
0
  public TransitRouteData(Network network, TransitRoute transitRoute) {

    this.transportMode = transitRoute.getTransportMode();

    this.firstDeparture = Double.MAX_VALUE;
    this.lastDeparture = -Double.MAX_VALUE;
    this.vehIds = new TreeSet<String>();
    this.numberOfDepartures = 0;

    for (Departure departure : transitRoute.getDepartures().values()) {
      this.firstDeparture = Math.min(this.firstDeparture, departure.getDepartureTime());
      this.lastDeparture = Math.max(this.lastDeparture, departure.getDepartureTime());
      this.vehIds.add(departure.getVehicleId().toString());
      this.numberOfDepartures++;
    }

    this.firstStop = transitRoute.getStops().get(0).getStopFacility();
    this.lastStop =
        transitRoute.getStops().get(transitRoute.getStops().size() - 1).getStopFacility();

    if (this.firstStop == this.lastStop) {
      // get the stop location of stop with the largest distance between first and last stop
      TransitStopFacility currentViaStop = null;
      double currentViaDistance = Double.NEGATIVE_INFINITY;
      for (TransitRouteStop stop : transitRoute.getStops()) {
        double distanceFirstPotentialVia =
            CoordUtils.calcDistance(this.firstStop.getCoord(), stop.getStopFacility().getCoord());
        double distanceLastProtenialVia =
            CoordUtils.calcDistance(this.lastStop.getCoord(), stop.getStopFacility().getCoord());
        double newDistance =
            Math.sqrt(
                Math.pow(distanceFirstPotentialVia, 2) + Math.pow(distanceLastProtenialVia, 2));

        if (newDistance > currentViaDistance) {
          // this one is farther away - keep it
          currentViaStop = stop.getStopFacility();
          currentViaDistance = newDistance;
        }
      }
      this.viaStop = currentViaStop;
    } else {
      // get the stop in the middle of the line
      this.viaStop =
          transitRoute.getStops().get((int) (transitRoute.getStops().size() / 2)).getStopFacility();
    }

    // calculate the length of the route
    double distance = 0.0;
    double freeSpeedTravelTime = 0.0;
    for (Id<Link> linkId : transitRoute.getRoute().getLinkIds()) {
      Link link = network.getLinks().get(linkId);
      distance += link.getLength();
      freeSpeedTravelTime += link.getLength() / link.getFreespeed();
    }
    // add last link but not the first link
    Link link = network.getLinks().get(transitRoute.getRoute().getEndLinkId());
    distance += link.getLength();
    freeSpeedTravelTime += link.getLength() / link.getFreespeed();

    this.distance = distance;
    this.freeSpeedTravelTime = freeSpeedTravelTime;

    this.travelTime =
        transitRoute.getStops().get(transitRoute.getStops().size() - 1).getArrivalOffset();

    this.avgSpeed = this.distance / this.travelTime;
  }
Пример #21
0
  public static void main(String[] args) {
    // Parameters
    Integer planningAreaId = 11000000;

    boolean onlyCar = false; // car; new, should be used for runs with ChangeLedModes enabled

    boolean onlyInterior = false; // int
    boolean onlyBerlinBased = true; // ber; usually varied for analysis

    boolean distanceFilter = true; // dist; usually varied for analysis
    // double minDistance = 0;
    double maxDistance = 100;

    boolean onlyWorkTrips = false; // NEW

    // --------------------------------------------------------------------------------------------------
    boolean ageFilter = false;
    Integer minAge = 80;
    Integer maxAge = 119;
    // --------------------------------------------------------------------------------------------------

    String runId = "run_168a";
    //		String runId = "run791";
    String usedIteration = "300"; // most frequently used value: 150
    //		String usedIteration = "600";

    int maxBinDuration = 120;
    int binWidthDuration = 1;
    // int binWidthDuration = 5;

    int maxBinTime = 23;
    int binWidthTime = 1;

    int maxBinDistance = 60;
    int binWidthDistance = 1;
    // int binWidthDistance = 5;

    int maxBinSpeed = 60;
    int binWidthSpeed = 1;
    // int binWidthSpeed = 5;

    // Input and output files
    String networkFile =
        "/Users/dominik/Workspace/shared-svn/studies/countries/de/berlin/counts/iv_counts/network.xml";
    //	    String networkFile =
    // "D:/Workspace/shared-svn/studies/countries/de/berlin/counts/iv_counts/network.xml";
    //	    String networkFile = "D:/Workspace/runs-svn/"  + runId +
    // "/counts_network_merged.xml_cl.xml.gz";

    //	    String eventsFile = "D:/Workspace/data/cemdapMatsimCadyts/output/" + runId + "/ITERS/it."
    // + usedIteration + "/"
    //	    String eventsFile = "D:/Workspace/runs-svn/" + runId + "/output_rerun/ITERS/it." +
    // usedIteration + "/"
    //	    		+ runId + "." + usedIteration + ".events.txt.gz";
    //	    String eventsFile = "D:/Workspace/runs-svn/cemdapMatsimCadyts/" + runId + "/ITERS/it." +
    // usedIteration + "/"
    //				+ runId + "." + usedIteration + ".events.xml.gz";
    String eventsFile =
        "/Users/dominik/Workspace/runs-svn/cemdapMatsimCadyts/"
            + runId
            + "/ITERS/it."
            + usedIteration
            + "/"
            + runId
            + "."
            + usedIteration
            + ".events.xml.gz";

    //	    String cemdapPersonFile =
    // "D:/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/19/persons1.dat"; // wrong!!!
    //	    String cemdapPersonFile =
    // "D:/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/18/persons1.dat";
    //	    String cemdapPersonFile =
    // "D:/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/21/persons1.dat";
    String cemdapPersonFile =
        "/Users/dominik/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/21/persons1.dat";

    // String outputDirectory = "D:/Workspace/data/cemdapMatsimCadyts/output/" + runId +
    // "/analysis";
    //	    String outputDirectory = "D:/Workspace/runs-svn/cemdapMatsimCadyts/" + runId +
    // "/analysis";
    String outputDirectory =
        "/Users/dominik/Workspace/runs-svn/cemdapMatsimCadyts/" + runId + "/analysis";
    //	    String outputDirectory = "D:/Workspace/runs-svn/other/" + runId + "/analysis";

    //	    String shapeFileBerlin =
    // "D:/Workspace/data/cemdapMatsimCadyts/input/shapefiles/Berlin_DHDN_GK4.shp";
    String shapeFileBerlin =
        "/Users/dominik/Workspace/data/cemdapMatsimCadyts/input/shapefiles/Berlin_DHDN_GK4.shp";
    Map<Integer, Geometry> zoneGeometries = ShapeReader.read(shapeFileBerlin, "NR");
    Geometry berlinGeometry = zoneGeometries.get(planningAreaId);

    // Output naming
    Integer usedIt = Integer.parseInt(usedIteration);
    if (!usedIt.equals(150)) {
      outputDirectory = outputDirectory + "_" + usedIteration;
    }

    // --------------------------------------------------------------------------------------------------
    if (onlyCar == true) {
      outputDirectory = outputDirectory + "_car";
    }
    // --------------------------------------------------------------------------------------------------

    if (onlyInterior == true) {
      outputDirectory = outputDirectory + "_int";
    }

    if (onlyBerlinBased == true) {
      outputDirectory = outputDirectory + "_ber";
    }

    if (distanceFilter == true) {
      outputDirectory = outputDirectory + "_dist";
    }

    // --------------------------------------------------------------------------------------------------
    if (onlyWorkTrips == true) {
      outputDirectory = outputDirectory + "_work";
    }
    // --------------------------------------------------------------------------------------------------

    // --------------------------------------------------------------------------------------------------
    if (ageFilter == true) {
      outputDirectory = outputDirectory + "_" + minAge.toString();
      outputDirectory = outputDirectory + "_" + maxAge.toString();
    }
    // --------------------------------------------------------------------------------------------------

    // Create an EventsManager instance (MATSim infrastructure)
    EventsManager eventsManager = EventsUtils.createEventsManager();
    TripHandler handler = new TripHandler();
    eventsManager.addHandler(handler);

    // Connect a file reader to the EventsManager and read in the event file
    MatsimEventsReader reader = new MatsimEventsReader(eventsManager);
    reader.readFile(eventsFile);
    System.out.println("Events file read!");

    // check if all trips have been completed; if so, result will be zero
    int numberOfIncompleteTrips = 0;
    for (Trip trip : handler.getTrips().values()) {
      if (!trip.getTripComplete()) {
        numberOfIncompleteTrips++;
      }
    }
    System.out.println(numberOfIncompleteTrips + " trips are incomplete.");

    // --------------------------------------------------------------------------------------------------
    CemdapPersonFileReader cemdapPersonFileReader = new CemdapPersonFileReader();
    if (ageFilter == true) {
      // TODO needs to be adapted for other analyses that are based on person-specific attributes as
      // well
      // so far age is the only one
      // parse person file

      cemdapPersonFileReader.parse(cemdapPersonFile);
    }
    // --------------------------------------------------------------------------------------------------

    // get network, which is needed to calculate distances
    Config config = ConfigUtils.createConfig();
    Scenario scenario = ScenarioUtils.createScenario(config);
    MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario);
    networkReader.readFile(networkFile);
    Network network = scenario.getNetwork();

    // create objects
    int tripCounter = 0;
    int tripCounterSpeed = 0;
    int tripCounterIncomplete = 0;

    Map<Integer, Double> tripDurationMap = new TreeMap<Integer, Double>();
    double aggregateTripDuration = 0.;

    Map<Integer, Double> departureTimeMap = new TreeMap<Integer, Double>();

    Map<String, Double> activityTypeMap = new TreeMap<String, Double>();

    Map<Integer, Double> tripDistanceRoutedMap = new TreeMap<Integer, Double>();
    double aggregateTripDistanceRouted = 0.;

    Map<Integer, Double> tripDistanceBeelineMap = new TreeMap<Integer, Double>();
    double aggregateTripDistanceBeeline = 0.;

    Map<Integer, Double> averageTripSpeedRoutedMap = new TreeMap<Integer, Double>();
    double aggregateOfAverageTripSpeedsRouted = 0.;

    Map<Integer, Double> averageTripSpeedBeelineMap = new TreeMap<Integer, Double>();
    double aggregateOfAverageTripSpeedsBeeline = 0.;

    int numberOfTripsWithNoCalculableSpeed = 0;

    Map<Id<Trip>, Double> distanceRoutedMap = new TreeMap<Id<Trip>, Double>();
    Map<Id<Trip>, Double> distanceBeelineMap = new TreeMap<Id<Trip>, Double>();

    Map<String, Integer> otherInformationMap = new TreeMap<String, Integer>();

    // --------------------------------------------------------------------------------------------------
    ObjectAttributes personActivityAttributes = new ObjectAttributes();
    // --------------------------------------------------------------------------------------------------

    // do calculations
    for (Trip trip : handler.getTrips().values()) {
      if (trip.getTripComplete()) {
        boolean considerTrip = false;

        // get coordinates of links
        Id<Link> departureLinkId = trip.getDepartureLinkId();
        Id<Link> arrivalLinkId = trip.getArrivalLinkId();

        Link departureLink = network.getLinks().get(departureLinkId);
        Link arrivalLink = network.getLinks().get(arrivalLinkId);

        double arrivalCoordX = arrivalLink.getCoord().getX();
        double arrivalCoordY = arrivalLink.getCoord().getY();
        double departureCoordX = departureLink.getCoord().getX();
        double departureCoordY = departureLink.getCoord().getY();

        // calculate (beeline) distance
        double horizontalDistanceInMeter = (Math.abs(departureCoordX - arrivalCoordX)) / 1000;
        double verticalDistanceInMeter = (Math.abs(departureCoordY - arrivalCoordY)) / 1000;

        double tripDistanceBeeline =
            Math.sqrt(
                horizontalDistanceInMeter * horizontalDistanceInMeter
                    + verticalDistanceInMeter * verticalDistanceInMeter);

        // create points
        Point arrivalLocation = MGC.xy2Point(arrivalCoordX, arrivalCoordY);
        Point departureLocation = MGC.xy2Point(departureCoordX, departureCoordY);

        // choose if trip will be considered
        // Note: Check of "interior"/"berlinBased" has to come first since this sets the
        // "considerTrip"
        // variable to true.
        if (onlyInterior == true) {
          if (berlinGeometry.contains(arrivalLocation)
              && berlinGeometry.contains(departureLocation)) {
            considerTrip = true;
          }
        } else if (onlyBerlinBased == true) {
          if (berlinGeometry.contains(arrivalLocation)
              || berlinGeometry.contains(departureLocation)) {
            considerTrip = true;
          }
        } else {
          considerTrip = true;
        }

        // --------------------------------------------------------------------------------------------------
        //				if (!trip.getMode().equals("car") && !trip.getMode().equals("pt")) {
        //					throw new RuntimeException("In current implementation leg mode must either be car or
        // pt");
        //				}

        if (onlyCar == true) {
          if (!trip.getMode().equals("car")) {
            considerTrip = false;
          }
        }
        // --------------------------------------------------------------------------------------------------

        if (distanceFilter == true && tripDistanceBeeline >= maxDistance) {
          considerTrip = false;
        }

        //	    		if (distanceFilter == true && tripDistanceBeeline <= minDistance) {
        //	    			considerTrip = false;
        //	    		}

        // --------------------------------------------------------------------------------------------------------------------
        if (onlyWorkTrips == true) {
          boolean doesWorkTrip = false;
          if (trip.getActivityEndActType().equals("work")) {
            doesWorkTrip = true;
          }

          if (doesWorkTrip == true) { // can be varied
            considerTrip = false;
          }
        }
        // --------------------------------------------------------------------------------------------------------------------

        // write person activity attributes
        //	    		if (trip.getActivityEndActType().equals("work")) {
        //	    			personActivityAttributes.putAttribute(trip.getDriverId(), "hasWorkActivity",
        // true);
        //	    		}
        // TODO The plan was to claculated activity-chain frequencies here...

        // --------------------------------------------------------------------------------------------------
        // PERSON-SPECIFIC ATTRIBUTES
        if (ageFilter == true) {
          // TODO needs to be adapted for other analyses that are based on person-specific
          // attributes as well
          // so far age is the only one
          String personId = trip.getPersonId().toString();
          int age =
              (int) cemdapPersonFileReader.getPersonAttributes().getAttribute(personId, "age");

          if (age < minAge) {
            considerTrip = false;
          }
          if (age > maxAge) {
            considerTrip = false;
          }
        }
        // --------------------------------------------------------------------------------------------------

        if (considerTrip == true) {
          tripCounter++;

          // calculate travel times and store them in a map
          // trip.getArrivalTime() / trip.getDepartureTime() yields values in seconds!
          double departureTimeInSeconds = trip.getDepartureTime();
          double arrivalTimeInSeconds = trip.getArrivalTime();
          double tripDurationInSeconds = arrivalTimeInSeconds - departureTimeInSeconds;
          double tripDurationInMinutes = tripDurationInSeconds / 60.;
          double tripDurationInHours = tripDurationInMinutes / 60.;
          // addToMapIntegerKey(tripDurationMap, tripDurationInMinutes, 5, 120);
          addToMapIntegerKey(
              tripDurationMap, tripDurationInMinutes, binWidthDuration, maxBinDuration, 1.);
          aggregateTripDuration = aggregateTripDuration + tripDurationInMinutes;

          // store departure times in a map
          double departureTimeInHours = departureTimeInSeconds / 3600.;
          addToMapIntegerKey(departureTimeMap, departureTimeInHours, binWidthTime, maxBinTime, 1.);

          // store activities in a map
          String activityType = trip.getActivityStartActType();
          addToMapStringKey(activityTypeMap, activityType);

          // calculate (routed) distances and and store them in a map
          double tripDistanceMeter = 0.;
          for (int i = 0; i < trip.getLinks().size(); i++) {
            Id<Link> linkId = trip.getLinks().get(i);
            Link link = network.getLinks().get(linkId);
            double length = link.getLength();
            tripDistanceMeter = tripDistanceMeter + length;
          }
          // TODO here, the distances from activity to link and link to activity are missing!
          double tripDistanceRouted = tripDistanceMeter / 1000.;

          // store (routed) distances  in a map
          addToMapIntegerKey(
              tripDistanceRoutedMap, tripDistanceRouted, binWidthDistance, maxBinDistance, 1.);
          aggregateTripDistanceRouted = aggregateTripDistanceRouted + tripDistanceRouted;
          distanceRoutedMap.put(trip.getTripId(), tripDistanceRouted);

          // store (beeline) distances in a map
          addToMapIntegerKey(
              tripDistanceBeelineMap, tripDistanceBeeline, binWidthDistance, maxBinDistance, 1.);
          aggregateTripDistanceBeeline = aggregateTripDistanceBeeline + tripDistanceBeeline;
          distanceBeelineMap.put(trip.getTripId(), tripDistanceBeeline);

          // calculate speeds and and store them in a map
          if (tripDurationInHours > 0.) {
            // System.out.println("trip distance is " + tripDistance + " and time is " +
            // timeInHours);
            double averageTripSpeedRouted = tripDistanceRouted / tripDurationInHours;
            addToMapIntegerKey(
                averageTripSpeedRoutedMap, averageTripSpeedRouted, binWidthSpeed, maxBinSpeed, 1.);
            aggregateOfAverageTripSpeedsRouted =
                aggregateOfAverageTripSpeedsRouted + averageTripSpeedRouted;

            double averageTripSpeedBeeline = tripDistanceBeeline / tripDurationInHours;
            addToMapIntegerKey(
                averageTripSpeedBeelineMap,
                averageTripSpeedBeeline,
                binWidthSpeed,
                maxBinSpeed,
                1.);
            aggregateOfAverageTripSpeedsBeeline =
                aggregateOfAverageTripSpeedsBeeline + averageTripSpeedBeeline;

            tripCounterSpeed++;
          } else {
            numberOfTripsWithNoCalculableSpeed++;
          }
        }
      } else {
        System.err.println("Trip is not complete!");
        tripCounterIncomplete++;
        // Until now, the only case where incomplete trips happen is when agents are removed
        // according to "removeStuckVehicles = true"
        // Since a removed agent can at most have one incomplete trip (this incomplete trip is
        // exactly the event when he is removed)
        // the number of incomplete trips should be equal to the number of removed agents
      }
    }

    double averageTripDuration = aggregateTripDuration / tripCounter;
    double averageTripDistanceRouted = aggregateTripDistanceRouted / tripCounter;
    double averageTripDistanceBeeline = aggregateTripDistanceBeeline / tripCounter;
    double averageOfAverageTripSpeedsRouted = aggregateOfAverageTripSpeedsRouted / tripCounterSpeed;
    double averageOfAverageTripSpeedsBeeline =
        aggregateOfAverageTripSpeedsBeeline / tripCounterSpeed;

    otherInformationMap.put(
        "Number of trips that have no previous activity",
        handler.getNoPreviousEndOfActivityCounter());
    otherInformationMap.put(
        "Number of trips that have no calculable speed", numberOfTripsWithNoCalculableSpeed);
    otherInformationMap.put(
        "Number of incomplete trips (i.e. number of removed agents)", tripCounterIncomplete);
    otherInformationMap.put("Number of (complete) trips", tripCounter);

    // write results to files
    new File(outputDirectory).mkdir();
    AnalysisFileWriter writer = new AnalysisFileWriter();
    writer.writeToFileIntegerKey(
        tripDurationMap,
        outputDirectory + "/tripDuration.txt",
        binWidthDuration,
        tripCounter,
        averageTripDuration);
    writer.writeToFileIntegerKey(
        departureTimeMap,
        outputDirectory + "/departureTime.txt",
        binWidthTime,
        tripCounter,
        averageTripDuration);
    writer.writeToFileStringKey(
        activityTypeMap, outputDirectory + "/activityTypes.txt", tripCounter);
    writer.writeToFileIntegerKey(
        tripDistanceRoutedMap,
        outputDirectory + "/tripDistanceRouted.txt",
        binWidthDistance,
        tripCounter,
        averageTripDistanceRouted);
    writer.writeToFileIntegerKey(
        tripDistanceBeelineMap,
        outputDirectory + "/tripDistanceBeeline.txt",
        binWidthDistance,
        tripCounter,
        averageTripDistanceBeeline);
    writer.writeToFileIntegerKey(
        averageTripSpeedRoutedMap,
        outputDirectory + "/averageTripSpeedRouted.txt",
        binWidthSpeed,
        tripCounterSpeed,
        averageOfAverageTripSpeedsRouted);
    writer.writeToFileIntegerKey(
        averageTripSpeedBeelineMap,
        outputDirectory + "/averageTripSpeedBeeline.txt",
        binWidthSpeed,
        tripCounterSpeed,
        averageOfAverageTripSpeedsBeeline);
    writer.writeToFileIntegerKeyCumulative(
        tripDurationMap,
        outputDirectory + "/tripDurationCumulative.txt",
        binWidthDuration,
        tripCounter,
        averageTripDuration);
    writer.writeToFileIntegerKeyCumulative(
        tripDistanceBeelineMap,
        outputDirectory + "/tripDistanceBeelineCumulative.txt",
        binWidthDistance,
        tripCounter,
        averageTripDistanceBeeline);
    writer.writeToFileIntegerKeyCumulative(
        averageTripSpeedBeelineMap,
        outputDirectory + "/averageTripSpeedBeelineCumulative.txt",
        binWidthSpeed,
        tripCounterSpeed,
        averageOfAverageTripSpeedsBeeline);
    writer.writeToFileOther(otherInformationMap, outputDirectory + "/otherInformation.txt");

    // write a routed distance vs. beeline distance comparison file
    writer.writeRoutedBeelineDistanceComparisonFile(
        distanceRoutedMap, distanceBeelineMap, outputDirectory + "/beeline.txt", tripCounter);
  }
Пример #22
0
  public static void main(String[] args) {
    // Input file
    String networkFile = "D:/Workspace/container/demand/input/iv_counts/network.xml";

    // Get network, which is needed to calculate distances
    Config config = ConfigUtils.createConfig();
    Scenario scenario = ScenarioUtils.createScenario(config);
    MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario);
    networkReader.readFile(networkFile);
    Network network = scenario.getNetwork();

    // Create needed objects
    int numberOfNodes = 0;
    int numberOfLinks = 0;

    Map<Double, Integer> capacityMap = new HashMap<Double, Integer>();

    int capacity0To1000 = 0;
    int capacity1000To2000 = 0;
    int capacity2000To3000 = 0;
    int capacity3000To4000 = 0;
    int capacity4000To5000 = 0;
    int capacity5000ToInf = 0;

    Map<Double, Integer> freeSpeedMap = new HashMap<Double, Integer>();
    Map<Double, Integer> numberOfLanesMap = new HashMap<Double, Integer>();

    int linksWithMoreThanOneMode = 0;

    double maxLength = Integer.MIN_VALUE;
    double minLength = Integer.MAX_VALUE;

    // Do calculations
    for (Node node : network.getNodes().values()) {
      numberOfNodes++;
    }

    for (Link link : network.getLinks().values()) {
      numberOfLinks++;

      double capacity = link.getCapacity();
      if (!capacityMap.containsKey(capacity)) {
        capacityMap.put(capacity, 1);
      } else {
        int quantityCapacity = capacityMap.get(capacity);
        capacityMap.put(capacity, quantityCapacity + 1);
      }
      if (capacity < 1000) {
        capacity0To1000++;
      } else if (capacity >= 1000 && capacity < 2000) {
        capacity1000To2000++;
      } else if (capacity >= 2000 && capacity < 3000) {
        capacity2000To3000++;
      } else if (capacity >= 3000 && capacity < 4000) {
        capacity3000To4000++;
      } else if (capacity >= 4000 && capacity < 5000) {
        capacity4000To5000++;
      } else if (capacity >= 5000) {
        capacity5000ToInf++;
      } else {
        System.err.println("Error!");
      }

      double freeSpeed = link.getFreespeed();
      if (!freeSpeedMap.containsKey(freeSpeed)) {
        freeSpeedMap.put(freeSpeed, 1);
      } else {
        int quantityFreeSpeed = freeSpeedMap.get(freeSpeed);
        freeSpeedMap.put(freeSpeed, quantityFreeSpeed + 1);
      }

      double numberOfLanes = link.getNumberOfLanes();
      if (!numberOfLanesMap.containsKey(numberOfLanes)) {
        numberOfLanesMap.put(numberOfLanes, 1);
      } else {
        int quantityNumberOfLanes = numberOfLanesMap.get(numberOfLanes);
        numberOfLanesMap.put(numberOfLanes, quantityNumberOfLanes + 1);
      }

      if (link.getAllowedModes().size() > 1) {
        linksWithMoreThanOneMode++;
      }

      double length = link.getLength();
      if (length > maxLength) {
        maxLength = length;
      }
      if (length < minLength) {
        minLength = length;
      }
    }

    // Write information to console
    System.out.println("Number of Nodes: " + numberOfNodes);
    System.out.println("Number of Links: " + numberOfLinks);

    for (Double capacity : capacityMap.keySet()) {
      System.out.println(capacityMap.get(capacity) + " links have a capacity of " + capacity + ".");
    }

    System.out.println(capacity0To1000 + " links have a capacity of less than 1000.");
    System.out.println(
        capacity1000To2000 + " links have a capacity of at least 1000 and less than 2000.");
    System.out.println(
        capacity2000To3000 + " links have a capacity of at least 2000 and less than 3000.");
    System.out.println(
        capacity3000To4000 + " links have a capacity of at least 3000 and less than 4000.");
    System.out.println(
        capacity4000To5000 + " links have a capacity of at least 4000 and less than 5000.");
    System.out.println(capacity5000ToInf + " links have a capacity of at least 5000.");

    for (Double freeSpeed : freeSpeedMap.keySet()) {
      System.out.println(
          freeSpeedMap.get(freeSpeed)
              + " links have a free speed of "
              + freeSpeed
              + " / "
              + freeSpeed * 3.6
              + ".");
    }

    for (Double numberOfLanes : numberOfLanesMap.keySet()) {
      System.out.println(
          numberOfLanesMap.get(numberOfLanes) + " links have " + numberOfLanes + " lanes.");
    }

    System.out.println(linksWithMoreThanOneMode + " links allow more than one mode.");

    System.out.println("Maximum link length is: " + maxLength);
    System.out.println("Minimum link length is: " + minLength);
  }
Пример #23
0
  public QSimDensityDrawer(Scenario sc) {
    for (Link l : sc.getNetwork().getLinks().values()) {
      if (l.getId().toString().contains("jps")
          || l.getId().toString().contains("el")
          || l.getAllowedModes().contains("walk2d")
          || l.getCapacity() >= 100000
          || l.getFreespeed() > 100
          || l.getId().toString().contains("el")) {
        continue;
      }

      float width = (float) (l.getCapacity() / sc.getNetwork().getCapacityPeriod() / 1.3);

      boolean isCar = false;
      if (l.getFreespeed() > 1.35) {
        width = (float) (l.getNumberOfLanes() * 3.5);
        isCar = true;
      } else {
        width = (float) (width);
      }

      double dx = l.getToNode().getCoord().getX() - l.getFromNode().getCoord().getX();
      double dy = l.getToNode().getCoord().getY() - l.getFromNode().getCoord().getY();
      double length = Math.sqrt(dx * dx + dy * dy);
      dx /= length;
      dy /= length;
      LinkInfo info = new LinkInfo();

      info.id = l.getId();
      info.cap =
          (l.getLength() / ((NetworkImpl) sc.getNetwork()).getEffectiveCellSize())
              * l.getNumberOfLanes();

      double x0 = l.getFromNode().getCoord().getX();
      double y0 = l.getFromNode().getCoord().getY();

      double x1 = l.getToNode().getCoord().getX();
      double y1 = l.getToNode().getCoord().getY();

      x0 += dy * width / 2;
      x1 += dy * width / 2;
      y0 -= dx * width / 2;
      y1 -= dx * width / 2;

      info.width = width;
      info.x0 = x0;
      info.x1 = x1;
      info.y0 = y0;
      info.y1 = y1;

      double tan = dx / dy;
      double atan = Math.atan(tan);
      if (atan > 0) {
        atan -= Math.PI / 2;
      } else {
        atan += Math.PI / 2;
      }

      double offsetX = dy * .075;
      double offsetY = -dx * .075;
      if (dx > 0) {
        offsetX *= -1;
        offsetY *= -1;
      }

      info.tx = (x0 + x1) / 2 + offsetX;
      info.ty = (y0 + y1) / 2 + offsetY;
      info.text = "0";
      info.atan = atan;
      info.isCar = isCar;
      if (isCar) {
        info.cap = l.getLength() / 7.5 * l.getNumberOfLanes();
      }

      this.links.add(info);
      this.map.put(l.getId(), info);
    }
  }