Ejemplo n.º 1
0
  public <T> T evaluate(Object object, Class<T> context) {
    Point point;
    Expression param1 = parameters.get(0);

    if (param1.equals(ToDirectPositionFunction.SRS_NAME)) {

      if (parameters.size() > 5 || parameters.size() < 4) {
        throw new IllegalArgumentException(
            "Wrong number of parameters for toPoint function: "
                + parameters.toString()
                + ". Usage: toPoint('SRS_NAME'(optional), srsName(optional), point 1, point 2, gml:id(optional))");
      }
      CoordinateReferenceSystem crs = null;
      String srsName = parameters.get(1).evaluate(object, String.class);
      try {
        crs = CRS.decode((String) srsName);
      } catch (NoSuchAuthorityCodeException e) {
        throw new IllegalArgumentException(
            "Invalid or unsupported SRS name detected for toPoint function: "
                + srsName
                + ". Cause: "
                + e.getMessage());
      } catch (FactoryException e) {
        throw new RuntimeException("Unable to decode SRS name. Cause: " + e.getMessage());
      }
      GeometryFactory fac = new GeometryFactory(new PrecisionModel());
      point =
          fac.createPoint(
              new Coordinate(
                  parameters.get(2).evaluate(object, Double.class),
                  parameters.get(3).evaluate(object, Double.class)));
      // set attributes
      String gmlId = null;
      if (parameters.size() == 5) {
        gmlId = parameters.get(4).evaluate(object, String.class);
      }
      setUserData(point, crs, gmlId);
    } else {

      if (parameters.size() > 3 || parameters.size() < 2) {
        throw new IllegalArgumentException(
            "Wrong number of parameters for toPoint function: "
                + parameters.toString()
                + ". Usage: toPoint('SRS_NAME'(optional), srsName(optional), point 1, point 2, gml:id(optional))");
      }
      GeometryFactory fac = new GeometryFactory();

      point =
          fac.createPoint(
              new Coordinate(
                  param1.evaluate(object, Double.class),
                  parameters.get(1).evaluate(object, Double.class)));

      if (parameters.size() == 3) {
        String gmlId = parameters.get(2).evaluate(object, String.class);
        setUserData(point, null, gmlId);
      }
    }
    return (T) point;
  }
    /**
     * Handles the encoding of the layers elements.
     *
     * <p>This method does a search over the SRS of all the layers to see if there are at least a
     * common one, as needed by the spec: "<i>The root Layer element shall include a sequence of
     * zero or more &lt;SRS&gt; elements listing all SRSes that are common to all subsidiary layers.
     * Use a single SRS element with empty content (like so: "&lt;SRS&gt;&lt;/SRS&gt;") if there is
     * no common SRS."</i>
     *
     * <p>By the other hand, this search is also used to collecto the whole latlon bbox, as stated
     * by the spec: <i>"The bounding box metadata in Capabilities XML specify the minimum enclosing
     * rectangle for the layer as a whole."</i>
     *
     * @task TODO: manage this differently when we have the layer list of the WMS service decoupled
     *     from the feature types configured for the server instance. (This involves nested layers,
     *     gridcoverages, etc)
     */
    private void handleLayers() {
      start("Layer");

      final List<LayerInfo> layers;

      // filter the layers if a namespace filter has been set
      if (request.getNamespace() != null) {
        final List<LayerInfo> allLayers = wmsConfig.getLayers();
        layers = new ArrayList<LayerInfo>();

        String namespace = wmsConfig.getNamespaceByPrefix(request.getNamespace());
        for (LayerInfo layer : allLayers) {
          Name name = layer.getResource().getQualifiedName();
          if (name.getNamespaceURI().equals(namespace)) {
            layers.add(layer);
          }
        }
      } else {
        layers = wmsConfig.getLayers();
      }

      WMSInfo serviceInfo = wmsConfig.getServiceInfo();
      element("Title", serviceInfo.getTitle());
      element("Abstract", serviceInfo.getAbstract());

      List<String> srsList = serviceInfo.getSRS();
      Set<String> srs = new HashSet<String>();
      if (srsList != null) {
        srs.addAll(srsList);
      }
      handleRootCrsList(srs);

      handleRootBbox(layers);

      // now encode each layer individually
      LayerTree featuresLayerTree = new LayerTree(layers);
      handleLayerTree(featuresLayerTree);

      try {
        List<LayerGroupInfo> layerGroups = wmsConfig.getLayerGroups();
        handleLayerGroups(new ArrayList<LayerGroupInfo>(layerGroups));
      } catch (FactoryException e) {
        throw new RuntimeException("Can't obtain Envelope of Layer-Groups: " + e.getMessage(), e);
      } catch (TransformException e) {
        throw new RuntimeException("Can't obtain Envelope of Layer-Groups: " + e.getMessage(), e);
      }

      end("Layer");
    }
Ejemplo n.º 3
0
 @Override
 public AbstractLayerSourceAssistantPage getNextPage() {
   final LayerSourcePageContext context = getContext();
   try {
     final Product product = context.getAppContext().getSelectedProduct();
     final GeoPos referencePos = ProductUtils.getCenterGeoPos(product);
     final CoordinateReferenceSystem crs = crsSelectionPanel.getCrs(referencePos);
     context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FEATURE_COLLECTION_CRS, crs);
     return new ShapefileAssistantPage3();
   } catch (FactoryException e) {
     e.printStackTrace();
     context.showErrorDialog("Could not create CRS:\n" + e.getMessage());
   }
   return null;
 }
Ejemplo n.º 4
0
  public void reproject(
      Coordinate coordinate, final CoordinateSystem source, final CoordinateSystem destiny) {
    try {

      // CRSAuthorityFactory crsFactory = FactoryFinder.getCRSAuthorityFactory("EPSG", null);
      CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:" + source.getEPSGCode());
      CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:" + destiny.getEPSGCode());
      MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
      GeometryFactory h = AppContext.getApplicationContext().getGeometryFactory();
      h = new GeometryFactory(h.getPrecisionModel(), destiny.getEPSGCode());
      Coordinate coordinateFinal = coordinate;
      JTS.transform(coordinate, coordinateFinal, transform);
    } catch (NoSuchAuthorityCodeException e) {
      JOptionPane.showMessageDialog(null, e.getMessage());
    } catch (FactoryException e) {
      JOptionPane.showMessageDialog(null, e.getMessage());
    } catch (VerifyError e) {
      JOptionPane.showMessageDialog(null, e.getMessage());
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, e.getMessage());
    }
  }
Ejemplo n.º 5
0
  // Constructor
  public CrsUtil(String sCrs, String tCrs) throws WCSException {
    sCrsID = null;
    tCrsID = null;

    try {
      //
      crssMap = new ArrayList<String>(2);
      crssMap.addAll(Arrays.asList(sCrs, tCrs));

      if (CrsUtil.loadedTransforms.containsKey(crssMap)) {
        log.info("CRS transform already loaded in memory.");
      } else {
        log.info("Previously unused CRS transform: create and load in memory.");
        sCrsID = CRS.decode("EPSG:" + extractCode(sCrs));
        tCrsID = CRS.decode("EPSG:" + extractCode(tCrs));
        MathTransform transform = CRS.findMathTransform(sCrsID, tCrsID);
        CrsUtil.loadedTransforms.put(crssMap, transform);
      }
    } catch (NoSuchAuthorityCodeException e) {
      log.error(
          "Could not find CRS "
              + (sCrsID == null ? sCrs : tCrs)
              + " on the EPSG db: CRS transform impossible.");
      throw new WCSException(
          ExceptionCode.InvalidMetadata,
          "Unsopported or invalid CRS \"" + (sCrsID == null ? sCrs : tCrs) + "\".");
    } catch (FactoryException e) {
      log.error(
          "Error while decoding CRS " + (sCrsID == null ? sCrs : tCrs) + "\n" + e.getMessage());
      throw new WCSException(
          ExceptionCode.InternalComponentError, "Error while instanciating new CrsUtil object.\".");
    } catch (Exception e) {
      log.error(e.getMessage());
      throw new WCSException(
          ExceptionCode.InternalComponentError, "Error while instanciating new CrsUtil object.\".");
    }
  }
  @DescribeResult(
      name = "UrbanGridCUDAProcess",
      description = "Urban Grid indexes calculated using CUDA",
      type = List.class)
  public List<StatisticContainer> execute(
      @DescribeParameter(name = "reference", description = "Name of the reference raster")
          GridCoverage2D referenceCoverage,
      @DescribeParameter(name = "now", description = "Name of the new raster")
          GridCoverage2D nowCoverage,
      @DescribeParameter(name = "index", min = 1, description = "Index to calculate") int index,
      @DescribeParameter(
              name = "subindex",
              min = 0,
              description = "String indicating which sub-index must be calculated")
          String subId,
      @DescribeParameter(name = "pixelarea", min = 0, description = "Pixel Area") Double pixelArea,
      @DescribeParameter(name = "rois", min = 1, description = "Administrative Areas")
          List<Geometry> rois,
      @DescribeParameter(name = "populations", min = 0, description = "Populations for each Area")
          List<List<Integer>> populations,
      @DescribeParameter(
              name = "coefficient",
              min = 0,
              description = "Multiplier coefficient for index 10")
          Double coeff,
      @DescribeParameter(name = "rural", min = 0, description = "Rural or Urban index")
          boolean rural,
      @DescribeParameter(name = "radius", min = 0, description = "Radius in meters") int radius)
      throws IOException {

    // Check on the index 7
    boolean nullSubId = subId == null || subId.isEmpty();
    boolean subIndexA = !nullSubId && subId.equalsIgnoreCase("a");
    boolean subIndexC = !nullSubId && subId.equalsIgnoreCase("c");
    boolean subIndexB = !nullSubId && subId.equalsIgnoreCase("b");
    if (index == SEVENTH_INDEX && (nullSubId || !(subIndexA || subIndexB || subIndexC))) {
      throw new IllegalArgumentException("Wrong subindex for index 7");
    }
    // Check if almost one coverage is present
    if (referenceCoverage == null && nowCoverage == null) {
      throw new IllegalArgumentException("No input Coverage provided");
    }

    double areaPx;
    if (pixelArea == null) {
      areaPx = PIXEL_AREA;
    } else {
      areaPx = pixelArea;
    }

    // Check if Geometry area or perimeter must be calculated
    boolean inRasterSpace = true;
    // Selection of the operation to do for each index
    switch (index) {
      case FIFTH_INDEX:
      case SIXTH_INDEX:
      case SEVENTH_INDEX:
      case ELEVENTH_INDEX:
      case TWELVE_INDEX:
        if (!subIndexA) {
          inRasterSpace = false;
        }
        break;
      default:
        break;
    }

    // If the index is 7a-8-9-10 then the input Geometries must be transformed to the Model Space
    List<Geometry> geoms = new ArrayList<Geometry>();
    final AffineTransform gridToWorldCorner =
        (AffineTransform)
            ((GridGeometry2D) referenceCoverage.getGridGeometry())
                .getGridToCRS2D(PixelOrientation.UPPER_LEFT);
    if (inRasterSpace) {
      for (Geometry geo : rois) {
        try {
          geoms.add(JTS.transform(geo, ProjectiveTransform.create(gridToWorldCorner)));
        } catch (MismatchedDimensionException e) {
          LOGGER.log(Level.SEVERE, e.getMessage(), e);
          throw new ProcessException(e);
        } catch (TransformException e) {
          LOGGER.log(Level.SEVERE, e.getMessage(), e);
          throw new ProcessException(e);
        }
      }
    } else {
      geoms.addAll(rois);
    }

    // Check if the Geometries must be reprojected
    /*        Object userData = geoms.get(0).getUserData();
            if (!inRasterSpace && userData instanceof CoordinateReferenceSystem) {
                CoordinateReferenceSystem geomCRS = (CoordinateReferenceSystem) userData;
                CoordinateReferenceSystem refCRS = referenceCoverage.getCoordinateReferenceSystem();
                MathTransform tr = null;
                try {
                    tr = CRS.findMathTransform(geomCRS, refCRS);

                    if (!(tr == null || tr.isIdentity())) {
                        int geosize = geoms.size();
                        for (int i = 0; i < geosize; i++) {
                            Geometry geo = geoms.get(i);
                            Geometry transform = JTS.transform(geo, tr);
                            transform.setUserData(refCRS);
                            geoms.set(i, transform);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, e.getMessage(), e);
                    throw new ProcessException(e);
                }
                // Otherwise only set the correct User_Data parameter
            } else if (inRasterSpace){
    */ int geosize = geoms.size();
    final CoordinateReferenceSystem refCrs = referenceCoverage.getCoordinateReferenceSystem();
    for (int i = 0; i < geosize; i++) {
      Geometry geo = geoms.get(i);

      geo.setUserData(refCrs);

      if (geo.getSRID() == 0) {
        try {
          geo.setSRID(CRS.lookupEpsgCode(refCrs, true));
        } catch (FactoryException e) {
          LOGGER.log(Level.WARNING, e.getMessage(), e);
        }
      }
    }
    //        }

    // Empty arrays containing the statistics results
    double[] statsRef = null;
    double[] statsNow = null;
    double[][][] statsComplex = null;

    // Create a new List of CUDA Bean objects
    List<CUDABean> beans = new ArrayList<CUDABean>();

    // Loop around all the Geometries and generate a new CUDA Bean object
    try {
      // MathTransform transform = ProjectiveTransform.create(gridToWorldCorner).inverse();
      int counter = 0;
      int buffer = (index == 12 ? radius : 0);
      for (Geometry geo : geoms) {
        // Create the CUDABean object
        CUDABean bean = new CUDABean();
        bean.setAreaPix(areaPx);

        // Populate it with Reference coverage parameters
        populateBean(bean, true, referenceCoverage, geo, null, buffer);

        // Set the population values if needed
        if (populations != null) {
          Integer popRef = populations.get(0).get(counter);
          bean.setPopRef(popRef);
        }

        // Do the same for the Current Coverage if present
        if (nowCoverage != null) {
          populateBean(bean, false, nowCoverage, geo, null, buffer);
          // Set the population values if needed
          if (populations != null) {
            Integer popCur = populations.get(1).get(counter);
            bean.setPopCur(popCur);
          }
        }
        // Add the bean to the list
        beans.add(bean);
        // Update counter
        counter++;
      }
    } catch (Exception e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      throw new ProcessException(e);
    }

    // Calculate the index using CUDA
    //		System.out.println(
    // java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()) );
    //      long startTime = System.currentTimeMillis();
    /**
     * Generalize: > isUrban = false/true ------------------------| > RADIUS [meters] = scalar
     * ---------------------------------|
     */
    Object output = null;
    try {
      output = calculateCUDAIndex(index, subId, beans, rural, radius);
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    //		long estimatedTime = System.currentTimeMillis() - startTime;
    //		System.out.println("Elapsed time calculateCUDAIndex()\t--> " + estimatedTime + " [ms]");
    Rectangle refRect =
        PlanarImage.wrapRenderedImage(referenceCoverage.getRenderedImage()).getBounds();

    // For index 8 calculate the final Image
    if (index == 8 || index == 9 || index == 12) {

      System.out.println("rural=" + rural + " -- radius/buffer=" + radius + " [m]");

      List<StatisticContainer> results = new ArrayList<CLCProcess.StatisticContainer>();
      StatisticContainer stats = new StatisticContainer();
      double[][][] images = (double[][][]) output;

      int numGeo = beans.size();
      // Images to mosaic
      RenderedImage[] refImgs = new RenderedImage[numGeo];
      ROI[] roiObjs = new ROI[numGeo];

      // Giuliano tested for 91 municipalities in NAPLES and it FAILED within the following FOR
      // loop!!
      for (int i = 0; i < numGeo; i++) {
        double[][] refData = images[i];
        CUDABean bean = beans.get(i);
        double[] data = refData[0];
        if (data != null) {
          Rectangle rect =
              new Rectangle(bean.getMinX(), bean.getMinY(), bean.getWidth(), bean.getHeight());
          refImgs[i] = createImage(rect, data);
          roiObjs[i] = bean.getRoiObj();
        }
      }
      ImageLayout layout = new ImageLayout2();
      layout.setMinX(refRect.x);
      layout.setMinY(refRect.y);
      layout.setWidth(refRect.width);
      layout.setHeight(refRect.height);

      RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);

      // Mosaic of the images
      double[] background = (index == 8 || index == 12 ? new double[] {-1.0} : new double[] {0.0});
      RenderedImage finalRef =
          MosaicDescriptor.create(
              refImgs,
              MosaicDescriptor.MOSAIC_TYPE_OVERLAY,
              null,
              roiObjs,
              null,
              background,
              hints);

      // RenderedImageBrowser.showChain(finalRef, false, false);

      // Upgrade of the statistics container
      stats.setReferenceImage(finalRef);
      // Check if the same calculations must be done for the Current coverage
      if (nowCoverage != null && index != 9) {
        RenderedImage[] currImgs = new RenderedImage[numGeo];
        RenderedImage[] diffImgs = new RenderedImage[numGeo];
        for (int i = 0; i < numGeo; i++) {
          CUDABean bean = beans.get(i);
          double[] data = images[i][1];
          double[] diff = images[i][2];
          Rectangle rect =
              new Rectangle(bean.getMinX(), bean.getMinY(), bean.getWidth(), bean.getHeight());
          currImgs[i] = createImage(rect, data);
          diffImgs[i] = createImage(rect, diff);
        }
        // Mosaic of the images
        RenderedImage finalCurr =
            MosaicDescriptor.create(
                currImgs,
                MosaicDescriptor.MOSAIC_TYPE_OVERLAY,
                null,
                roiObjs,
                null,
                background,
                hints);

        // Mosaic of the images
        RenderedImage finalDiff =
            MosaicDescriptor.create(
                diffImgs,
                MosaicDescriptor.MOSAIC_TYPE_OVERLAY,
                null,
                roiObjs,
                null,
                background,
                hints);
        // Update the statistics container
        stats.setNowImage(finalCurr);
        stats.setDiffImage(finalDiff);
      }
      results.add(stats);
      return results;
    }
    /*else if (index == 9) {// LAND TAKE
        double[][][] values = (double[][][]) output;
        statsRef = values[0][0];
        statsNow = values[0].length > 1 ? values[0][1] : null;
    }*/
    else if (index == 11) { // MODEL OF URBAN DEVELOPMENT
      statsComplex = (double[][][]) output;
    } else {
      double[][][] values = (double[][][]) output;
      statsRef = new double[values.length];
      statsNow = (values[0][0].length > 1 ? new double[values.length] : null);

      for (int v = 0; v < values.length; v++) {
        statsRef[v] = values[v][0][0];
        if (values[v][0].length > 1) {
          statsNow[v] = values[v][0][1];
        }
      }
    }

    // Result accumulation
    List<StatisticContainer> results = accumulateResults(rois, statsRef, statsNow, statsComplex);

    return results;
  }