public boolean isFitForAggregation(Point point) {

    boolean result = false;

    for (String propertyName : GlobalProperties.getPropertiesOfInterestDatabase().keySet()) {

      Object numberObject = point.getProperty(propertyName);

      if (numberObject instanceof Number) {
        result = result || !Utils.isNumberObjectNullOrZero((Number) numberObject);
      } else {
        /*
         * not a number, we cannot aggregate this currently
         */
        result = result || false;
      }
    }

    /*
     * also check for bbox
     */
    if (bbox != null) {
      Coordinate pointCoordinate = new Coordinate(point.getX(), point.getY());

      if (!bbox.contains(Utils.geometryFactory.createPoint(pointCoordinate))) {
        return false;
      }
    }

    return result;
  }
Ejemplo n.º 2
0
  public void runAccessibilityComputation() {

    final Network network = (Network) this.scenario.getNetwork();

    ProgressBar bar = new ProgressBar(this.measuringPoints.getZones().size());

    for (Zone<Id<Zone>> measurePoint : this.measuringPoints.getZones()) {

      bar.update();

      Coord coord = MGC.point2Coord(measurePoint.getGeometry().getCentroid());
      Point p = measurePoint.getGeometry().getCentroid();
      final Coord coord1 = coord;

      Link nearestLink = NetworkUtils.getNearestLinkExactly(network, coord1);
      final Coord coord2 = coord;
      Node nearestNode = NetworkUtils.getNearestNode(network, coord2);

      Distances distance =
          NetworkUtil.getDistances2NodeViaGivenLink(coord, nearestLink, nearestNode);
      double distanceMeasuringPoint2Road_meter = distance.getDistancePoint2Intersection();

      double walkTravelTime_h =
          distanceMeasuringPoint2Road_meter
              / this.walkSpeedMeterPerHour; // travel time from coord to network (node or link)

      if (boundary.contains(p)) this.freeSpeedGrid.setValue(walkTravelTime_h, p);
    }
  }
Ejemplo n.º 3
0
  private static final List<Coord> getRandomCoordinatesInZone(
      int numCoordinates, Geometry zoneGeometry, Random random) {

    /*
     * Get the bounding box of the geometry. The returned geometry is a polygon with the following points:
     * (minx, miny), (maxx, miny), (maxx, maxy), (minx, maxy), (minx, miny).
     */
    Geometry envelope = zoneGeometry.getEnvelope();
    Coordinate[] coords = envelope.getCoordinates();

    double minX = Double.MAX_VALUE;
    double maxX = Double.MIN_VALUE;
    double minY = Double.MAX_VALUE;
    double maxY = Double.MIN_VALUE;

    for (Coordinate coord : coords) {
      if (coord.x < minX) minX = coord.x;
      if (coord.x > maxX) maxX = coord.x;
      if (coord.y < minY) minY = coord.y;
      if (coord.y > maxY) maxY = coord.y;
    }

    List<Coord> list = new ArrayList<Coord>();

    // loop until a valid point was found and is returned
    while (list.size() < numCoordinates) {
      double x = minX + random.nextDouble() * (maxX - minX);
      double y = minY + random.nextDouble() * (maxY - minY);

      Point point = geometryFactory.createPoint(new Coordinate(x, y));
      if (zoneGeometry.contains(point))
        list.add(fromWGS84CoordinateTransformation.transform(new Coord(x, y)));
    }
    return list;
  }
Ejemplo n.º 4
0
  /**
   * <b>validateMultipleLayers Purpose:</b> <br>
   *
   * <p>This validation tests for a geometry containing another geometry. Uses JTS'
   * Geometry.contains(Geometry) method. DE-9IM intersection matrix is T*F**F***.
   * <b>Description:</b><br>
   *
   * <p>The function filters the FeatureSources using the given bounding box. It creates iterators
   * over both filtered FeatureSources. It calls contains() using the geometries in the
   * SimpleFeatureSource layers. Tests the results of the method call against the given expected
   * results. Returns true if the returned results and the expected results are true, false
   * otherwise. Author: bowens<br>
   * Created on: Apr 27, 2004<br>
   *
   * @param featureSourceA - the SimpleFeatureSource to pull the original geometries from. This
   *     geometry is the one that is tested for containing the other
   * @param featureSourceB - the SimpleFeatureSource to pull the other geometries from - these
   *     geometries will be those that may be contained within the first geometry
   * @param expected - boolean value representing the user's expected outcome of the test
   * @param results - ValidationResults
   * @param bBox - Envelope - the bounding box within which to perform the contains()
   * @return boolean result of the test
   * @throws Exception - IOException if iterators improperly closed
   */
  private boolean validateMultipleLayers(
      SimpleFeatureSource featureSourceA,
      SimpleFeatureSource featureSourceB,
      boolean expected,
      ValidationResults results,
      Envelope bBox)
      throws Exception {
    boolean success = true;

    FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
    Filter filter = null;

    SimpleFeatureCollection featureResultsA = featureSourceA.getFeatures(filter);
    SimpleFeatureCollection featureResultsB = featureSourceB.getFeatures(filter);

    SimpleFeatureIterator fr1 = null;
    SimpleFeatureIterator fr2 = null;
    try {
      fr1 = featureResultsA.features();

      if (fr1 == null) return false;

      while (fr1.hasNext()) {
        SimpleFeature f1 = fr1.next();
        Geometry g1 = (Geometry) f1.getDefaultGeometry();
        fr2 = featureResultsB.features();
        try {
          while (fr2 != null && fr2.hasNext()) {
            SimpleFeature f2 = fr2.next();
            Geometry g2 = (Geometry) f2.getDefaultGeometry();
            if (g1.contains(g2) != expected) {
              results.error(
                  f1,
                  ((Geometry) f1.getDefaultGeometry()).getGeometryType()
                      + " "
                      + getGeomTypeRefA()
                      + " contains "
                      + getGeomTypeRefB()
                      + "("
                      + f2.getID()
                      + "), Result was not "
                      + expected);
              success = false;
            }
          }
        } finally {
          fr2.close();
        }
      }
    } finally {
      fr1.close();
      fr2.close();
    }

    return success;
  }
Ejemplo n.º 5
0
 /**
  * Check if geometry is in SpatialFilter envelopes
  *
  * @param geometry Geometry to check
  * @param envelopes SpatialFilter envelopes
  * @return True if geometry is contained in envelopes
  */
 public boolean featureIsInFilter(final Geometry geometry, final List<Geometry> envelopes) {
   if (geometry != null && !geometry.isEmpty()) {
     for (final Geometry envelope : envelopes) {
       if (envelope.contains(geometry)) {
         return true;
       }
     }
   }
   return false;
 }
Ejemplo n.º 6
0
  private static Set<Point> filterCoors(Set<Coord> source, Geometry zone) {
    GeometryFactory factory = new GeometryFactory();
    Set<Point> points = new HashSet<Point>();
    for (Coord c : source) {
      Point p = factory.createPoint(new Coordinate(c.getX(), c.getY()));
      if (zone.contains(p)) points.add(p);
    }

    return points;
  }
  /**
   * @param toSplit the line to split
   * @param line the line to use for the split
   * @return a sorted list of geometries as a result of splitting toSplit with line
   */
  protected List<LineString> splitLine(Geometry toSplit, Geometry line) {
    List<LineString> output = new ArrayList();
    Geometry lines = toSplit.union(line);

    for (int i = 0; i < lines.getNumGeometries(); i++) {
      LineString l = (LineString) lines.getGeometryN(i);
      // TODO to be tested
      if (toSplit.contains(l.getInteriorPoint())) {
        output.add(l);
      }
    }
    geometrySorter(output);
    return output;
  }
Ejemplo n.º 8
0
 private Map<String, Double> fetchPointValues(KmlFeature feature, List<String> parameters) {
   try {
     SimpleFeatureIterator iterator = getIterator();
     while (iterator.hasNext()) {
       SimpleFeature shape = iterator.next();
       Geometry geometry = (Geometry) shape.getDefaultGeometry();
       if (geometry.contains(feature.getGeometry())) return fetchValues(shape, parameters);
     }
     return Collections.emptyMap();
   } catch (Exception e) {
     log.error("failed to fetch point values", e);
     return Collections.emptyMap();
   }
 }
  private TransitStopFacility drawRandomStop(
      Geometry buffer, PRouteProvider pRouteProvider, Set<Id> stopsUsed) {
    List<TransitStopFacility> choiceSet = new LinkedList<TransitStopFacility>();

    // find choice-set
    for (TransitStopFacility stop : pRouteProvider.getAllPStops()) {
      if (!stopsUsed.contains(stop.getId())) {
        if (buffer.contains(MGC.coord2Point(stop.getCoord()))) {
          choiceSet.add(stop);
        }
      }
    }

    return pRouteProvider.drawRandomStopFromList(choiceSet);
  }
Ejemplo n.º 10
0
  /*package*/ void addConnectorLinks() {

    QuadTree<Node> quadTree = getNodesQuadTree();
    NetworkFactory factory = network.getFactory();

    /*
     * Try to use the centroid of the polygon. If that does not lie within
     * the polygon, use an interior point.
     */
    for (Entry<Integer, SimpleFeature> entry : zonesMap.entrySet()) {
      int zoneId = entry.getKey();
      SimpleFeature zone = entry.getValue();

      if (SpecialZones.skipZone(zone)) continue;

      Geometry polygon = (Geometry) zone.getDefaultGeometry();
      Point point = polygon.getCentroid();
      if (!polygon.contains(point)) point = polygon.getInteriorPoint();

      /*
       * Convert coordinate from WGS84 to EPSG:28992 (Netherlands Projection)
       */
      Coord wgs84Coord = new Coord(point.getCoordinate().x, point.getCoordinate().y);
      Coord nodeCoord = ct.transform(wgs84Coord);

      Id<Node> nodeId = Id.create(String.valueOf(zoneId), Node.class);
      network.addNode(factory.createNode(nodeId, nodeCoord));

      Node networkConnectorNode = quadTree.getClosest(nodeCoord.getX(), nodeCoord.getY());
      Id<Node> networkConnectorNodeId = networkConnectorNode.getId();

      double length = CoordUtils.calcDistance(nodeCoord, networkConnectorNode.getCoord());

      Id<Link> linkFromId = Id.create(String.valueOf(zoneId) + "from", Link.class);
      Link fromLink = factory.createLink(linkFromId, nodeId, networkConnectorNodeId);
      fromLink.setLength(length);
      fromLink.setCapacity(this.connectorCapacity);
      fromLink.setFreespeed(this.connectorLinkFreeSpeed);
      network.addLink(fromLink);

      Id<Link> linkToId = Id.create(String.valueOf(zoneId) + "to", Link.class);
      Link toLink = factory.createLink(linkToId, networkConnectorNodeId, nodeId);
      toLink.setLength(length);
      toLink.setCapacity(this.connectorCapacity);
      toLink.setFreespeed(this.connectorLinkFreeSpeed);
      network.addLink(toLink);
    }
  }
Ejemplo n.º 11
0
  /**
   * @param poly the polygon to split
   * @param line the line to use for the split
   * @return a sorted list of geometries as a result of splitting poly with line
   */
  protected List<Polygon> splitPolygon(Geometry poly, Geometry line) {
    List<Polygon> output = new ArrayList();

    Geometry nodedLinework = poly.getBoundary().union(line);
    Geometry polys = polygonize(nodedLinework);

    // only keep polygons which are inside the input
    for (int i = 0; i < polys.getNumGeometries(); i++) {
      Polygon candpoly = (Polygon) polys.getGeometryN(i);
      if (poly.contains(candpoly.getInteriorPoint())) {
        output.add(candpoly);
      }
    }
    geometrySorter(output);
    return output;
  }
Ejemplo n.º 12
0
 private Coord drawRandomPointFromGeometry(Geometry g) {
   Point p;
   double x, y;
   do {
     x =
         g.getEnvelopeInternal().getMinX()
             + random.nextDouble()
                 * (g.getEnvelopeInternal().getMaxX() - g.getEnvelopeInternal().getMinX());
     y =
         g.getEnvelopeInternal().getMinY()
             + random.nextDouble()
                 * (g.getEnvelopeInternal().getMaxY() - g.getEnvelopeInternal().getMinY());
     p = MGC.xy2Point(x, y);
   } while (!g.contains(p));
   Coord coord = new Coord(p.getX(), p.getY());
   return coord;
 }
 @Override
 public boolean isWater(double lat, double lon) {
   double realLon = lon;
   if (lon == -180.0) {
     realLon = -179.9;
   } else if (lon == 180.0) {
     realLon = 179.9;
   }
   Coordinate coordinate = new Coordinate(realLon, lat);
   com.vividsolutions.jts.geom.Point point = geometryFactory.createPoint(coordinate);
   for (Geometry geometry : geometryList) {
     if (geometry.contains(point)) {
       return true;
     }
   }
   return false; // To change body of implemented methods use File | Settings | File Templates.
 }
Ejemplo n.º 14
0
  // iterate over all nodes to find all external nodes
  private static final Set<Id<Node>> getExternalNodes(
      Scenario scenario, Map<Integer, SimpleFeature> zonalShapes) {

    Set<Id<Node>> externalNodes = new TreeSet<Id<Node>>();
    for (Node node : scenario.getNetwork().getNodes().values()) {
      Coord pointCoord = toWGS84CoordinateTransformation.transform(node.getCoord());
      Point point =
          geometryFactory.createPoint(new Coordinate(pointCoord.getX(), pointCoord.getY()));

      SimpleFeature pointZone = null;
      for (SimpleFeature zone : zonalShapes.values()) {
        Geometry polygon = (Geometry) zone.getDefaultGeometry();
        if (polygon.contains(point)) {
          pointZone = zone;
          break;
        }
      }

      // if the point is not contained in any Zone it is an external node.
      if (pointZone == null) externalNodes.add(node.getId());
    }

    return externalNodes;
  }
Ejemplo n.º 15
0
  public void setupAgents(GeomVectorField populationLayer) {
    Bag nodeBag = majorRoadNodesLayer.getGeometries();

    int numNodes = nodeBag.size();
    for (Object o : populationLayer.getGeometries()) {
      MasonGeometry g = (MasonGeometry) o;
      Coordinate c = g.geometry.getCoordinate();
      for (int i = 0; i < 50; i++) {
        //				GeoNode gn = (GeoNode) nodeBag.get(random.nextInt(numNodes));
        //				Coordinate myHome = (Coordinate) gn.geometry.getCoordinate().clone();
        //				double distance = Math.abs(random.nextGaussian()) * 1500;
        //				double degrees = random.nextDouble() * 2 * Math.PI;
        //				double xOffset = distance * Math.cos(degrees) + c.x;
        double xOffset = random.nextGaussian() * 100 + c.x;
        //				double yOffset = distance * Math.sin(degrees) + c.y;
        double yOffset = random.nextGaussian() * 100 + c.y;
        Coordinate myHome = new Coordinate(xOffset, yOffset);
        Geometry point = fa.createPoint(myHome);
        if (!landArea.contains(point)) continue;
        HumanTeleporter hum = new HumanTeleporter("id_" + random.nextLong(), myHome, myHome, this);
        humans.add(hum);
      }
    }
  }
Ejemplo n.º 16
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);
  }
Ejemplo n.º 17
0
 private boolean isBuildingInZone(Geometry zone, Coord building) {
   ;
   Point p = MGC.xy2Point(building.getX(), building.getY());
   return zone.contains(p);
 }
Ejemplo n.º 18
0
 /**
  * Returns a boolean value that shows if this geometry contains the specified geometry.
  *
  * @param node1 xml element containing gml object(s)
  * @param node2 xml element containing gml object(s)
  * @return boolean value
  * @throws QueryException query exception
  */
 @Deterministic
 public Bln contains(final ANode node1, final ANode node2) throws QueryException {
   final Geometry geo1 = checkGeo(node1);
   final Geometry geo2 = checkGeo(node2);
   return Bln.get(geo1.contains(geo2));
 }