コード例 #1
0
ファイル: DatasetInfo.java プロジェクト: QSRImpl/MRCC8
 public static void removeEqual(List<Geometry> aGeometryList) {
   List<Integer> uniqueGeometries = new ArrayList<Integer>();
   int numVar = aGeometryList.size();
   for (int i = 0; i < numVar; i++) {
     System.out.println("check:" + i);
     Geometry a = aGeometryList.get(i);
     boolean eq = false;
     for (Integer v : uniqueGeometries) {
       Geometry b = aGeometryList.get(v);
       if (a.getArea() == b.getArea()) {
         if (a.equalsTopo(b)) {
           eq = true;
           break;
         }
       }
     }
     if (!eq) {
       uniqueGeometries.add(i);
     }
     //			for(int j=i+1;j<numVar;j++){
     //
     //			}
   }
   System.out.println("Removed equals:");
   for (Integer v : uniqueGeometries) {
     System.out.println(v);
   }
 }
コード例 #2
0
 static double getIntersectionArea(
     Geometry first,
     CoordinateReferenceSystem firstCRS,
     Geometry second,
     CoordinateReferenceSystem secondCRS,
     boolean divideFirst) {
   // basic checks
   if (firstCRS == null || secondCRS == null)
     throw new IllegalArgumentException("CRS cannot be set to null");
   if (!Polygon.class.isAssignableFrom(first.getClass())
       && !MultiPolygon.class.isAssignableFrom(first.getClass()))
     throw new IllegalArgumentException("first geometry must be poligonal");
   if (!Polygon.class.isAssignableFrom(second.getClass())
       && !MultiPolygon.class.isAssignableFrom(second.getClass()))
     throw new IllegalArgumentException("second geometry must be poligonal");
   try {
     Geometry firstTargetGeometry = reprojectAndDensify(first, firstCRS, null);
     Geometry secondTargetGeometry = reprojectAndDensify(second, firstCRS, null);
     double numeratorArea =
         (double) (firstTargetGeometry.intersection(secondTargetGeometry)).getArea();
     if (divideFirst) {
       double denom = firstTargetGeometry.getArea();
       if (denom != 0) return numeratorArea / denom;
       return 0;
     }
     double denom = secondTargetGeometry.getArea();
     if (denom != 0) return numeratorArea / denom;
     return 0;
   } catch (Exception e) {
     e.printStackTrace();
     return -1;
   }
 }
コード例 #3
0
ファイル: DatasetOperate.java プロジェクト: QSRImpl/MRCC8
 /*
  * This method takes a geometry and translate (move) it along x for tx and along y for ty
  */
 public static void moveGeometry(Geometry a, double tx, double ty)
     throws MismatchedDimensionException, TransformException {
   System.out.println("a: " + a.getCentroid() + "," + a.getArea());
   AffineTransform affineTransform = AffineTransform.getTranslateInstance(tx, ty);
   MathTransform mathTransform = new AffineTransform2D(affineTransform);
   Geometry a1 = JTS.transform(a, mathTransform);
   System.out.println("a': " + a1.getCentroid() + "," + a1.getArea());
 }
コード例 #4
0
  @Override
  public SimpleFeature addFeature(Geometry geometry) {
    org.sola.clients.beans.cadastre.CadastreObjectBean formBean =
        new org.sola.clients.beans.cadastre.CadastreObjectBean();
    formBean.setNameFirstpart(getLayer().getLastPart());
    formBean.setNameLastpart(getLayer().getNameFirstPart());
    if (geometry != null) {
      formBean.setOfficialAreaSize(new BigDecimal(geometry.getArea()));
      formBean.setCalculatedArea(new BigDecimal(geometry.getArea()));
    }
    ParcelDialog form = new ParcelDialog(formBean, false, null, true);

    final CadastreObjectBean[] beans = new CadastreObjectBean[1];

    // AM - Multi-SRID change
    // Need to explicitly set the SRID of the map on the geometry.
    final Geometry geom = this.layer.setSridOnGeometry(geometry);

    form.addPropertyChangeListener(
        new PropertyChangeListener() {

          @Override
          public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals(ParcelDialog.SELECTED_PARCEL)) {
              // Convert between CadastreObject in the GIS project and CadastreObject in the Clients
              // Beans
              org.sola.clients.beans.cadastre.CadastreObjectBean bean =
                  (org.sola.clients.beans.cadastre.CadastreObjectBean) evt.getNewValue();
              CadastreObjectBean bean2 =
                  MappingManager.getMapper().map(bean, CadastreObjectBean.class);
              // Fix problem with list area list duplications
              bean2.getSpatialValueAreaList().clear();
              bean2.getSpatialValueAreaList().addAll(bean.getSpatialValueAreaList());

              bean2.setFeatureGeom(geom);
              getLayer().getBeanList().add(bean2);
              beans[0] = bean2;
            }
          }
        });

    form.setVisible(true);
    if (beans[0] != null) {
      return getLayer().getFeatureByCadastreObjectId(beans[0].getId());
    }
    return null;
  }
コード例 #5
0
ファイル: AreaProcess.java プロジェクト: tjkr/geotoolkit
  @Override
  protected void execute() {

    final Geometry geom = value(GEOM, inputParameters);

    final double result = geom.getArea();

    getOrCreate(RESULT, outputParameters).setValue(result);
  }
コード例 #6
0
  public Geometry createHullFromGeometry(
      Geometry clusterGeometry, Collection<Coordinate> additionalPoints, boolean fast) {

    if (additionalPoints.isEmpty()) return clusterGeometry;
    final Set<Coordinate> batchCoords = new HashSet<Coordinate>();

    for (final Coordinate coordinate : clusterGeometry.getCoordinates()) {
      batchCoords.add(coordinate);
    }
    for (final Coordinate coordinate : additionalPoints) {
      batchCoords.add(coordinate);
    }

    final Coordinate[] actualCoords = batchCoords.toArray(new Coordinate[batchCoords.size()]);

    if (batchCoords.size() == 2) {
      return clusterGeometry.getFactory().createLineString(actualCoords);
    }

    final ConvexHull convexHull = new ConvexHull(actualCoords, clusterGeometry.getFactory());

    final Geometry convexHullGeo = convexHull.getConvexHull();

    try {
      // does this shape benefit from concave hulling?
      // it cannot be a line string
      if (batchCoords.size() > 5 && convexHullGeo.getArea() > 0.0) {
        final Geometry concaveHull =
            fast
                ? concaveHull(convexHullGeo, batchCoords)
                : this.concaveHullParkOhMethod(convexHullGeo, batchCoords);
        if (!concaveHull.isSimple()) {
          LOGGER.warn("Produced non simple hull", concaveHull.toText());
          return convexHullGeo;
        }
        return concaveHull;
      } else {
        return convexHullGeo;
      }
    } catch (final Exception ex) {

      /*
       * Geometry[] points = new Geometry[actualCoords.length + 1]; for
       * (int i = 0; i < actualCoords.length; i++) points[i] =
       * hull.getFactory().createPoint( actualCoords[i]);
       * points[points.length - 1] = hull; try { ShapefileTool.writeShape(
       * "test_perf_xh", new File( "./targettest_perf_xh"), points); }
       * catch (IOException e) { e.printStackTrace(); }
       */
      LOGGER.error("Failed to compute hull", ex);

      return convexHullGeo;
    }
  }
コード例 #7
0
  static Geometry densify(Geometry geom, CoordinateReferenceSystem crs, double maxAreaError)
      throws FactoryException, TransformException {
    // basic checks
    if (maxAreaError <= 0) {
      throw new IllegalArgumentException("maxAreaError must be greater than 0");
    }
    if (!(geom instanceof Polygon) && !(geom instanceof MultiPolygon)) {
      throw new IllegalArgumentException("Geom must be poligonal");
    }
    if (crs == null) {
      throw new IllegalArgumentException("CRS cannot be set to null");
    }
    double previousArea = 0.0;
    CoordinateReferenceSystem targetCRS = CRS.parseWKT(ECKERT_IV_WKT);
    MathTransform firstTransform = CRS.findMathTransform(crs, targetCRS);
    GeometryFactory geomFactory = new GeometryFactory();
    int ngeom = geom.getNumGeometries();
    Geometry densifiedGeometry = geom;
    double areaError = 1.0d;
    int maxIterate = 0;
    do {
      double max = 0;
      maxIterate++;
      // check the maximum side length of the densifiedGeometry
      for (int j = 0; j < ngeom; j++) {
        Geometry geometry = densifiedGeometry.getGeometryN(j);
        Coordinate[] coordinates = geometry.getCoordinates();
        int n = coordinates.length;
        for (int i = 0; i < (n - 1); i++) {
          Coordinate[] coords = new Coordinate[2];
          coords[0] = coordinates[i];
          coords[1] = coordinates[i + 1];
          LineString lineString = geomFactory.createLineString(coords);
          if (lineString.getLength() > max) max = lineString.getLength();
        }
      }

      // calculate the denified geometry
      densifiedGeometry = Densifier.densify(densifiedGeometry, max / 2);

      // reproject densifiedGeometry to Eckert IV
      Geometry targetGeometry = JTS.transform(densifiedGeometry, firstTransform);
      double nextArea = targetGeometry.getArea();

      // evaluate the current error
      areaError = Math.abs(previousArea - nextArea) / nextArea;
      //      logger3.info("AREA ERROR"+areaError);
      previousArea = nextArea;
      // check whether the current error is greater than the maximum allowed
    } while (areaError > maxAreaError && maxIterate < 10);
    return densifiedGeometry;
  }
コード例 #8
0
 @Override
 public void filter(Geometry gmtr) {
   if (MultiPolygon.class.isAssignableFrom(binding)) {
     if (gmtr.getArea() != 0.0d && gmtr.getGeometryType().equals("Polygon")) {
       collection.add(gmtr);
     }
   }
   if (MultiLineString.class.isAssignableFrom(binding)) {
     if (gmtr.getLength() != 0.0d && gmtr.getGeometryType().equals("LineString")) {
       collection.add(gmtr);
     }
   }
   if (MultiPoint.class.isAssignableFrom(binding)) {
     if (gmtr.getNumGeometries() > 0 && gmtr.getGeometryType().equals("Point")) {
       collection.add(gmtr);
     }
   }
   if (Point.class.isAssignableFrom(binding)) {
     if (gmtr.getGeometryType().equals("Point")) {
       collection.add(gmtr);
     }
   }
 }
コード例 #9
0
  /**
   * Add a feature with layer name (typically feature type name), some attributes and a Geometry.
   * The Geometry must be in "pixel" space 0,0 lower left and 256,256 upper right.
   *
   * <p>For optimization, geometries will be clipped, geometries will simplified and features with
   * geometries outside of the tile will be skipped.
   *
   * @param layerName
   * @param attributes
   * @param geometry
   */
  public void addFeature(String layerName, Map<String, ?> attributes, Geometry geometry) {

    // split up MultiPolygon and GeometryCollection (without subclasses)
    if (geometry instanceof MultiPolygon || geometry.getClass().equals(GeometryCollection.class)) {
      splitAndAddFeatures(layerName, attributes, (GeometryCollection) geometry);
      return;
    }

    // skip small Polygon/LineString.
    if (geometry instanceof Polygon && geometry.getArea() < 1.0d) {
      return;
    }
    if (geometry instanceof LineString && geometry.getLength() < 1.0d) {
      return;
    }

    // clip geometry. polygons right outside. other geometries at tile
    // border.
    try {
      if (geometry instanceof Polygon) {
        Geometry original = geometry;
        geometry = polygonClipGeometry.intersection(original);

        // some times a intersection is returned as an empty geometry.
        // going via wkt fixes the problem.
        if (geometry.isEmpty() && original.intersects(polygonClipGeometry)) {
          Geometry originalViaWkt = new WKTReader().read(original.toText());
          geometry = polygonClipGeometry.intersection(originalViaWkt);
        }

      } else {
        geometry = clipGeometry.intersection(geometry);
      }
    } catch (TopologyException e) {
      // could not intersect. original geometry will be used instead.
    } catch (ParseException e1) {
      // could not encode/decode WKT. original geometry will be used instead.
    }

    // if clipping result in MultiPolygon, then split once more
    if (geometry instanceof MultiPolygon) {
      splitAndAddFeatures(layerName, attributes, (GeometryCollection) geometry);
      return;
    }

    // no need to add empty geometry
    if (geometry.isEmpty()) {
      return;
    }

    Layer layer = layers.get(layerName);
    if (layer == null) {
      layer = new Layer();
      layers.put(layerName, layer);
    }

    Feature feature = new Feature();
    feature.geometry = geometry;

    for (Map.Entry<String, ?> e : attributes.entrySet()) {
      // skip attribute without value
      if (e.getValue() == null) {
        continue;
      }
      feature.tags.add(layer.key(e.getKey()));
      feature.tags.add(layer.value(e.getValue()));
    }

    layer.features.add(feature);
  }
コード例 #10
0
ファイル: ST_Area.java プロジェクト: sennj/orbisgis
 @Override
 public Value evaluateResult(DataSourceFactory dsf, Value[] args) throws FunctionException {
   final Geometry gv = args[0].getAsGeometry();
   return ValueFactory.createValue(gv.getArea());
 }
コード例 #11
0
  private SimpleFeatureCollection calculateRisk(
      SimpleFeatureCollection features,
      JDBCDataStore dataStore,
      String storeName,
      Integer precision,
      String connectionParams,
      int processing,
      int formula,
      int target,
      String materials,
      String scenarios,
      String entities,
      String severeness,
      String fpfield,
      int batch,
      boolean simulation,
      Geometry damageArea,
      Map<Integer, Double> damageValues,
      List<TargetInfo> changedTargets,
      Map<Integer, Map<Integer, Double>> cffs,
      List<String> psc,
      Map<Integer, Map<Integer, Double>> padrs,
      Map<Integer, Double> piss,
      List<Integer> distances,
      boolean extendedSchema)
      throws IOException, SQLException {

    if (precision == null) {
      precision = 3;
    }

    DefaultTransaction transaction = new DefaultTransaction();
    Connection conn = null;
    try {
      conn = dataStore.getConnection(transaction);

      // output FeatureType (risk)
      //  - id_geo_arco
      //  - geometria
      //  - rischio1
      //  - rischio2
      SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
      tb.add(
          "id_geo_arco", features.getSchema().getDescriptor("id_geo_arco").getType().getBinding());
      tb.add(
          "geometria",
          MultiLineString.class,
          features.getSchema().getGeometryDescriptor().getCoordinateReferenceSystem());

      if (extendedSchema) {
        tb.add("rischio_sociale", Double.class);
        tb.add("rischio_ambientale", Double.class);
        tb.add("nr_corsie", Integer.class);
        tb.add("lunghezza", Integer.class);
        tb.add("nr_incidenti", Integer.class);
      } else {
        tb.add("rischio1", Double.class);
        tb.add("rischio2", Double.class);
      }
      // fake layer name (risk) used for WPS output. Layer risk must be defined in GeoServer
      // catalog
      tb.setName(new NameImpl(features.getSchema().getName().getNamespaceURI(), "risk"));
      SimpleFeatureType ft = tb.buildFeatureType();

      // feature level (1, 2, 3)
      int level = FormulaUtils.getLevel(features);

      LOGGER.info("Doing calculus for level " + level);

      Formula formulaDescriptor = Formula.load(conn, processing, formula, target);

      if (formulaDescriptor == null) {
        throw new ProcessException("Unable to load formula " + formula);
      }

      if (((!formulaDescriptor.hasGrid() && level == 3)
              || (!formulaDescriptor.hasNoGrid() && level < 3))
          && !extendedSchema) {
        LOGGER.info("Formula not supported on this level, returning empty collection");
        return new EmptyFeatureCollection(ft);
      } else {
        // iterator on source
        SimpleFeatureIterator iter = features.features();

        // result builder
        SimpleFeatureBuilder fb = new SimpleFeatureBuilder(ft);
        ListFeatureCollection result = new ListFeatureCollection(ft);
        int count = 0;
        Double[] risk = new Double[] {0.0, 0.0};

        // iterate source features
        try {
          // we will calculate risk in batch of arcs
          // we store each feature of the batch in a map
          // indexed by id
          Map<Number, SimpleFeature> temp = new HashMap<Number, SimpleFeature>();
          StringBuilder ids = new StringBuilder();
          String fk_partner = null;

          while (iter.hasNext()) {
            SimpleFeature feature = iter.next();
            Number id = (Number) feature.getAttribute("id_geo_arco");
            fk_partner = (String) feature.getAttribute("fk_partner");
            fb.add(id);
            fb.add(feature.getDefaultGeometry());
            if (formulaDescriptor.takeFromSource()) {
              risk[0] = ((Number) feature.getAttribute("rischio1")).doubleValue();
              risk[1] = ((Number) feature.getAttribute("rischio2")).doubleValue();
            }
            fb.add(risk[0]);
            fb.add(risk[1]);
            if (extendedSchema) {
              fb.add((Number) feature.getAttribute("nr_corsie"));
              fb.add((Number) feature.getAttribute("lunghezza"));
              fb.add((Number) feature.getAttribute("nr_incidenti"));
            }
            temp.put(id.intValue(), fb.buildFeature(id + ""));

            if (simulation) {
              Double pis = piss.get(id.intValue());
              Map<Integer, Double> padr = padrs.get(id.intValue());
              Map<Integer, Double> cff = cffs.get(id.intValue());

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

              if (!changedTargets.isEmpty()) {
                for (int distance : distances) {
                  Geometry buffer =
                      BufferUtils.iterativeBuffer(
                          (Geometry) feature.getDefaultGeometry(), (double) distance, 100);
                  for (TargetInfo targetInfo : changedTargets) {
                    if (targetInfo.getGeometry() != null) {
                      Geometry intersection = buffer.intersection(targetInfo.getGeometry());
                      if (intersection != null && intersection.getArea() > 0) {
                        Map<Integer, Double> distancesMap =
                            simulationTargets.get(targetInfo.getType());
                        if (distancesMap == null) {
                          distancesMap = new HashMap<Integer, Double>();
                          simulationTargets.put(targetInfo.getType(), distancesMap);
                        }
                        double value = 0.0;
                        if (targetInfo.isHuman()) {
                          value =
                              intersection.getArea()
                                  / targetInfo.getGeometry().getArea()
                                  * targetInfo.getValue();
                        } else {
                          value = intersection.getArea();
                        }
                        if (targetInfo.isRemoved()) {
                          value = -value;
                        }
                        distancesMap.put(distance, value);
                      }
                    }
                  }
                }
              }

              FormulaUtils.calculateSimulationFormulaValuesOnSingleArc(
                  conn,
                  level,
                  processing,
                  formulaDescriptor,
                  id.intValue(),
                  fk_partner,
                  materials,
                  scenarios,
                  entities,
                  severeness,
                  fpfield,
                  target,
                  simulationTargets,
                  temp,
                  precision,
                  cff,
                  psc,
                  padr,
                  pis,
                  null,
                  extendedSchema);

              result.addAll(temp.values());
              temp = new HashMap<Number, SimpleFeature>();
            } else if (damageArea != null) {
              Geometry arcGeometry = (Geometry) feature.getDefaultGeometry();
              if (arcGeometry != null && arcGeometry.intersects(damageArea)) {
                FormulaUtils.calculateSimulationFormulaValuesOnSingleArc(
                    conn,
                    level,
                    processing,
                    formulaDescriptor,
                    id.intValue(),
                    fk_partner,
                    materials,
                    scenarios,
                    entities,
                    severeness,
                    fpfield,
                    target,
                    null,
                    temp,
                    precision,
                    null,
                    null,
                    null,
                    null,
                    damageValues,
                    extendedSchema);
                result.addAll(temp.values());
              }
              temp = new HashMap<Number, SimpleFeature>();
            } else {
              ids.append("," + id);
              count++;
              // calculate batch items a time
              if (count % batch == 0) {
                LOGGER.info("Calculated " + count + " values");
                FormulaUtils.calculateFormulaValues(
                    conn,
                    level,
                    processing,
                    formulaDescriptor,
                    ids.toString().substring(1),
                    fk_partner,
                    materials,
                    scenarios,
                    entities,
                    severeness,
                    fpfield,
                    target,
                    temp,
                    precision,
                    extendedSchema);
                result.addAll(temp.values());
                ids = new StringBuilder();
                temp = new HashMap<Number, SimpleFeature>();
              }
            }
          }

          // final calculus for remaining items not in batch size
          LOGGER.info("Calculating remaining items");
          if (ids.length() > 0) {
            FormulaUtils.calculateFormulaValues(
                conn,
                level,
                processing,
                formulaDescriptor,
                ids.toString().substring(1),
                fk_partner,
                materials,
                scenarios,
                entities,
                severeness,
                fpfield,
                target,
                temp,
                precision,
                extendedSchema);
          }
          result.addAll(temp.values());

          LOGGER.info("Calculated " + result.size() + " values");

        } finally {
          iter.close();
        }
        return result;
      }

    } finally {
      transaction.close();
      if (conn != null) {
        conn.close();
      }
    }
  }
コード例 #12
0
 public double getArea() {
   if (area == -1.0 && geometry != null) {
     area = geometry.getArea();
   }
   return area;
 }