public void testExecuteBuffer() throws Exception {
    org.geotools.process.Process buffer = factory.create(new NameImpl("JTS", "Buffer"));

    // try less than the required params
    Map<String, Object> inputs = new HashMap<String, Object>();
    try {
      buffer.execute(inputs, null);
      fail("What!!! Should have failed big time!");
    } catch (ProcessException e) {
      // fine
    }

    // try out only the required params
    Geometry geom = new WKTReader().read("POINT(0 0)");
    inputs.put("geom", geom);
    inputs.put("distance", 1d);
    Map<String, Object> result = buffer.execute(inputs, null);

    assertEquals(1, result.size());
    Geometry buffered = (Geometry) result.get("result");
    assertNotNull(buffered);
    assertTrue(buffered.equals(geom.buffer(1d)));

    // pass in all params
    inputs.put("quadrantSegments", 12);
    inputs.put("capStyle", GeometryFunctions.BufferCapStyle.Square);
    result = buffer.execute(inputs, null);

    assertEquals(1, result.size());
    buffered = (Geometry) result.get("result");
    assertNotNull(buffered);
    assertTrue(buffered.equals(geom.buffer(1d, 12, BufferParameters.CAP_SQUARE)));
  }
Exemplo n.º 2
0
  private void save() throws Exception {
    FeatureStore fs = (FeatureStore) ds.getFeatureSource("poly_county");
    FeatureType ft = fs.getSchema();

    MemoryDataStore memorystore = new MemoryDataStore();

    ArrayList polys = new ArrayList(resultPolygon);

    Geometry gfinal = null;
    if (polys.size() == 1) {
      gfinal = (Polygon) polys.get(0); // POLYGON
    } else {
      GeometryFactory gf = ((Polygon) polys.get(0)).getFactory();
      gfinal = new MultiPolygon((Polygon[]) polys.toArray(new Polygon[polys.size()]), gf);
    }

    gfinal = gfinal.buffer(0); // for topologic problems.

    Object[] values = new Object[5];
    values[ft.find("module")] = MODULE;
    values[ft.find("gen_full")] = gfinal;

    values[ft.find("gen_1")] = generalize(gfinal, tolerance1);
    ;
    values[ft.find("gen_2")] = generalize(gfinal, tolerance1);
    ;
    values[ft.find("gen_3")] = generalize(gfinal, tolerance1);
    ;

    Feature f = ft.create(values);
    memorystore.addFeature(f);

    fs.addFeatures(memorystore.getFeatureReader("poly_county"));
  }
  /**
   * Quick method for populating the {@link CUDABean} instance provided.
   *
   * @param bean
   * @param reference
   * @param coverage
   * @param geo
   * @param transform
   * @throws IOException
   * @throws MismatchedDimensionException
   * @throws TransformException
   */
  private void populateBean(
      CUDABean bean,
      boolean reference,
      GridCoverage2D coverage,
      Geometry geo,
      MathTransform transform,
      int buffer)
      throws IOException, MismatchedDimensionException, TransformException {

    RenderedImage image = coverage.getRenderedImage();

    // 0) Check if a buffer must be applied
    Geometry originalGeo = (Geometry) geo.clone();
    if (buffer > 0) {
      try {
        if (!"EPSG:4326"
            .equals(CRS.lookupIdentifier(coverage.getCoordinateReferenceSystem(), false))) {
          geo = geo.buffer(buffer);
        } else {
          geo = geo.buffer(buffer / 111.128);
        }
      } catch (FactoryException e) {
        geo = geo.buffer(buffer);
      }
    }

    // 1) Crop the two coverages with the selected Geometry
    GridCoverage2D crop = CROP.execute(coverage, geo, null);
    transform =
        ProjectiveTransform.create(
                (AffineTransform) crop.getGridGeometry().getGridToCRS(PixelInCell.CELL_CORNER))
            .inverse();

    // 2) Extract the BufferedImage from each image
    image = crop.getRenderedImage();

    Rectangle rectIMG =
        new Rectangle(image.getMinX(), image.getMinY(), image.getWidth(), image.getHeight());
    ImageWorker w = new ImageWorker(image);
    BufferedImage buf = w.getBufferedImage();
    if (image instanceof RenderedOp) {
      ((RenderedOp) image).dispose();
    }

    // 3) Generate an array of data from each image
    Raster data = buf.getData();
    final DataBufferByte db = (DataBufferByte) data.getDataBuffer();
    byte[] byteData = db.getData();

    if (reference) {
      // 4) Transform the Geometry to Raster space
      Geometry rs = JTS.transform(geo, transform);
      Geometry rsFilter = JTS.transform(geo.difference(originalGeo), transform);
      ROI roiGeo = new ROIGeometry(rs);
      ROI roiFilter = new ROIGeometry(rsFilter);

      // 5) Extract an array of data from the transformed ROI
      byte[] roiData = getROIData((buffer > 0 ? roiFilter : roiGeo), rectIMG);
      bean.setRoi(roiData);
      bean.setRoiObj(roiGeo);

      // 6) Setting the Coverage data array
      bean.setReferenceImage(byteData);

      // 7) Setting the Image dimensions
      bean.setHeight(rectIMG.height);
      bean.setWidth(rectIMG.width);
      bean.setMinX(rectIMG.x);
      bean.setMinY(rectIMG.y);
    } else {
      // 6) Setting the Coverage data array
      bean.setCurrentImage(byteData);
    }

    // 7) Store the Reference Covergae containing the geospatial info
    bean.setReferenceCoverage(coverage);
  }
  @Override
  /**
   * @param inputData a HashMap of the input data: inputObservations: the observations
   *     inputAuthoritativeData: the authoritative points inputDistance: the distance threshold
   *     minNumber: the minimum number of named features to pass fieldName: the name of the field
   *     within the observations to match
   * @result results a HashpMap of the results: result: the input data with the polygon attributes
   *     attached, null values for no match qual_result: the matched input only data with polygon
   *     attributes attached
   */
  public Map<String, IData> run(Map<String, List<IData>> inputData) throws ExceptionReport {

    List obsList = inputData.get("inputObservations");
    List authList = inputData.get("inputAuthoritativeData");
    List distList = inputData.get("inputDistance");
    List minList = inputData.get("minNumber");
    List fieldList = inputData.get("fieldName");

    FeatureCollection obsFc = ((GTVectorDataBinding) obsList.get(0)).getPayload();
    FeatureCollection authFc = ((GTVectorDataBinding) authList.get(0)).getPayload();
    double dist = ((LiteralDoubleBinding) distList.get(0)).getPayload();
    int minNum = ((LiteralIntBinding) minList.get(0)).getPayload();
    String fieldName = ((LiteralStringBinding) fieldList.get(0)).getPayload();

    ArrayList<SimpleFeature> resultFeatures = new ArrayList<SimpleFeature>();
    ArrayList<SimpleFeature> returnFeatures = new ArrayList<SimpleFeature>();

    SimpleFeatureIterator obsIt = (SimpleFeatureIterator) obsFc.features();
    SimpleFeatureIterator authIt = (SimpleFeatureIterator) authFc.features();

    SimpleFeatureIterator sfi = (SimpleFeatureIterator) obsFc.features();
    SimpleFeatureType fType = null;
    SimpleFeature tempPropFeature = sfi.next();
    CoordinateReferenceSystem inputObsCrs = obsFc.getSchema().getCoordinateReferenceSystem();

    Collection<Property> obsProp = tempPropFeature.getProperties();

    SimpleFeatureTypeBuilder resultTypeBuilder = new SimpleFeatureTypeBuilder();
    resultTypeBuilder.setName("typeBuilder");
    resultTypeBuilder.setCRS(inputObsCrs);

    Iterator<Property> pItObs = obsProp.iterator();

    sfi.close();
    while (pItObs.hasNext() == true) {

      try {

        Property tempProp = pItObs.next();
        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        resultTypeBuilder.add(name, valueClass);

        // LOG.warn ("Obs property " + name + " " + valueClass + " " +type.toString());
      } catch (Exception e) {
        LOG.error("property error " + e);
      }
    }

    // add DQ_Field

    resultTypeBuilder.add("DQ_SA_SimilarF", Double.class);
    SimpleFeatureType typeF = resultTypeBuilder.buildFeatureType();
    // LOG.warn("Get Spatial Accuracy Feature Type " + typeF.toString());

    SimpleFeatureBuilder resultFeatureBuilder = new SimpleFeatureBuilder(typeF);

    obsIt.close();

    SimpleFeatureIterator obsIt2 = (SimpleFeatureIterator) obsFc.features();

    while (obsIt2.hasNext()) {
      SimpleFeature tempFeature = obsIt2.next();

      fType = tempFeature.getType();

      // LOG.warn("fieldName " + fieldName + " featureName " + featureN + " tempFeature Type " +
      // fType);
      // LOG.warn("TableFeatureName " + tempFeature.getProperty(fieldName).getValue());

      String tempFeatureName = (String) tempFeature.getProperty(fieldName).getValue();

      Geometry geom = (Geometry) tempFeature.getDefaultGeometry();
      for (Property obsProperty : tempFeature.getProperties()) {

        String name = obsProperty.getName().toString();
        Object value = obsProperty.getValue();

        resultFeatureBuilder.set(name, value);
      }

      Geometry bufferGeom = geom.buffer(dist);

      SimpleFeatureIterator authIt2 = (SimpleFeatureIterator) authFc.features();

      int count = 0;
      int within = 0;

      while (authIt2.hasNext() && count <= minNum) {
        SimpleFeature tempAuth = authIt2.next();
        String featureN = (String) tempAuth.getProperty(fieldName).getValue();

        Geometry tempGeom = (Geometry) tempAuth.getDefaultGeometry();

        String authProperty = (String) tempAuth.getProperty(fieldName).getValue();

        if (tempGeom.within(bufferGeom) && authProperty.equalsIgnoreCase(featureN)) {

          count++;

          if (count >= minNum) {
            within = 1;
          }
        }
      }
      LOG.warn("HERE " + within);
      resultFeatureBuilder.set("DQ_SA_SimilarF", within);

      SimpleFeature result = resultFeatureBuilder.buildFeature(tempFeature.getID());
      result.setDefaultGeometry(geom);
      LOG.warn("HERE " + result);
      returnFeatures.add(result);

      if (within == 1) {
        resultFeatures.add(result);
      }

      authIt2.close();
    }
    obsIt2.close();

    ListFeatureCollection qualResult = new ListFeatureCollection(fType, resultFeatures);
    ListFeatureCollection returns = new ListFeatureCollection(fType, returnFeatures);

    LOG.warn("HERE 2 " + qualResult.size() + " " + returns.size());

    Map<String, IData> results = new HashMap<String, IData>();
    results.put("qual_result", new GTVectorDataBinding(qualResult));
    results.put("result", new GTVectorDataBinding(returns));

    return results;
  }
Exemplo n.º 5
0
  /**
   * Get polygons covering the components of the graph. The largest component (in terms of number of
   * nodes) will not overlap any other components (it will have holes); the others may overlap each
   * other.
   *
   * @param dateTime
   */
  public static List<Geometry> getComponentPolygons(
      Graph graph, RoutingRequest options, long time) {
    DisjointSet<Vertex> components = getConnectedComponents(graph);

    LinkedListMultimap<Integer, Coordinate> componentCoordinates = LinkedListMultimap.create();
    options.setDummyRoutingContext(graph);
    for (Vertex v : graph.getVertices()) {
      for (Edge e : v.getOutgoing()) {
        State s0 = new State(v, time, options);
        State s1 = e.traverse(s0);
        if (s1 != null) {
          Integer component = components.find(e.getFromVertex());
          Geometry geometry = s1.getBackEdge().getGeometry();
          if (geometry != null) {
            List<Coordinate> coordinates =
                new ArrayList<Coordinate>(Arrays.asList(geometry.getCoordinates()));
            for (int i = 0; i < coordinates.size(); ++i) {
              Coordinate coordinate = new Coordinate(coordinates.get(i));
              coordinate.x = Math.round(coordinate.x * PRECISION) / PRECISION;
              coordinate.y = Math.round(coordinate.y * PRECISION) / PRECISION;
              coordinates.set(i, coordinate);
            }
            componentCoordinates.putAll(component, coordinates);
          }
        }
      }
    }

    // generate convex hull of each component
    List<Geometry> geoms = new ArrayList<Geometry>();
    int mainComponentSize = 0;
    int mainComponentIndex = -1;
    int component = 0;
    for (Integer key : componentCoordinates.keySet()) {
      List<Coordinate> coords = componentCoordinates.get(key);
      Coordinate[] coordArray = new Coordinate[coords.size()];
      ConvexHull hull =
          new ConvexHull(coords.toArray(coordArray), GeometryUtils.getGeometryFactory());
      Geometry geom = hull.getConvexHull();
      // buffer components which are mere lines so that they do not disappear.
      if (geom instanceof LineString) {
        geom = geom.buffer(0.01); // ~10 meters
      } else if (geom instanceof Point) {
        geom = geom.buffer(0.05); // ~50 meters, so that it shows up
      }

      geoms.add(geom);
      if (mainComponentSize < coordArray.length) {
        mainComponentIndex = component;
        mainComponentSize = coordArray.length;
      }
      ++component;
    }

    // subtract small components out of main component
    // (small components are permitted to overlap each other)
    Geometry mainComponent = geoms.get(mainComponentIndex);
    for (int i = 0; i < geoms.size(); ++i) {
      Geometry geom = geoms.get(i);
      if (i == mainComponentIndex) {
        continue;
      }
      mainComponent = mainComponent.difference(geom);
    }
    geoms.set(mainComponentIndex, mainComponent);

    return geoms;
  }
  @Override
  /**
   * inputData a HashMap of the input data:
   *
   * @param inputObservations: the observations
   * @param inputAuthoritativeData: the polygons
   * @param bufferSize: the size of the buffer around the polygons results a HashpMap of the
   *     results:
   * @result result: the input data with the polygon attributes attached, null values for no match
   * @result qual_result: the matched input only data with polygon attributes attached
   */
  public Map<String, IData> run(Map<String, List<IData>> inputData) throws ExceptionReport {

    HashMap<String, Object> metadataMap = new HashMap<String, Object>();
    ArrayList<SimpleFeature> list = new ArrayList<SimpleFeature>();
    List<IData> inputObs = inputData.get("inputObservations");
    List<IData> inputAuth = inputData.get("inputAuthoritativeData");
    List<IData> inputLit = inputData.get("bufferSize");
    IData observations = inputObs.get(0);
    IData authoritative = inputAuth.get(0);

    IData buffersize = inputLit.get(0);

    double doubleB = (Double) buffersize.getPayload();

    FeatureCollection obsFC = ((GTVectorDataBinding) observations).getPayload();
    FeatureCollection authFC = ((GTVectorDataBinding) authoritative).getPayload();

    SimpleFeatureIterator obsIt = (SimpleFeatureIterator) obsFC.features();

    SimpleFeatureIterator authIt = (SimpleFeatureIterator) authFC.features();

    // setup result feature

    SimpleFeature obsItFeat = obsIt.next();

    SimpleFeature obsItAuth = authIt.next();

    Collection<Property> property = obsItFeat.getProperties();
    Collection<Property> authProperty = obsItAuth.getProperties();

    // setup result type builder
    SimpleFeatureTypeBuilder resultTypeBuilder = new SimpleFeatureTypeBuilder();
    resultTypeBuilder.setName("typeBuilder");

    Iterator<Property> pItObs = property.iterator();
    Iterator<Property> pItAuth = authProperty.iterator();

    metadataMap.put("element", "elementBufferedMetadata");
    File metadataFile = createXMLMetadata(metadataMap);

    while (pItObs.hasNext() == true) {

      try {
        Property tempProp = pItObs.next();

        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        resultTypeBuilder.add(name, valueClass);

      } catch (Exception e) {
        LOGGER.error("property error " + e);
      }
    }
    int i = 0;
    while (pItAuth.hasNext() == true) {
      try {
        Property tempProp = pItAuth.next();

        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        if (i > 3) {

          resultTypeBuilder.add(name, valueClass);
        }

        i++;

      } catch (Exception e) {
        LOGGER.error("property error " + e);
      }
    }

    obsIt.close();
    authIt.close();
    resultTypeBuilder.add("withinBuffer", Integer.class);

    // set up result feature builder

    SimpleFeatureType type = resultTypeBuilder.buildFeatureType();
    SimpleFeatureBuilder resultFeatureBuilder = new SimpleFeatureBuilder(type);

    // process data here:

    SimpleFeatureIterator obsIt2 = (SimpleFeatureIterator) obsFC.features();

    int within = 0;

    FeatureCollection resultFeatureCollection = DefaultFeatureCollections.newCollection();

    while (obsIt2.hasNext() == true) {
      within = 0;
      SimpleFeature tempObs = obsIt2.next();
      Geometry obsGeom = (Geometry) tempObs.getDefaultGeometry();

      for (Property obsProperty : tempObs.getProperties()) {

        String name = obsProperty.getName().getLocalPart();
        Object value = obsProperty.getValue();

        resultFeatureBuilder.set(name, value);
        // LOGGER.warn("obs Property set " + name);
      }

      double bufferSizeDouble = doubleB;

      Geometry bufferGeom = obsGeom.buffer(bufferSizeDouble);

      int j = 0;
      SimpleFeatureIterator authIt2 = (SimpleFeatureIterator) authFC.features();
      while (authIt2.hasNext() == true) {

        SimpleFeature tempAuth = authIt2.next();
        Geometry authGeom = (Geometry) tempAuth.getDefaultGeometry();

        if (bufferGeom.intersects(authGeom) == true) {
          within = 1;
          j = 0;

          LOGGER.warn("Intersection = true");
          for (Property authProperty1 : tempAuth.getProperties()) {

            String name = authProperty1.getName().getLocalPart();
            Object value = authProperty1.getValue();
            // Class valueClass = (Class<String>)authProperty1.getType().getBinding();

            //		LOGGER.warn("Auth property " + name);
            if (j > 3) {
              resultFeatureBuilder.set(name, value);
              //	LOGGER.warn("Auth property set " + name);

            }

            j++;
          }
        }
      }
      resultFeatureBuilder.set("withinBuffer", within);

      SimpleFeature resultFeature = resultFeatureBuilder.buildFeature(tempObs.getName().toString());
      Geometry geom = (Geometry) tempObs.getDefaultGeometry();
      resultFeature.setDefaultGeometry(geom);

      list.add(resultFeature);

      // resultFeatureCollection.add(resultFeature);
      // LOGGER.warn("RESULT FEATURE " + resultFeatureCollection.getSchema().toString());
      // resultFeatureCollection = obsFC;
    }

    ListFeatureCollection listFeatureCollection = new ListFeatureCollection(type, list);
    LOGGER.warn("Result Feature Size " + listFeatureCollection.size());

    // sort HashMap
    GenericFileData gf = null;
    try {
      gf = new GenericFileData(metadataFile, "text/xml");
    } catch (IOException e) {
      LOGGER.error("GenericFileData " + e);
    }

    HashMap<String, IData> results = new HashMap<String, IData>();
    results.put("result", new GTVectorDataBinding((FeatureCollection) obsFC));
    results.put("qual_result", new GTVectorDataBinding((FeatureCollection) listFeatureCollection));
    results.put("metadata", new GenericFileDataBinding(gf));

    return results;
  }
  @Execute
  /**
   * inputData a HashMap of the input data:
   *
   * @param inputObservations: the observations
   * @param inputAuthoritativeData: the polygons
   * @param bufferSize: the size of the buffer in the same units as the input data (degrees for
   *     lat/long) results a HashpMap of the results:
   * @result result: the input data with the polygon attributes attached, null values for no match
   * @result qual_result: the matched input only data with polygon attributes attached
   * @result metadata: an unused output that was supposed to return an XML document for GeoNetwork
   */
  public void runBuffer() {

    Logger LOGGER = Logger.getLogger(BufferAuthoritativeDataComparison.class);

    SimpleFeatureIterator obsIt = (SimpleFeatureIterator) obsFC.features();

    SimpleFeatureIterator authIt = (SimpleFeatureIterator) authFC.features();

    // setup result feature

    SimpleFeature obsItFeat = obsIt.next();

    SimpleFeature obsItAuth = authIt.next();

    Collection<Property> property = obsItFeat.getProperties();
    Collection<Property> authProperty = obsItAuth.getProperties();

    // setup result type builder
    SimpleFeatureTypeBuilder resultTypeBuilder = new SimpleFeatureTypeBuilder();
    resultTypeBuilder.setName("typeBuilder");

    Iterator<Property> pItObs = property.iterator();
    Iterator<Property> pItAuth = authProperty.iterator();

    metadataMap.put("element", "elementBufferedMetadata");
    metadataFile = createXMLMetadata(metadataMap);

    while (pItObs.hasNext() == true) {

      try {
        Property tempProp = pItObs.next();

        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        resultTypeBuilder.add(name, valueClass);

      } catch (Exception e) {
        LOGGER.error("property error " + e);
      }
    }
    int i = 0;
    while (pItAuth.hasNext() == true) {
      try {
        Property tempProp = pItAuth.next();

        PropertyType type = tempProp.getDescriptor().getType();
        String name = type.getName().getLocalPart();
        Class<String> valueClass = (Class<String>) tempProp.getType().getBinding();

        if (i > 3) {

          resultTypeBuilder.add(name, valueClass);
        }

        i++;

      } catch (Exception e) {
        LOGGER.error("property error " + e);
      }
    }

    obsIt.close();
    authIt.close();
    resultTypeBuilder.add("withinBuffer", Integer.class);

    // set up result feature builder

    SimpleFeatureType type = resultTypeBuilder.buildFeatureType();
    SimpleFeatureBuilder resultFeatureBuilder = new SimpleFeatureBuilder(type);

    // process data here:

    SimpleFeatureIterator obsIt2 = (SimpleFeatureIterator) obsFC.features();

    int within = 0;

    resultFeatureCollection = DefaultFeatureCollections.newCollection();

    while (obsIt2.hasNext() == true) {
      within = 0;
      SimpleFeature tempObs = obsIt2.next();
      Geometry obsGeom = (Geometry) tempObs.getDefaultGeometry();

      for (Property obsProperty : tempObs.getProperties()) {

        String name = obsProperty.getName().getLocalPart();
        Object value = obsProperty.getValue();

        resultFeatureBuilder.set(name, value);
        // LOGGER.warn("obs Property set " + name);
      }

      double bufferSizeDouble = Double.parseDouble(bufferSize);

      Geometry bufferGeom = obsGeom.buffer(bufferSizeDouble);

      int j = 0;
      SimpleFeatureIterator authIt2 = (SimpleFeatureIterator) authFC.features();
      while (authIt2.hasNext() == true) {

        SimpleFeature tempAuth = authIt2.next();
        Geometry authGeom = (Geometry) tempAuth.getDefaultGeometry();

        if (bufferGeom.intersects(authGeom) == true) {
          within = 1;
          j = 0;

          LOGGER.warn("Intersection = true");
          for (Property authProperty1 : tempAuth.getProperties()) {

            String name = authProperty1.getName().getLocalPart();
            Object value = authProperty1.getValue();
            // Class valueClass = (Class<String>)authProperty1.getType().getBinding();

            //		LOGGER.warn("Auth property " + name);
            if (j > 3) {
              resultFeatureBuilder.set(name, value);
              //	LOGGER.warn("Auth property set " + name);

            }

            j++;
          }
        }
      }
      resultFeatureBuilder.set("withinBuffer", within);

      SimpleFeature resultFeature = resultFeatureBuilder.buildFeature(tempObs.getName().toString());
      Geometry geom = (Geometry) tempObs.getDefaultGeometry();
      resultFeature.setDefaultGeometry(geom);

      list.add(resultFeature);

      // resultFeatureCollection.add(resultFeature);
      // LOGGER.warn("RESULT FEATURE " + resultFeatureCollection.getSchema().toString());
      // resultFeatureCollection = obsFC;
    }

    listFeatureCollection = new ListFeatureCollection(type, list);
    LOGGER.warn("Result Feature Size " + listFeatureCollection.size());
  }