Search in sources :

Example 1 with EstimatedGridGeometry

use of org.geotoolkit.coverage.grid.EstimatedGridGeometry in project geotoolkit by Geomatys.

the class Layer method getGridGeometry2D.

@Override
public GridGeometry getGridGeometry2D() {
    if (getBoundingBox().isEmpty()) {
        final AbstractGeographicBoundingBox bbox = getLatLonBoundingBox();
        if (bbox != null) {
            GeneralEnvelope env = new GeneralEnvelope(CommonCRS.WGS84.normalizedGeographic());
            env.setRange(0, bbox.getWestBoundLongitude(), bbox.getEastBoundLongitude());
            env.setRange(1, bbox.getSouthBoundLatitude(), bbox.getNorthBoundLatitude());
            return new GridGeometry(null, env, GridOrientation.HOMOTHETY);
        }
        return null;
    }
    final BoundingBox bbox = getBoundingBox().get(0);
    try {
        GeneralEnvelope env = new GeneralEnvelope(CRS.forCode(bbox.getCRSCode()));
        env.setRange(0, bbox.getMinx(), bbox.getMaxx());
        env.setRange(1, bbox.getMiny(), bbox.getMaxy());
        Double resx = bbox.getResx();
        Double resy = bbox.getResy();
        if (resx != null && resy != null) {
            return new EstimatedGridGeometry(env, new double[] { resx, resy });
        } else {
            return new GridGeometry(null, env, GridOrientation.HOMOTHETY);
        }
    } catch (FactoryException e) {
        Logger.getLogger("org.geotoolkit.wms.xml.v110").warning(e.getMessage());
    }
    return null;
}
Also used : EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) AbstractGeographicBoundingBox(org.geotoolkit.wms.xml.AbstractGeographicBoundingBox) FactoryException(org.opengis.util.FactoryException) AbstractGeographicBoundingBox(org.geotoolkit.wms.xml.AbstractGeographicBoundingBox) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope)

Example 2 with EstimatedGridGeometry

use of org.geotoolkit.coverage.grid.EstimatedGridGeometry in project geotoolkit by Geomatys.

the class AggregatedCoverageResource method initGridGeometry.

private void initGridGeometry() throws DataStoreException {
    if (cachedGridGeometry != null)
        return;
    tree = new Quadtree();
    final Map<GridCoverageResource, GridGeometry> components = new HashMap<>();
    for (VirtualBand band : bands) {
        for (Source source : band.sources) {
            try {
                final GridGeometry gridGeometry = source.resource.getGridGeometry();
                if (!(gridGeometry.isDefined(GridGeometry.CRS) && gridGeometry.isDefined(GridGeometry.ENVELOPE))) {
                    throw new DataStoreException("Resource has no defined CRS and Envelope.");
                }
                final CoordinateReferenceSystem crs = gridGeometry.getCoordinateReferenceSystem();
                if (crs instanceof ImageCRS) {
                    throw new DataStoreException("CRS " + crs.getClass() + " can not be used in aggregation, resource will be ignored.");
                } else if (crs != null && crs.getCoordinateSystem().getDimension() != 2) {
                    throw new DataStoreException("CRS " + crs.getName() + " can not be used in aggregation it is not 2D, resource will be ignored.");
                }
                components.put(source.resource, gridGeometry);
            } catch (Exception ex) {
                if (neverfail) {
                    this.cachedGridGeometry = new GridGeometry(new GridExtent(1, 1), null, GridOrientation.HOMOTHETY);
                    LOGGER.log(Level.INFO, "Failed to extract grid geometry crs or envelope from resource " + resourceName(source.resource) + " : " + ex.getMessage());
                    source.inMetaError = true;
                } else {
                    throw ex;
                }
            }
        }
    }
    if (components.isEmpty()) {
        // no data yet
        this.cachedGridGeometry = new GridGeometry(new GridExtent(1, 1), null, GridOrientation.HOMOTHETY);
        return;
    } else if (components.size() == 1) {
        // copy exact definition
        final Map.Entry<GridCoverageResource, GridGeometry> entry = components.entrySet().iterator().next();
        final GridCoverageResource resource = entry.getKey();
        final GridGeometry gridGeometry = entry.getValue();
        if (outputCrs == null || Utilities.equalsIgnoreMetadata(outputCrs, gridGeometry.getCoordinateReferenceSystem())) {
            this.cachedGridGeometry = gridGeometry;
            final JTSEnvelope2D key = new JTSEnvelope2D(gridGeometry.getEnvelope());
            tree.insert(key, new IndexedResource(key, resource));
            return;
        }
    }
    if (outputCrs == null) {
        // use most common crs
        // TODO find a better approach to determinate a common crs
        final FrequencySortedSet<CoordinateReferenceSystem> map = new FrequencySortedSet<>();
        for (Map.Entry<GridCoverageResource, GridGeometry> entry : components.entrySet()) {
            map.add(entry.getValue().getCoordinateReferenceSystem());
        }
        outputCrs = map.last();
    }
    // compute envelope and check sample dimensions
    GeneralEnvelope env = new GeneralEnvelope(outputCrs);
    env.setToNaN();
    int index = 0;
    double[] estimatedResolution = new double[outputCrs.getCoordinateSystem().getDimension()];
    Arrays.fill(estimatedResolution, Double.POSITIVE_INFINITY);
    // if all coverage resources have the same grid geometry we can use it directly
    GridGeometry sharedGrid = components.entrySet().iterator().next().getValue();
    if (!Utilities.equalsIgnoreMetadata(sharedGrid.getCoordinateReferenceSystem(), outputCrs)) {
        sharedGrid = null;
    }
    for (Map.Entry<GridCoverageResource, GridGeometry> entry : components.entrySet()) {
        final GridCoverageResource resource = entry.getKey();
        final GridGeometry componentGrid = entry.getValue();
        if (sharedGrid != null && !sharedGrid.equals(componentGrid)) {
            // this coverage has a different grid
            sharedGrid = null;
        }
        Envelope envelope = componentGrid.getEnvelope();
        try {
            envelope = Envelopes.transform(envelope, outputCrs);
        } catch (TransformException ex) {
            if (neverfail) {
                LOGGER.log(Level.INFO, "Failed to transform resource envelope" + resourceName(resource) + " : " + ex.getMessage());
                continue;
            } else {
                throw new DataStoreException(ex.getMessage(), ex);
            }
        }
        final JTSEnvelope2D key = new JTSEnvelope2D(envelope);
        tree.insert(key, new IndexedResource(key, resource));
        // try to find an estimated resolution
        if (estimatedResolution != null) {
            try {
                final double[] est = CoverageUtilities.estimateResolution(componentGrid.getEnvelope(), componentGrid.getResolution(true), outputCrs);
                for (int i = 0; i < estimatedResolution.length; i++) {
                    estimatedResolution[i] = Math.min(estimatedResolution[i], est[i]);
                }
            } catch (FactoryException | MismatchedDimensionException | TransformException | IncompleteGridGeometryException ex) {
                estimatedResolution = null;
            }
        }
        if (env.isAllNaN()) {
            env.setEnvelope(envelope);
        } else {
            env.add(envelope);
        }
    }
    if (sharedGrid != null) {
        cachedGridGeometry = sharedGrid;
    } else if (env.isAllNaN()) {
        // could not extract any usefull information from datas
        this.cachedGridGeometry = new GridGeometry(new GridExtent(1, 1), null, GridOrientation.HOMOTHETY);
    } else if (estimatedResolution != null) {
        cachedGridGeometry = new EstimatedGridGeometry(env, estimatedResolution);
    } else {
        cachedGridGeometry = new GridGeometry(null, env, GridOrientation.HOMOTHETY);
    }
}
Also used : GridExtent(org.apache.sis.coverage.grid.GridExtent) FactoryException(org.opengis.util.FactoryException) FrequencySortedSet(org.apache.sis.util.collection.FrequencySortedSet) Envelope(org.opengis.geometry.Envelope) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope) MismatchedDimensionException(org.opengis.geometry.MismatchedDimensionException) EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) Entry(java.util.Map.Entry) GridCoverageResource(org.apache.sis.storage.GridCoverageResource) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) DataStoreException(org.apache.sis.storage.DataStoreException) TransformException(org.opengis.referencing.operation.TransformException) NoninvertibleTransformException(org.opengis.referencing.operation.NoninvertibleTransformException) TransformException(org.opengis.referencing.operation.TransformException) IncompleteGridGeometryException(org.apache.sis.coverage.grid.IncompleteGridGeometryException) NoSuchDataException(org.apache.sis.storage.NoSuchDataException) FactoryException(org.opengis.util.FactoryException) MismatchedDimensionException(org.opengis.geometry.MismatchedDimensionException) NoninvertibleTransformException(org.opengis.referencing.operation.NoninvertibleTransformException) DataStoreException(org.apache.sis.storage.DataStoreException) BackingStoreException(org.apache.sis.util.collection.BackingStoreException) InterruptedStoreException(org.geotoolkit.storage.InterruptedStoreException) DisjointExtentException(org.apache.sis.coverage.grid.DisjointExtentException) Point(java.awt.Point) Quadtree(org.locationtech.jts.index.quadtree.Quadtree) ImageCRS(org.opengis.referencing.crs.ImageCRS) JTSEnvelope2D(org.geotoolkit.geometry.jts.JTSEnvelope2D) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope) IncompleteGridGeometryException(org.apache.sis.coverage.grid.IncompleteGridGeometryException)

Example 3 with EstimatedGridGeometry

use of org.geotoolkit.coverage.grid.EstimatedGridGeometry in project geotoolkit by Geomatys.

the class WMSUtilities method getGridGeometry.

/**
 * Find layer grid geometry.
 * This geometry only contains the envelope but may
 * also contain an approximated resolution.
 * Extra dimensions are included in the grid geometry.
 *
 * @param server web map server
 * @param layername wms layer name
 */
public static GridGeometry getGridGeometry(final WebMapClient server, final String layername) throws CapabilitiesException {
    ArgumentChecks.ensureNonNull("server", server);
    ArgumentChecks.ensureNonNull("layer name", layername);
    final AbstractWMSCapabilities capa = server.getServiceCapabilities();
    final AbstractLayer layer = capa.getLayerFromName(layername);
    if (layer == null) {
        return null;
    }
    GridGeometry layerGrid = layer.getGridGeometry2D();
    final List<AbstractDimension> dimensions = (List<AbstractDimension>) layer.getDimension();
    if (!dimensions.isEmpty()) {
        final CoordinateReferenceSystem envCRS = layerGrid.getCoordinateReferenceSystem();
        final List<CoordinateReferenceSystem> dimensionsCRS = new ArrayList<CoordinateReferenceSystem>();
        dimensionsCRS.add(envCRS);
        final List<Double> lower = new ArrayList<>();
        final List<Double> upper = new ArrayList<>();
        GeneralEnvelope layerEnvelope = new GeneralEnvelope(layerGrid.getEnvelope());
        lower.add(layerEnvelope.getMinimum(0));
        lower.add(layerEnvelope.getMinimum(1));
        upper.add(layerEnvelope.getMaximum(0));
        upper.add(layerEnvelope.getMaximum(1));
        for (final AbstractDimension dim : dimensions) {
            CoordinateReferenceSystem dimCRS = null;
            final String dimName = dim.getName();
            final String dimUnitSymbol = dim.getUnitSymbol();
            final Unit<?> unit = dimUnitSymbol != null ? Units.valueOf(dimUnitSymbol) : Units.UNITY;
            // create CRS
            if ("time".equals(dimName)) {
                dimCRS = CommonCRS.Temporal.JAVA.crs();
            } else if ("elevation".equals(dimName)) {
                dimCRS = CommonCRS.Vertical.ELLIPSOIDAL.crs();
            } else {
                final DefaultEngineeringDatum dimDatum = new DefaultEngineeringDatum(Collections.singletonMap("name", dimName));
                final CoordinateSystemAxis csAxis = new DefaultCoordinateSystemAxis(Collections.singletonMap("name", dimName), dimName.substring(0, 1), AxisDirection.OTHER, unit);
                final AbstractCS dimCs = new AbstractCS(Collections.singletonMap("name", dimName), csAxis);
                dimCRS = new DefaultEngineeringCRS(Collections.singletonMap("name", dimName), dimDatum, dimCs);
            }
            double minVal = Double.MIN_VALUE;
            double maxVal = Double.MAX_VALUE;
            // extract discret values
            final String dimValues = dim.getValue();
            if (dimValues != null) {
                if (!CommonCRS.Temporal.JAVA.crs().equals(dimCRS)) {
                    // serie of values
                    final String[] dimStrArray = dimValues.split(",");
                    final double[] dblValues = new double[dimStrArray.length];
                    for (int i = 0; i < dimStrArray.length; i++) {
                        dblValues[i] = Double.valueOf(dimStrArray[i]).doubleValue();
                    }
                    minVal = dblValues[0];
                    maxVal = dblValues[dblValues.length - 1];
                } else {
                    // might be serie of dates or periods
                    final String[] dimStrArray = dimValues.split(",");
                    final List<Double> dblValues = new ArrayList<Double>();
                    for (int i = 0; i < dimStrArray.length; i++) {
                        final String candidate = dimStrArray[i];
                        // try to parse a period
                        synchronized (PERIOD_DATE_FORMAT) {
                            final PeriodUtilities parser = new PeriodUtilities(PERIOD_DATE_FORMAT);
                            try {
                                final SortedSet<Date> dates = parser.getDatesFromPeriodDescription(candidate);
                                for (Date date : dates) {
                                    dblValues.add((double) date.getTime());
                                }
                                continue;
                            } catch (ParseException ex) {
                                LOGGER.log(Level.FINER, "Value : {0} is not a period", candidate);
                            }
                        }
                        // try to parse a single date
                        try {
                            final Date date = TemporalUtilities.parseDate(candidate);
                            dblValues.add((double) date.getTime());
                            continue;
                        } catch (ParseException ex) {
                            LOGGER.log(Level.FINER, "Value : {0} is not a date", candidate);
                        }
                    }
                    final double[] values = new double[dblValues.size()];
                    for (int i = 0; i < values.length; i++) {
                        values[i] = dblValues.get(i);
                    }
                    if (values.length > 0) {
                        minVal = values[0];
                        maxVal = values[values.length - 1];
                    }
                }
            }
            // add CRS to list
            if (dimCRS != null) {
                dimensionsCRS.add(dimCRS);
                lower.add(minVal);
                upper.add(maxVal);
            }
        }
        // build new envelope with all dimension CRSs and lower/upper coordinates.
        if (!dimensionsCRS.isEmpty()) {
            final CoordinateReferenceSystem outCRS;
            try {
                outCRS = new GeodeticObjectBuilder().addName(layer.getName()).createCompoundCRS(dimensionsCRS.toArray(new CoordinateReferenceSystem[dimensionsCRS.size()]));
            } catch (FactoryException ex) {
                throw new CapabilitiesException("", ex);
            }
            layerEnvelope = new GeneralEnvelope(outCRS);
            // build ordinate list like (xmin, ymin, zmin, xmax, ymax, zmax)
            final List<Double> ordinateList = new ArrayList<Double>(lower);
            ordinateList.addAll(upper);
            final double[] coordinates = new double[ordinateList.size()];
            for (int i = 0; i < ordinateList.size(); i++) {
                coordinates[i] = ordinateList.get(i);
            }
            layerEnvelope.setEnvelope(coordinates);
            // add additional resolution informations
            try {
                double[] resolution = layerGrid.getResolution(true);
                double[] resnd = new double[layerEnvelope.getDimension()];
                // todo : time and elevation values are not on a regular axis
                // how can we map those to a correct resolution ?
                Arrays.fill(resnd, Double.MAX_VALUE);
                resnd[0] = resolution[0];
                resnd[1] = resolution[1];
                layerGrid = new EstimatedGridGeometry(layerEnvelope, resnd);
            } catch (IncompleteGridGeometryException ex) {
                layerGrid = new GridGeometry(null, layerEnvelope, GridOrientation.HOMOTHETY);
            }
        }
    }
    return layerGrid;
}
Also used : AbstractLayer(org.geotoolkit.wms.xml.AbstractLayer) FactoryException(org.opengis.util.FactoryException) ArrayList(java.util.ArrayList) CoordinateSystemAxis(org.opengis.referencing.cs.CoordinateSystemAxis) DefaultCoordinateSystemAxis(org.apache.sis.referencing.cs.DefaultCoordinateSystemAxis) EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) AbstractDimension(org.geotoolkit.wms.xml.AbstractDimension) AbstractCS(org.apache.sis.referencing.cs.AbstractCS) ArrayList(java.util.ArrayList) List(java.util.List) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) CapabilitiesException(org.geotoolkit.client.CapabilitiesException) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) DefaultCoordinateSystemAxis(org.apache.sis.referencing.cs.DefaultCoordinateSystemAxis) Date(java.util.Date) PeriodUtilities(org.geotoolkit.temporal.util.PeriodUtilities) AbstractWMSCapabilities(org.geotoolkit.wms.xml.AbstractWMSCapabilities) GeodeticObjectBuilder(org.apache.sis.internal.referencing.GeodeticObjectBuilder) ParseException(java.text.ParseException) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope) IncompleteGridGeometryException(org.apache.sis.coverage.grid.IncompleteGridGeometryException) DefaultEngineeringDatum(org.apache.sis.referencing.datum.DefaultEngineeringDatum) DefaultEngineeringCRS(org.apache.sis.referencing.crs.DefaultEngineeringCRS)

Example 4 with EstimatedGridGeometry

use of org.geotoolkit.coverage.grid.EstimatedGridGeometry in project geotoolkit by Geomatys.

the class Layer method getGridGeometry2D.

@Override
public GridGeometry getGridGeometry2D() {
    if (getBoundingBox().isEmpty()) {
        final AbstractGeographicBoundingBox bbox = getEXGeographicBoundingBox();
        if (bbox != null) {
            GeneralEnvelope env = new GeneralEnvelope(CommonCRS.WGS84.normalizedGeographic());
            env.setRange(0, bbox.getWestBoundLongitude(), bbox.getEastBoundLongitude());
            env.setRange(1, bbox.getSouthBoundLatitude(), bbox.getNorthBoundLatitude());
            return new GridGeometry(null, env, GridOrientation.HOMOTHETY);
        }
        return null;
    }
    final BoundingBox bbox = getBoundingBox().get(0);
    try {
        GeneralEnvelope env = new GeneralEnvelope(CRS.forCode(bbox.getCRS()));
        env.setRange(0, bbox.getMinx(), bbox.getMaxx());
        env.setRange(1, bbox.getMiny(), bbox.getMaxy());
        Double resx = bbox.getResx();
        Double resy = bbox.getResy();
        if (resx != null && resy != null) {
            return new EstimatedGridGeometry(env, new double[] { resx, resy });
        } else {
            return new GridGeometry(null, env, GridOrientation.HOMOTHETY);
        }
    } catch (FactoryException e) {
        Logger.getLogger("org.geotoolkit.wms.xml.v130").warning(e.getMessage());
    }
    return null;
}
Also used : EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) AbstractGeographicBoundingBox(org.geotoolkit.wms.xml.AbstractGeographicBoundingBox) FactoryException(org.opengis.util.FactoryException) AbstractGeographicBoundingBox(org.geotoolkit.wms.xml.AbstractGeographicBoundingBox) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope)

Example 5 with EstimatedGridGeometry

use of org.geotoolkit.coverage.grid.EstimatedGridGeometry in project geotoolkit by Geomatys.

the class Layer method getGridGeometry2D.

@Override
public GridGeometry getGridGeometry2D() {
    if (getBoundingBox().isEmpty()) {
        final LatLonBoundingBox bbox = getLatLonBoundingBox();
        if (bbox != null) {
            GeneralEnvelope env = new GeneralEnvelope(CommonCRS.WGS84.normalizedGeographic());
            env.setRange(0, bbox.getWestBoundLongitude(), bbox.getEastBoundLongitude());
            env.setRange(1, bbox.getSouthBoundLatitude(), bbox.getNorthBoundLatitude());
            return new GridGeometry(null, env, GridOrientation.HOMOTHETY);
        }
        return null;
    }
    final BoundingBox bbox = getBoundingBox().get(0);
    try {
        GeneralEnvelope env = new GeneralEnvelope(CRS.forCode(bbox.getCRSCode()));
        env.setRange(0, bbox.getMinx(), bbox.getMaxx());
        env.setRange(1, bbox.getMiny(), bbox.getMaxy());
        Double resx = bbox.getResx();
        Double resy = bbox.getResy();
        if (resx != null && resy != null) {
            return new EstimatedGridGeometry(env, new double[] { resx, resy });
        } else {
            return new GridGeometry(null, env, GridOrientation.HOMOTHETY);
        }
    } catch (FactoryException e) {
        Logger.getLogger("org.geotoolkit.wms.xml.v100").warning(e.getMessage());
    }
    return null;
}
Also used : EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) EstimatedGridGeometry(org.geotoolkit.coverage.grid.EstimatedGridGeometry) FactoryException(org.opengis.util.FactoryException) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope)

Aggregations

EstimatedGridGeometry (org.geotoolkit.coverage.grid.EstimatedGridGeometry)8 GridGeometry (org.apache.sis.coverage.grid.GridGeometry)7 GeneralEnvelope (org.apache.sis.geometry.GeneralEnvelope)6 FactoryException (org.opengis.util.FactoryException)5 Envelope (org.opengis.geometry.Envelope)4 GridExtent (org.apache.sis.coverage.grid.GridExtent)3 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)3 IncompleteGridGeometryException (org.apache.sis.coverage.grid.IncompleteGridGeometryException)2 AbstractGeographicBoundingBox (org.geotoolkit.wms.xml.AbstractGeographicBoundingBox)2 Dimension (java.awt.Dimension)1 Point (java.awt.Point)1 ParseException (java.text.ParseException)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 List (java.util.List)1 Entry (java.util.Map.Entry)1 DisjointExtentException (org.apache.sis.coverage.grid.DisjointExtentException)1 GeodeticObjectBuilder (org.apache.sis.internal.referencing.GeodeticObjectBuilder)1 DefaultEngineeringCRS (org.apache.sis.referencing.crs.DefaultEngineeringCRS)1 AbstractCS (org.apache.sis.referencing.cs.AbstractCS)1