Beispiel #1
0
  @Override
  public void notifyAfterMobsim(AfterMobsimEvent event) {
    if (!trackIteration) return;

    try {
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

      Document document = documentBuilder.newDocument();
      Element schedules = document.createElement("services");
      document.appendChild(schedules);

      for (Service service : services) {
        schedules.appendChild(buildXmlService(document, service));
      }

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

      DOMSource source = new DOMSource(document);

      this.openFile(controlerIO.getIterationFilename(event.getIteration(), "av_services.xml.gz"));
      StreamResult result = new StreamResult(this.writer);

      transformer.transform(source, result);
    } catch (ParserConfigurationException
        | TransformerFactoryConfigurationError
        | TransformerException e) {
      throw new RuntimeException("Error while dumping AV schedules");
    } finally {
      this.close();
    }
  }
  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);
      }
    }
  }
  @Override
  public void notifyAfterMobsim(AfterMobsimEvent event) {
    Network network = event.getServices().getScenario().getNetwork();
    DescriptiveStatistics error = new DescriptiveStatistics();
    DescriptiveStatistics errorAbs = new DescriptiveStatistics();
    DescriptivePiStatistics errorWeighted = new WSMStatsFactory().newInstance();

    TDoubleArrayList errorVals = new TDoubleArrayList();
    TDoubleArrayList caps = new TDoubleArrayList();
    TDoubleArrayList speeds = new TDoubleArrayList();

    for (Count count : counts.getCounts().values()) {
      if (!count.getId().toString().startsWith(ODCalibrator.VIRTUAL_ID_PREFIX)) {
        double obsVal = 0;
        for (int i = 1; i < 25; i++) {
          obsVal += count.getVolume(i).getValue();
        }

        if (obsVal > 0) {
          double simVal = calculator.getOccupancy(count.getId());
          simVal *= factor;

          double err = (simVal - obsVal) / obsVal;

          error.addValue(err);
          errorAbs.addValue(Math.abs(err));
          errorWeighted.addValue(Math.abs(err), 1 / obsVal);

          Link link = network.getLinks().get(count.getId());
          errorVals.add(Math.abs(err));
          caps.add(link.getCapacity());
          speeds.add(link.getFreespeed());
        }
      }
    }

    logger.info(
        String.format(
            "Relative counts error: mean = %s, var = %s, stderr = %s, min = %s, max = %s",
            error.getMean(),
            error.getVariance(),
            error.getStandardDeviation(),
            error.getMin(),
            error.getMax()));
    logger.info(
        String.format(
            "Absolute relative counts error: mean = %s, var = %s, stderr = %s, min = %s, max = %s",
            errorAbs.getMean(),
            errorAbs.getVariance(),
            errorAbs.getStandardDeviation(),
            errorAbs.getMin(),
            errorAbs.getMax()));
    logger.info(
        String.format(
            "Absolute weigthed relative counts error: mean = %s, var = %s, stderr = %s, min = %s, max = %s",
            errorWeighted.getMean(),
            errorWeighted.getVariance(),
            errorWeighted.getStandardDeviation(),
            errorWeighted.getMin(),
            errorWeighted.getMax()));

    String outdir = event.getServices().getControlerIO().getIterationPath(event.getIteration());

    try {
      TDoubleDoubleHashMap map = Correlations.mean(caps.toArray(), errorVals.toArray());
      StatsWriter.writeHistogram(
          map, "capacity", "counts", String.format("%s/countsError.capacity.txt", outdir));

      map = Correlations.mean(speeds.toArray(), errorVals.toArray());
      StatsWriter.writeHistogram(
          map, "speed", "counts", String.format("%s/countsError.speed.txt", outdir));

      StatsWriter.writeHistogram(
          Histogram.createHistogram(error, new LinearDiscretizer(0.1), false),
          "Error",
          "Frequency",
          String.format("%s/countsError.hist.txt", outdir));
      StatsWriter.writeHistogram(
          Histogram.createHistogram(errorAbs, new LinearDiscretizer(0.1), false),
          "Error (absolute)",
          "Frequency",
          String.format("%s/countsErrorAbs.hist.txt", outdir));
      StatsWriter.writeHistogram(
          Histogram.createHistogram(errorWeighted, new LinearDiscretizer(0.1), true),
          "Error (weighted)",
          "Frequency",
          String.format("%s/countsErrorWeighted.hist.txt", outdir));

      CountsCompare2GeoJSON.write(calculator, counts, factor, network, outdir);
      NetworkLoad2GeoJSON.write(
          event.getServices().getScenario().getNetwork(),
          calculator,
          factor,
          outdir + "/network.json");
    } catch (Exception e) {
      e.printStackTrace();
    }

    String rootOutDir = event.getServices().getControlerIO().getOutputPath();
    boolean append = false;
    if (event.getIteration() > 0) {
      append = true;
    }
    writeErrorFile(error, String.format("%s/countsError.txt", rootOutDir), append);
    writeErrorFile(errorAbs, String.format("%s/countsAbsError.txt", rootOutDir), append);
  }
  @Override
  public void notifyAfterMobsim(AfterMobsimEvent event) {

    if (event.getIteration()
                % this.congestionInfo.getDecongestionConfigGroup().getWRITE_OUTPUT_ITERATION()
            == 0.
        || event.getIteration()
                % this.congestionInfo.getDecongestionConfigGroup().getUPDATE_PRICE_INTERVAL()
            == 0.) {
      computeDelays(event);
    }

    if (event.getIteration()
        == this.congestionInfo.getScenario().getConfig().controler().getFirstIteration()) {
      // skip first iteration

    } else if (event.getIteration()
            % this.congestionInfo.getDecongestionConfigGroup().getUPDATE_PRICE_INTERVAL()
        == 0.) {

      int totalNumberOfIterations =
          this.congestionInfo.getScenario().getConfig().controler().getLastIteration()
              - this.congestionInfo.getScenario().getConfig().controler().getFirstIteration();
      int iterationCounter =
          event.getIteration()
              - this.congestionInfo.getScenario().getConfig().controler().getFirstIteration();

      if (iterationCounter
              < this.congestionInfo
                      .getDecongestionConfigGroup()
                      .getFRACTION_OF_ITERATIONS_TO_END_PRICE_ADJUSTMENT()
                  * totalNumberOfIterations
          && iterationCounter
              > this.congestionInfo
                      .getDecongestionConfigGroup()
                      .getFRACTION_OF_ITERATIONS_TO_START_PRICE_ADJUSTMENT()
                  * totalNumberOfIterations) {

        log.info("+++ Iteration " + event.getIteration() + ". Update tolls per link and time bin.");
        tollComputation.updateTolls(event.getIteration());
      }
    }

    if (event.getIteration()
            % this.congestionInfo.getDecongestionConfigGroup().getWRITE_OUTPUT_ITERATION()
        == 0.) {
      CongestionInfoWriter.writeDelays(
          congestionInfo,
          event.getIteration(),
          this.congestionInfo.getScenario().getConfig().controler().getOutputDirectory()
              + "ITERS/it."
              + event.getIteration()
              + "/");
      CongestionInfoWriter.writeTolls(
          congestionInfo,
          event.getIteration(),
          this.congestionInfo.getScenario().getConfig().controler().getOutputDirectory()
              + "ITERS/it."
              + event.getIteration()
              + "/");
    }
  }