/** put all the needed things in the blackboards */
  private void commitToBlackboards(
      JGrassRegion jgR, CoordinateReferenceSystem crs, String windPath) {
    blackboard = getLayer().getMap().getBlackboard();

    style.north = (float) jgR.getNorth();
    style.south = (float) jgR.getSouth();
    style.east = (float) jgR.getEast();
    style.west = (float) jgR.getWest();
    style.rows = jgR.getRows();
    style.cols = jgR.getCols();

    style.windPath = windPath;

    try {

      try {
        Integer epsg = CRS.lookupEpsgCode(crs, true);
        style.crsString = "EPSG:" + epsg;
      } catch (Exception e) {
        // try non epsg
        style.crsString = CRS.lookupIdentifier(crs, true);
      }
    } catch (FactoryException e) {
      e.printStackTrace();
    }

    blackboard.put(ActiveregionStyleContent.ID, style);
    getLayer().setStatus(ILayer.DONE);
  }
Пример #2
0
 /**
  * Prints a list of CRS that can't be instantiated. This is used for implementation of {@linkplain
  * #main main method} in order to check the content of the {@value #FILENAME} file (or whatever
  * property file used as backing store for this factory) from the command line.
  *
  * @param out The writer where to print the report.
  * @return The set of codes that can't be instantiated.
  * @throws FactoryException if an error occured while {@linkplain #getAuthorityCodes fetching
  *     authority codes}.
  * @since 2.4
  */
 protected Set reportInstantiationFailures(final PrintWriter out) throws FactoryException {
   final Set<String> codes = getAuthorityCodes(CoordinateReferenceSystem.class);
   final Map<String, String> failures = new TreeMap<String, String>();
   for (final String code : codes) {
     try {
       createCoordinateReferenceSystem(code);
     } catch (FactoryException exception) {
       failures.put(code, exception.getLocalizedMessage());
     }
   }
   if (!failures.isEmpty()) {
     final TableWriter writer = new TableWriter(out, " ");
     for (final Map.Entry<String, String> entry : failures.entrySet()) {
       writer.write(entry.getKey());
       writer.write(':');
       writer.nextColumn();
       writer.write(entry.getValue());
       writer.nextLine();
     }
     try {
       writer.flush();
     } catch (IOException e) {
       // Should not happen, since we are writting to a PrintWriter
       throw new AssertionError(e);
     }
   }
   return failures.keySet();
 }
Пример #3
0
 /**
  * Returns a new bounding box which contains the transformed shape of this bounding box. This is a
  * convenience method that delegate its work to the {@link #transform transform} method.
  *
  * @since 2.4
  */
 public BoundingBox toBounds(final CoordinateReferenceSystem targetCRS) throws TransformException {
   try {
     return transform(targetCRS, true);
   } catch (FactoryException e) {
     throw new TransformException(e.getLocalizedMessage(), e);
   }
 }
Пример #4
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;
  }
Пример #5
0
  public AssignHomeFacilities(DataPool dataPool) {
    facilities = (FacilityData) dataPool.get(FacilityDataLoader.KEY);

    try {
      transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, CRSUtils.getCRS(31467));
    } catch (FactoryException e) {
      e.printStackTrace();
    }
  }
  private static void forceSRS(GetMapRequest getMap, String srs) {
    getMap.setSRS(srs);

    try {
      getMap.setCrs(CRS.decode(srs));
    } catch (NoSuchAuthorityCodeException e) {
      e.printStackTrace();
    } catch (FactoryException e) {
      e.printStackTrace();
    }
  }
    /**
     * 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");
    }
Пример #8
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;
 }
  /**
   * We have made this visible so that WMSDescribeLayer (used by InfoView2) can figure out how to
   * make the *exact* same request in order to a getInfo operation. We should really store the last
   * request on the layer blackboard for this intra module communication.
   *
   * @return SRS code
   */
  public static String findRequestCRS(
      List<Layer> layers, CoordinateReferenceSystem viewportCRS, IMap map) {
    String requestCRS = null;

    if (layers == null || layers.isEmpty()) {
      return null;
    }

    Collection<String> viewportEPSG = extractEPSG(map, viewportCRS);
    if (viewportEPSG != null) {
      String match = matchEPSG(layers, viewportEPSG);
      if (match != null) return match;
    }

    if (matchEPSG(layers, EPSG_4326)) return EPSG_4326;

    if (matchEPSG(layers, EPSG_4269)) {
      return EPSG_4269;
    }

    Layer firstLayer = layers.get(0);
    for (Object object : firstLayer.getSrs()) {
      String epsgCode = (String) object;

      try {
        // Check to see if *we* can actually use this code first.
        CRS.decode(epsgCode);
      } catch (NoSuchAuthorityCodeException e) {
        continue;
      } catch (FactoryException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      if (matchEPSG(layers, epsgCode)) {
        requestCRS = epsgCode;
        return requestCRS;
      }
    }

    if (requestCRS == null) {
      // Hmm. Our layers have no SRS in common - we are in an illegal state
      WMSPlugin.log(
          "ERROR: Illegal State: Basic WMS Renderer contains layers with no common CRS. Unable to perform request."); //$NON-NLS-1$
      return null;
    }
    return requestCRS;
  }
Пример #10
0
  public void reproject(
      Coordinate coordinate, final CoordinateSystem source, final CoordinateSystem destiny) {
    try {

      Coordinate coordinateSource = new Coordinate();
      Coordinate coordinateTarget = new Coordinate();
      if (source.getName().startsWith("Geographics")) {
        coordinateSource.x = coordinate.y;
        coordinateSource.y = coordinate.x;
      } else {
        coordinateSource.x = coordinate.x;
        coordinateSource.y = coordinate.y;
      }

      CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:" + source.getEPSGCode());
      CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:" + destiny.getEPSGCode());

      MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);

      JTS.transform(coordinateSource, coordinateTarget, transform);

      if (destiny.getName().startsWith("Geographics")) {
        coordinate.x = coordinateTarget.y;
        coordinate.y = coordinateTarget.x;
      } else {
        coordinate.x = coordinateTarget.x;
        coordinate.y = coordinateTarget.y;
      }

    } catch (NoSuchAuthorityCodeException e) {
      e.printStackTrace();

    } catch (FactoryException e) {
      e.printStackTrace();

    } catch (VerifyError e) {
      e.printStackTrace();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #11
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());
    }
  }
Пример #12
0
 /** Returns a projected CRS for test purpose. */
 private static CoordinateReferenceSystem getProjectedCRS(final GridCoverage2D coverage) {
   try {
     final GeographicCRS base = (GeographicCRS) coverage.getCoordinateReferenceSystem();
     final Ellipsoid ellipsoid = base.getDatum().getEllipsoid();
     final DefaultMathTransformFactory factory = new DefaultMathTransformFactory();
     final ParameterValueGroup parameters = factory.getDefaultParameters("Oblique_Stereographic");
     parameters.parameter("semi_major").setValue(ellipsoid.getSemiMajorAxis());
     parameters.parameter("semi_minor").setValue(ellipsoid.getSemiMinorAxis());
     parameters.parameter("central_meridian").setValue(5);
     parameters.parameter("latitude_of_origin").setValue(-5);
     final MathTransform mt;
     try {
       mt = factory.createParameterizedTransform(parameters);
     } catch (FactoryException exception) {
       fail(exception.getLocalizedMessage());
       return null;
     }
     return new DefaultProjectedCRS("Stereographic", base, mt, DefaultCartesianCS.PROJECTED);
   } catch (NoSuchIdentifierException exception) {
     fail(exception.getLocalizedMessage());
     return null;
   }
 }
Пример #13
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;
  }
Пример #15
0
  public static void write(
      Network network, LinkOccupancyCalculator linkVols, double factor, String file) {
    Map<Link, Double> volumes = new HashMap<>(network.getLinks().size());
    Map<Link, Double> loads = new HashMap<>(network.getLinks().size());

    double maxVolume = 0;
    double minVolume = Double.MAX_VALUE;

    for (Link link : network.getLinks().values()) {
      String linkId = link.getId().toString();
      if (!(linkId.startsWith(ODCalibrator.VIRTUAL_ID_PREFIX) || linkId.contains(".l"))) {
        double vol = linkVols.getOccupancy(link.getId()) * factor;
        double load = vol / (link.getCapacity() * 24);
        volumes.put(link, vol);
        loads.put(link, load);

        maxVolume = Math.max(maxVolume, vol);
        minVolume = Math.min(minVolume, vol);
      }
    }

    MathTransform transform = null;
    try {
      transform = CRS.findMathTransform(CRSUtils.getCRS(31467), CRSUtils.getCRS(4326));
    } catch (FactoryException e) {
      e.printStackTrace();
    }

    GeoJSONWriter jsonWriter = new GeoJSONWriter();
    List<Feature> features = new ArrayList<>(network.getLinks().size());

    for (Link link : volumes.keySet()) {
      double coord1[] =
          new double[] {link.getFromNode().getCoord().getX(), link.getFromNode().getCoord().getY()};
      double coord2[] =
          new double[] {link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY()};

      try {
        transform.transform(coord1, 0, coord1, 0, 1);
        transform.transform(coord2, 0, coord2, 0, 1);
      } catch (TransformException e) {
        e.printStackTrace();
      }

      double coords[][] = new double[2][2];
      coords[0][0] = coord1[0];
      coords[0][1] = coord1[1];
      coords[1][0] = coord2[0];
      coords[1][1] = coord2[1];

      LineString lineString = new LineString(coords);

      Map<String, Object> properties = new HashMap<>();
      double volume = volumes.get(link);
      double load = loads.get(link);
      properties.put("volume", volume);
      properties.put("load", load);
      properties.put("capacity", link.getCapacity());
      double width = (volume - minVolume) / (maxVolume - minVolume);
      properties.put("width", width);
      Color color = ColorUtils.getRedGreenColor(load);
      properties.put("color", "#" + String.format("%06x", color.getRGB() & 0x00FFFFFF));

      Feature feature = new Feature(lineString, properties);
      features.add(feature);
    }

    try {
      FeatureCollection fCollection = jsonWriter.write(features);
      BufferedWriter writer = new BufferedWriter(new FileWriter(file));
      writer.write(fCollection.toString());
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #16
0
  private static void addSourceToRoute(Point p, boolean b) {
    // TODO Auto-generated method stub
    String[] redes = configProperties.getRedesNames();
    GeometryFactory fact = new GeometryFactory();
    try {
      if (redes != null) {

        NetworkManager networkMgr = NetworkModuleUtilWorkbench.getNetworkManager(context);

        CoordinateSystem coordSys = context.getLayerManager().getCoordinateSystem();
        if (coordSys != null) {
          p.setSRID(coordSys.getEPSGCode());
        }
        CoordinateReferenceSystem crs = CRS.decode("EPSG:" + coordSys.getEPSGCode());
        org.opengis.geometry.primitive.Point primitivePoint =
            GeographicNodeUtil.createISOPoint(p, crs);

        ExternalInfoRouteLN externalInfoRouteLN = new ExternalInfoRouteLN();
        ArrayList<VirtualNodeInfo> virtualNodesInfo = new ArrayList<VirtualNodeInfo>();
        for (int i = 0; i < redes.length; i++) {

          configuatorNetworks.put(
              redes[i], ((LocalGISNetworkManager) networkMgr).getAllNetworks().get(redes[i]));
          VirtualNodeInfo nodeInfo = null;
          try {
            nodeInfo =
                externalInfoRouteLN.getVirtualNodeInfo(
                    new GeopistaRouteConnectionFactoryImpl(),
                    primitivePoint,
                    networkMgr,
                    redes[i],
                    100);
          } catch (Exception e) {
            e.printStackTrace();
          }
          if (nodeInfo != null) {
            virtualNodesInfo.add(nodeInfo);
          }
        }
        if (virtualNodesInfo.size() == 0) return;
        Iterator<VirtualNodeInfo> it = virtualNodesInfo.iterator();
        double lastDistante = -1;
        VirtualNodeInfo selectedNodeInfo = null;
        while (it.hasNext()) {
          VirtualNodeInfo vNodeinfo = it.next();
          if (lastDistante == -1 || lastDistante > vNodeinfo.getDistance()) {
            selectedNodeInfo = vNodeinfo;
            lastDistante = vNodeinfo.getDistance();
          }
        }

        //
        //	((LocalGISNetworkManager)networkMgr).addNewVirtualNode(networkMgr.getNetwork(selectedNodeInfo.getNetworkName()).getGraph()
        //						, selectedNodeInfo.getEdge()
        //						, selectedNodeInfo.getRatio()
        //						, this);
        nodesInfo.put(selectedNodeInfo.hashCode(), selectedNodeInfo);
        //
        Coordinate coord = selectedNodeInfo.getLinestringVtoB().getCoordinateN(0);
        Point geom_nodes = fact.createPoint(coord);
        Feature feature = new BasicFeature(nodesFeatureCol.getFeatureSchema());
        feature.setGeometry(geom_nodes);
        //				feature.setAttribute("nodeId", new Integer(node.getID()));
        feature.setAttribute("nodeId", selectedNodeInfo.hashCode());
        sourcePointLayer.getFeatureCollectionWrapper().add(feature);

      } else {

      }
    } catch (NoSuchAuthorityCodeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (FactoryException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * This method tries to automatically determine SRS, bounding box and output size based on the
   * layers provided by the user and any other parameters.
   *
   * <p>If bounds are not specified by the user, they are automatically se to the union of the
   * bounds of all layers.
   *
   * <p>The size of the output image defaults to 512 pixels, the height is automatically determined
   * based on the width to height ratio of the requested layers. This is also true if either height
   * or width are specified by the user. If both height and width are specified by the user, the
   * automatically determined bounding box will be adjusted to fit inside these bounds.
   *
   * <p>General idea 1) Figure out whether SRS has been specified, fall back to EPSG:4326 2)
   * Determine whether all requested layers use the same SRS, - if so, try to do bounding box
   * calculations in native coordinates 3) Aggregate the bounding boxes (in EPSG:4326 or native) 4a)
   * If bounding box has been specified, adjust height of image to match 4b) If bounding box has not
   * been specified, but height has, adjust bounding box
   */
  public static void autoSetBoundsAndSize(GetMapRequest getMap) {
    // Get the layers
    List<MapLayerInfo> layers = getMap.getLayers();

    /** 1) Check what SRS has been requested */
    String reqSRS = getMap.getSRS();

    // if none, try to determine which SRS to use
    // and keep track of whether we can use native all the way
    boolean useNativeBounds = true;
    if (reqSRS == null) {
      reqSRS = guessCommonSRS(layers);
      forceSRS(getMap, reqSRS);
    }

    /** 2) Compare requested SRS */
    for (int i = 0; useNativeBounds && i < layers.size(); i++) {
      if (layers.get(i) != null) {
        String layerSRS = layers.get(i).getSRS();
        useNativeBounds =
            reqSRS.equalsIgnoreCase(layerSRS)
                && layers.get(i).getResource().getNativeBoundingBox() != null;
      } else {
        useNativeBounds = false;
      }
    }

    CoordinateReferenceSystem reqCRS;
    try {
      reqCRS = CRS.decode(reqSRS);
    } catch (Exception e) {
      throw new ServiceException(e);
    }

    // Ready to determine the bounds based on the layers, if not specified
    Envelope aggregateBbox = getMap.getBbox();
    boolean specifiedBbox = true;

    // If bbox is not specified by request
    if (aggregateBbox == null) {
      specifiedBbox = false;

      // Get the bounding box from the layers
      for (int i = 0; i < layers.size(); i++) {
        MapLayerInfo layerInfo = layers.get(i);
        ReferencedEnvelope curbbox;
        try {
          curbbox = layerInfo.getLatLongBoundingBox();
          if (useNativeBounds) {
            ReferencedEnvelope nativeBbox = layerInfo.getBoundingBox();
            if (nativeBbox == null) {
              try {
                CoordinateReferenceSystem nativeCrs = layerInfo.getCoordinateReferenceSystem();
                nativeBbox = curbbox.transform(nativeCrs, true);
              } catch (Exception e) {
                throw new ServiceException("Best effort native bbox computation failed", e);
              }
            }
            curbbox = nativeBbox;
          }
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
        if (aggregateBbox != null) {
          aggregateBbox.expandToInclude(curbbox);
        } else {
          aggregateBbox = curbbox;
        }
      }

      ReferencedEnvelope ref = null;
      // Reproject back to requested SRS if we have to
      if (!useNativeBounds && !reqSRS.equalsIgnoreCase(SRS)) {
        try {
          ref = new ReferencedEnvelope(aggregateBbox, CRS.decode("EPSG:4326"));
          aggregateBbox = ref.transform(reqCRS, true);
        } catch (ProjectionException pe) {
          ref.expandBy(-1 * ref.getWidth() / 50, -1 * ref.getHeight() / 50);
          try {
            aggregateBbox = ref.transform(reqCRS, true);
          } catch (FactoryException e) {
            e.printStackTrace();
          } catch (TransformException e) {
            e.printStackTrace();
          }
          // And again...
        } catch (NoSuchAuthorityCodeException e) {
          e.printStackTrace();
        } catch (TransformException e) {
          e.printStackTrace();
        } catch (FactoryException e) {
          e.printStackTrace();
        }
      }
    }

    // Just in case
    if (aggregateBbox == null) {
      forceSRS(getMap, DefaultWebMapService.SRS);
      aggregateBbox = DefaultWebMapService.BBOX;
    }

    // Start the processing of adjust either the bounding box
    // or the pixel height / width

    double bbheight = aggregateBbox.getHeight();
    double bbwidth = aggregateBbox.getWidth();
    double bbratio = bbwidth / bbheight;

    double mheight = getMap.getHeight();
    double mwidth = getMap.getWidth();

    if (mheight > 0.5 && mwidth > 0.5 && specifiedBbox) {
      // This person really doesnt want our help,
      // we'll warp it any way they like it...
    } else {
      if (mheight > 0.5 && mwidth > 0.5) {
        // Fully specified, need to adjust bbox
        double mratio = mwidth / mheight;
        // Adjust bounds to be less than ideal to meet spec
        if (bbratio > mratio) {
          // Too wide, need to increase height of bb
          double diff = ((bbwidth / mratio) - bbheight) / 2;
          aggregateBbox.expandBy(0, diff);
        } else {
          // Too tall, need to increase width of bb
          double diff = ((bbheight * mratio) - bbwidth) / 2;
          aggregateBbox.expandBy(diff, 0);
        }

        adjustBounds(reqSRS, aggregateBbox);

      } else if (mheight > 0.5) {
        mwidth = bbratio * mheight;
      } else {
        if (mwidth > 0.5) {
          mheight = (mwidth / bbratio >= 1) ? mwidth / bbratio : 1;
        } else {
          if (bbratio > 1) {
            mwidth = MAX_SIDE;
            mheight = (mwidth / bbratio >= 1) ? mwidth / bbratio : 1;
          } else {
            mheight = MAX_SIDE;
            mwidth = (mheight * bbratio >= 1) ? mheight * bbratio : 1;
          }

          // make sure OL output height is sufficient to show the OL scale bar fully
          if (mheight < MIN_OL_HEIGHT
              && ("application/openlayers".equalsIgnoreCase(getMap.getFormat())
                  || "openlayers".equalsIgnoreCase(getMap.getFormat()))) {
            mheight = MIN_OL_HEIGHT;
            mwidth = (mheight * bbratio >= 1) ? mheight * bbratio : 1;
          }
        }
      }

      // Actually set the bounding box and size of image
      getMap.setBbox(aggregateBbox);
      getMap.setWidth((int) mwidth);
      getMap.setHeight((int) mheight);
    }
  }
  /**
   * Gets the coordinate reference system that will be associated to the {@link GridCoverage} by
   * looking for a related PRJ.
   */
  protected void parsePRJFile() {
    String prjPath = null;

    this.crs = null;
    prjPath = this.parentPath + File.separatorChar + coverageName + ".prj";

    // read the prj serviceInfo from the file
    PrjFileReader projReader = null;

    FileInputStream inStream = null;
    FileChannel channel = null;
    try {
      final File prj = new File(prjPath);
      if (prj.exists() && prj.canRead()) {

        inStream = new FileInputStream(prj);
        channel = inStream.getChannel();
        projReader = new PrjFileReader(channel);
        this.crs = projReader.getCoordinateReferenceSystem();
      }
      // If some exception occurs, warn about the error but proceed
      // using a default CRS
    } catch (FileNotFoundException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
      }
    } catch (IOException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
      }
    } catch (FactoryException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
      }
    } finally {
      if (projReader != null) {
        try {
          projReader.close();
        } catch (IOException e) {
          if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
          }
        }
      }

      if (inStream != null) {
        try {
          inStream.close();
        } catch (Throwable e) {
          if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
          }
        }
      }

      if (channel != null) {
        try {
          channel.close();
        } catch (Throwable e) {
          if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
          }
        }
      }
    }
  }
Пример #19
0
  private CoordinateReferenceSystem getCRS(Object source) {
    CoordinateReferenceSystem crs = null;
    if (source instanceof File
        || (source instanceof URL && (((URL) source).getProtocol() == "file"))) {
      // getting name for the prj file
      final String sourceAsString;

      if (source instanceof File) {
        sourceAsString = ((File) source).getAbsolutePath();
      } else {
        String auth = ((URL) source).getAuthority();
        String path = ((URL) source).getPath();
        if (auth != null && !auth.equals("")) {
          sourceAsString = "//" + auth + path;
        } else {
          sourceAsString = path;
        }
      }

      final int index = sourceAsString.lastIndexOf(".");
      final String base =
          index > 0 ? sourceAsString.substring(0, index) + ".prj" : sourceAsString + ".prj";

      // does it exist?
      final File prjFile = new File(base.toString());
      if (prjFile.exists()) {
        // it exists then we have top read it
        PrjFileReader projReader = null;
        FileInputStream instream = null;
        try {
          instream = new FileInputStream(prjFile);
          final FileChannel channel = instream.getChannel();
          projReader = new PrjFileReader(channel);
          crs = projReader.getCoordinateReferenceSystem();
        } catch (FileNotFoundException e) {
          // warn about the error but proceed, it is not fatal
          // we have at least the default crs to use
          LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
        } catch (IOException e) {
          // warn about the error but proceed, it is not fatal
          // we have at least the default crs to use
          LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
        } catch (FactoryException e) {
          // warn about the error but proceed, it is not fatal
          // we have at least the default crs to use
          LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
        } finally {
          if (projReader != null)
            try {
              projReader.close();
            } catch (IOException e) {
              // warn about the error but proceed, it is not fatal
              // we have at least the default crs to use
              LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }

          if (instream != null)
            try {
              instream.close();
            } catch (IOException e) {
              // warn about the error but proceed, it is not fatal
              // we have at least the default crs to use
              LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }
        }
      }
    }
    return crs;
  }
  private void computeCropBBOX() throws DataSourceException {

    // get the crs for the requested bbox
    if (requestCRS == null)
      requestCRS = CRS.getHorizontalCRS(requestedBBox.getCoordinateReferenceSystem());
    try {

      //
      // The destination to source transform has been computed (and eventually erased) already
      // by inspectCoordinateSystem()

      // now transform the requested envelope to source crs
      if (destinationToSourceTransform != null && !destinationToSourceTransform.isIdentity()) {
        final GeneralEnvelope temp =
            new GeneralEnvelope(CRS.transform(requestedBBox, coverageProperties.crs2D));
        temp.setCoordinateReferenceSystem(coverageProperties.crs2D);
        cropBBox = new ReferencedEnvelope(temp);
        needsReprojection = true;

      } else {
        // we do not need to do anything, but we do this in order to aboid problems with the
        // envelope checks
        cropBBox =
            new ReferencedEnvelope(
                requestedBBox.getMinX(),
                requestedBBox.getMaxX(),
                requestedBBox.getMinY(),
                requestedBBox.getMaxY(),
                coverageProperties.crs2D);
      }

      // intersect requested BBox in native CRS with coverage native bbox to get the crop bbox
      // intersect the requested area with the bounds of this layer in native crs
      if (!cropBBox.intersects((BoundingBox) coverageProperties.bbox)) {
        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.fine(
              new StringBuilder("The computed CropBoundingBox ")
                  .append(cropBBox)
                  .append(" Doesn't intersect the coverage BoundingBox ")
                  .append(coverageProperties.bbox)
                  .append(" resulting in an empty request")
                  .toString());
        }
        cropBBox = null;
        empty = true;
        return;
      }
      // TODO XXX Optimize when referenced envelope has intersection method that actually retains
      // the CRS, this is the JTS one
      cropBBox =
          new ReferencedEnvelope(
              ((ReferencedEnvelope) cropBBox).intersection(coverageProperties.bbox),
              coverageProperties.crs2D);

      return;
    } catch (TransformException te) {
      // something bad happened while trying to transform this
      // envelope. let's try with wgs84
      if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, te.getLocalizedMessage(), te);
    }

    try {
      // can we proceed? Do we have geo stuff to do all these operations?
      if (coverageProperties.geographicCRS2D != null && coverageProperties.geographicBBox != null) {

        //
        // If we can not reproject the requested envelope to the native CRS,
        // we go back to reproject in the geographic crs of the native
        // coverage since this usually happens for conversions between CRS
        // whose area of definition is different
        //

        // STEP 1 reproject the requested envelope to the coverage geographic bbox
        if (!CRS.equalsIgnoreMetadata(coverageProperties.geographicCRS2D, requestCRS)) {
          // try to convert the requested bbox to the coverage geocrs
          requestCRSToCoverageGeographicCRS2D =
              CRS.findMathTransform(requestCRS, coverageProperties.geographicCRS2D, true);
          if (!requestCRSToCoverageGeographicCRS2D.isIdentity()) {
            requestedBBOXInCoverageGeographicCRS =
                CRS.transform(requestedBBox, coverageProperties.geographicCRS2D);
            requestedBBOXInCoverageGeographicCRS.setCoordinateReferenceSystem(
                coverageProperties.geographicCRS2D);
          }
        }
        if (requestedBBOXInCoverageGeographicCRS == null) {
          requestedBBOXInCoverageGeographicCRS = new GeneralEnvelope(requestCRS);
        }

        // STEP 2 intersection with the geographic bbox for this coverage
        if (!requestedBBOXInCoverageGeographicCRS.intersects(
            coverageProperties.geographicBBox, true)) {
          cropBBox = null;
          empty = true;
          return;
        }
        // intersect with the coverage native geographic bbox
        // note that for the moment we got to use general envelope since there is no intersection
        // otherwise
        requestedBBOXInCoverageGeographicCRS.intersect(coverageProperties.geographicBBox);
        requestedBBOXInCoverageGeographicCRS.setCoordinateReferenceSystem(
            coverageProperties.geographicCRS2D);

        // now go back to the coverage native CRS in order to compute an approximate requested
        // resolution
        approximateRequestedBBoInNativeCRS =
            CRS.transform(requestedBBOXInCoverageGeographicCRS, coverageProperties.crs2D);
        approximateRequestedBBoInNativeCRS.setCoordinateReferenceSystem(coverageProperties.crs2D);
        cropBBox = new ReferencedEnvelope(approximateRequestedBBoInNativeCRS);
        return;
      }

    } catch (TransformException te) {
      // something bad happened while trying to transform this
      // envelope. let's try with wgs84
      if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, te.getLocalizedMessage(), te);
    } catch (FactoryException fe) {
      // something bad happened while trying to transform this
      // envelope. let's try with wgs84
      if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, fe.getLocalizedMessage(), fe);
    }

    LOGGER.log(
        Level.INFO,
        "We did not manage to crop the requested envelope, we fall back onto loading the whole coverage.");
    cropBBox = null;
  }