Class GridGeometry

Object
GridGeometry
All Implemented Interfaces:
Serializable, Lenient­Comparable

public class GridGeometry extends Object implements LenientComparable, Serializable
Valid extent of grid coordinates together with the transform from those grid coordinates to real world coordinates. Grid­Geometry contains: The first three properties should be mandatory, but are allowed to be temporarily absent during grid coverage construction. Temporarily absent properties are allowed because they may be inferred from a wider context. For example, a Grid­Geometry knows nothing about Rendered­Image, but Grid­Coverage2D has this information and may use it for providing a missing grid extent. By default, any request for an undefined property will throw an Incomplete­Grid­Geometry­Exception. In order to check if a property is defined, use is­Defined(int).

Non-linear referencing

A key property is the "grid to CRS" conversion, which defines how to map pixel coordinates to "real world" coordinates such as latitudes and longitudes. This relationship is often linear (an affine transform), but not necessarily; Grid­Geometry accepts non-linear conversions as well. Non-linear conversions may occur with images using localization grids, but non-linear conversions should not be used for expressing map projections (projections should be specified in the Coordinate Reference System (CRS) instead).

Some applications cannot handle non-linear "grid to CRS" conversions. For example, encoding an image in a GeoTIFF file is much simpler if the "grid to CRS" conversion is linear. The Domain­Linearizer class can be used for replacing non-linear conversions by linear approximations.

Multi-threading

Grid­Geometry instances are immutable and thread-safe. The same instance can be shared by different Grid­Coverage instances.
Since:
1.0
See Also:
  • Field Details

  • Constructor Details

    • GridGeometry

      protected GridGeometry(GridGeometry other)
      Creates a new grid geometry with the same values than the given grid geometry. This is a copy constructor for subclasses.
      Parameters:
      other - the other grid geometry to copy.
    • GridGeometry

      public GridGeometry(GridGeometry other, GridExtent extent, MathTransform toOther) throws TransformException
      Creates a new grid geometry derived from the given grid geometry with a new extent and a modified transform. This constructor is used for creating a grid geometry over a subregion (for example with the grid extent computed by Grid­Derivation​.subgrid(Envelope, double...)) or grid geometry for a subsampled raster.

      Conversion between old and new grid geometry

      If to­Other is non-null, it defines the conversion from grid coordinates of given extent to grid coordinates of other. That transform should be a scale and a translation only, but more complex transforms are accepted. The corner­To­CRS transform of the new grid geometry will be set to the following concatenation:
      this​.corner­To­CRS = to­Otherother​.corner­To­CRS
      The new grid geometry envelope will be computed from the new extent and transform, then clipped to the envelope of the other grid geometry. This clip is for preventing the envelope to become larger under the effect of subsampling because each cell become larger. The clip is not applied when to­Other is null because in such case, we presume that the grid extent has been changed for another reason than subsampling (e.g. application of a margin, in which case we want the envelope to be expanded).
      Parameters:
      other - the other grid geometry to copy.
      extent - the new extent for the grid geometry to construct, or null if none.
      to­Other - transform from this grid coordinates to other grid coordinates, or null if none.
      Throws:
      Null­Pointer­Exception - if extent is null and the other grid geometry contains no other information.
      Transform­Exception - if the math transform cannot compute the geospatial envelope from the grid extent.
      Since:
      1.2
      See Also:
    • GridGeometry

      public GridGeometry(GridExtent extent, PixelInCell anchor, MathTransform gridToCRS, CoordinateReferenceSystem crs)
      Creates a new grid geometry from a grid extent and a mapping from cell coordinates to "real world" coordinates. At least one of extent, grid­To­CRS or crs arguments shall be non-null. If grid­To­CRS is non-null, then anchor shall be non-null too with one of the following values:
      • Pixel­In­Cell​.CELL_CENTER if conversions of cell indices by grid­To­CRS give "real world" coordinates close to the center of each cell.
      • Pixel­In­Cell​.CELL_CORNER if conversions of cell indices by grid­To­CRS give "real world" coordinates at the corner of each cell. The cell corner is the one for which all grid indices have the smallest values (closest to negative infinity).

      API note

      There is no default value for anchor because experience shows that images shifted by ½ pixel (with pixels that may be tens of kilometres large) is a recurrent problem. We want to encourage developers to always think about wether their grid to CRS transform is mapping pixel corner or center.
      Upcoming API generalization: the extent type of this method may be changed to Grid­Envelope interface in a future Apache SIS version. This is pending GeoAPI update. In addition, the Pixel­In­Cell code list currently defined in the org​.opengis​.referencing​.datum package may move in another package in a future GeoAPI version because this type is no longer defined by the ISO 19111 standard after the 2018 revision.
      Parameters:
      extent - the valid extent of grid coordinates, or null if unknown.
      anchor - Cell center for OGC conventions or cell corner for Java2D/JAI conventions.
      grid­To­CRS - the mapping from grid coordinates to "real world" coordinates, or null if unknown.
      crs - the coordinate reference system of the "real world" coordinates, or null if unknown.
      Throws:
      Null­Pointer­Exception - if extent, grid­To­CRS and crs arguments are all null.
      Mismatched­Dimension­Exception - if the math transform and the CRS do not have consistent dimensions.
      Illegal­Grid­Geometry­Exception - if the math transform cannot compute the geospatial envelope or resolution from the grid extent.
    • GridGeometry

      public GridGeometry(PixelInCell anchor, MathTransform gridToCRS, Envelope envelope, GridRoundingMode rounding)
      Creates a new grid geometry from a geospatial envelope and a mapping from cell coordinates to "real world" coordinates. At least one of grid­To­CRS or envelope arguments shall be non-null. If grid­To­CRS is non-null, then anchor shall be non-null too with one of the values documented in the constructor expecting a grid extent.

      The given envelope shall encompass all cell surfaces, from the left border of leftmost cell to the right border of the rightmost cell and similarly along other axes. This constructor tries to store a geospatial envelope close to the specified envelope, but there is no guarantee that the envelope returned by get­Envelope() will be equal to the given envelope. The envelope stored in the new Grid­Geometry may be slightly smaller, larger or shifted because the floating point values used in geospatial envelope cannot always be mapped to the integer coordinates used in Grid­Extent. The rules for deciding whether coordinates should be rounded toward nearest integers, to floor or to ceil values are specified by the Grid­Rounding­Mode argument.

      Because of the uncertainties explained in above paragraph, this constructor should be used only in last resort, when the grid extent is unknown. For determinist results, developers should prefer the constructor using grid extent as much as possible. In particular, this constructor is not suitable for computing grid geometry of tiles in a tiled image, because the above-cited uncertainties may result in apparently random black lines between tiles.

      Upcoming API change: The Pixel­In­Cell code list currently defined in the org​.opengis​.referencing​.datum package may move in another package in a future GeoAPI version because this type is no longer defined by the ISO 19111 standard after the 2018 revision. This code list may be taken by ISO 19123 in a future revision.
      Parameters:
      anchor - Cell center for OGC conventions or cell corner for Java2D/JAI conventions.
      grid­To­CRS - the mapping from grid coordinates to "real world" coordinates, or null if unknown.
      envelope - the geospatial envelope, including its coordinate reference system if available. There is no guarantee that the envelope actually stored in the Grid­Geometry will be equal to this specified envelope.
      rounding - controls behavior of rounding from floating point values to integers.
      Throws:
      Illegal­Grid­Geometry­Exception - if the math transform cannot compute the grid extent or the resolution.
    • GridGeometry

      public GridGeometry(GridExtent extent, Envelope envelope, GridOrientation orientation)
      Creates an axis-aligned grid geometry with an extent and an envelope. This constructor can be used when the grid to CRS transform is unknown. If only the coordinate reference system is known, then the envelope coordinates can be all NaN.

      The main purpose of this constructor is to create "desired" grid geometries, for example for use in read or resample operations. For grid geometries describing preexisting data, it is safer and more flexible to use one of the constructors expecting a Math­Transform argument.

      Dimension order

      The given envelope shall always declare dimensions in same order than the given extent. This constructor may reorder axes if orientation is (for example) Grid­Orientation​.DISPLAY, but in such case this constructor will derive itself an envelope and a CRS with reordered axes.
      Parameters:
      extent - the valid extent of grid coordinates, or null if unknown.
      envelope - the envelope together with CRS of the "real world" coordinates, or null if unknown.
      orientation - high-level description of desired characteristics of the grid­To­CRS transform. Ignored (can be null) if envelope is null.
      Throws:
      Null­Pointer­Exception - if extent and envelope arguments are both null, or if envelope is non-null but orientation is null.
      Since:
      1.1
      See Also:
    • GridGeometry

      public GridGeometry(Envelope envelope)
      Creates a grid geometry with only an envelope.
      Parameters:
      envelope - the envelope together with CRS of the "real world" coordinates.
      Throws:
      Illegal­Argument­Exception - if the envelope has no CRS and only NaN coordinate values.
      Since:
      1.4
  • Method Details

    • getDimension

      public final int getDimension()
      Returns the number of dimensions of the grid. This is typically the same than the number of envelope dimensions or the number of coordinate reference system dimensions, but not necessarily.
      Returns:
      the number of grid dimensions.
      See Also:
    • getExtent

      public GridExtent getExtent()
      Returns the valid coordinate range of a grid coverage. The lowest valid grid coordinate is zero for Buffered­Image, but may be non-zero for arbitrary Rendered­Image. A grid with 512 cells can have a minimum coordinate of 0 and maximum of 511.
      Upcoming API generalization: the return type of this method may be changed to Grid­Envelope interface in a future Apache SIS version. This is pending GeoAPI update.
      Returns:
      the valid extent of grid coordinates (never null).
      Throws:
      Incomplete­Grid­Geometry­Exception - if this grid geometry has no extent — i.e. is­Defined(EXTENT) returned false.
    • getGridToCRS

      public MathTransform getGridToCRS(PixelInCell anchor)
      Returns the conversion from grid coordinates to "real world" coordinates. The conversion is often an affine transform, but not necessarily. Conversions from cell indices to geospatial coordinates can be performed for example as below:
      MathTransform  gridToCRS     = gridGeometry.getGridToCRS(PixelInCell.CELL_CENTER);
      DirectPosition indicesOfCell = new GeneralDirectPosition(2, 3, 4):
      DirectPosition aPixelCenter  = gridToCRS.transform(indicesOfCell, null);
      
      Callers must specify whether they want the "real world" coordinates of cell center or cell corner. The cell corner is the one for which all grid indices have the smallest values (closest to negative infinity). As a rule of thumb:

      API note

      There is no default value for anchor because experience shows that images shifted by ½ pixel (with pixels that may be tens of kilometres large) is a recurrent problem. We want to encourage developers to always think about wether the desired grid to CRS transform shall map pixel corner or center.
      Parameters:
      anchor - the cell part to map (center or corner).
      Returns:
      the conversion from grid coordinates to "real world" coordinates (never null).
      Throws:
      Illegal­Argument­Exception - if the given anchor is not a known code list value.
      Incomplete­Grid­Geometry­Exception - if this grid geometry has no transform — i.e. is­Defined(GRID_TO_CRS) returned false.
    • getLinearGridToCRS

      public LinearTransform getLinearGridToCRS(PixelInCell anchor) throws TransformException
      Returns a linear approximation of the conversion from grid coordinates to "real world" coordinates. If the value returned by get­Grid­To­CRS(Pixel­In­Cell) is already an instance of Linear­Transform, then it is returned as is. Otherwise this method computes the tangent of the transform at the grid extent point of interest (usually the center of the grid).
      Parameters:
      anchor - the cell part to map (center or corner).
      Returns:
      linear approximation of the conversion from grid coordinates to "real world" coordinates.
      Throws:
      Illegal­Argument­Exception - if the given anchor is not a known code list value.
      Incomplete­Grid­Geometry­Exception - if this grid geometry has no transform, or if the transform is non-linear but this grid geometry has no extent.
      Transform­Exception - if an error occurred while computing the tangent.
      Since:
      1.3
    • getCoordinateReferenceSystem

      public CoordinateReferenceSystem getCoordinateReferenceSystem()
      Returns the "real world" coordinate reference system.
      Returns:
      the coordinate reference system (never null).
      Throws:
      Incomplete­Grid­Geometry­Exception - if this grid geometry has no CRS — i.e. is­Defined(CRS) returned false.
    • getEnvelope

      public Envelope getEnvelope()
      Returns the bounding box of "real world" coordinates for this grid geometry. This envelope is computed from the grid extent, which is transformed to the "real world" coordinate system. The initial envelope encompasses all cell surfaces, from the left border of leftmost cell to the right border of the rightmost cell and similarly along other axes. If this grid geometry is a subgrid, then the envelope is also clipped to the envelope of the original (non subsampled) grid geometry.
      Returns:
      the bounding box in "real world" coordinates (never null).
      Throws:
      Incomplete­Grid­Geometry­Exception - if this grid geometry has no envelope — i.e. is­Defined(ENVELOPE) returned false.
    • getEnvelope

      public Envelope getEnvelope(CoordinateReferenceSystem crs) throws TransformException
      Returns the "real world" bounding box of this grid geometry transformed to the given CRS. This envelope is computed from the grid extent if available, or from the envelope otherwise.
      Parameters:
      crs - the desired coordinate reference system for the returned envelope.
      Returns:
      the bounding box in "real world" coordinates (never null).
      Throws:
      Incomplete­Grid­Geometry­Exception - if this grid geometry has no extent and no envelope.
      Transform­Exception - if the envelope cannot be transformed to the specified CRS.
      Since:
      1.2
    • getGeographicExtent

      public Optional<GeographicBoundingBox> getGeographicExtent()
      Returns the approximate latitude and longitude coordinates of the grid. The prime meridian is Greenwich, but the geodetic reference frame is not necessarily WGS 84. This is computed from the envelope if the coordinate reference system contains an horizontal component such as a geographic or projected CRS.

      API note

      This method does not throw Incomplete­Grid­Geometry­Exception because the geographic extent may be absent even with a complete grid geometry. Grid geometries are not required to have a spatial component on Earth surface; a raster could be a vertical profile for example.
      Returns:
      the geographic bounding box in "real world" coordinates.
    • getTemporalExtent

      public Instant[] getTemporalExtent()
      Returns the start time and end time of coordinates of the grid. If the grid has no temporal dimension, then this method returns an empty array. If only the start time or end time is defined, then returns an array of length 1. Otherwise this method returns an array of length 2 with the start time in the first element and the end time in the last element.
      Returns:
      time range as an array of length 0 (if none), 1 or 2.
    • getResolution

      public double[] getResolution(boolean allowEstimates)
      Returns an estimation of the grid resolution, in units of the coordinate reference system axes. The length of the returned array is the number of CRS dimensions, with resolution[0] being the resolution along the first CRS axis, resolution[1] the resolution along the second CRS axis, etc. Note that this axis order is not necessarily the same than grid axis order.

      If the resolution at CRS dimension i is not a constant factor (i.e. the is­Conversion­Linear(i) returns false), then resolution[i] is set to one of the following values:

      • Double​.Na­N if allow­Estimates is false.
      • An arbitrary representative resolution otherwise. Current implementation computes the resolution at grid center, but different implementations may use alternative algorithms.
      Parameters:
      allow­Estimates - whether to provide some values even for resolutions that are not constant factors.
      Returns:
      an estimation of the grid resolution (never null).
      Throws:
      Incomplete­Grid­Geometry­Exception - if this grid geometry has no resolution — i.e. is­Defined(RESOLUTION) returned false.
    • isConversionLinear

      public boolean isConversionLinear(int... targets)
      Indicates whether the grid to CRS conversion is linear for all the specified CRS axes. The conversion from grid coordinates to real world coordinates is often linear for some dimensions, typically the horizontal ones at indices 0 and 1. But the vertical dimension (usually at index 2) is often non-linear, for example with data at 0, 5, 10, 100 and 1000 metres.
      Parameters:
      targets - indices of CRS axes. This is not necessarily the same than indices of grid axes.
      Returns:
      true if the conversion from grid coordinates to "real world" coordinates is linear for all the given CRS dimension.
    • isDefined

      public boolean isDefined(int bitmask)
      Returns true if all the properties specified by the argument are set. If this method returns true, then invoking the corresponding getter methods will not throw Incomplete­Grid­Geometry­Exception.
      Parameters:
      bitmask - any combination of CRS, ENVELOPE, EXTENT, GRID_TO_CRS and RESOLUTION.
      Returns:
      true if all specified properties are defined (i.e. invoking the corresponding getter methods will not throw Incomplete­Grid­Geometry­Exception).
      Throws:
      Illegal­Argument­Exception - if the specified bitmask is not a combination of known masks.
      See Also:
    • derive

      public GridDerivation derive()
      Returns an object that can be used for creating a new grid geometry derived from this grid geometry. Grid­Derivation does not change the state of this Grid­Geometry but instead creates new instances as needed. Examples of modifications include clipping to a sub-area or applying a sub-sampling.

      Each Grid­Derivation instance can be used only once and should be used in a single thread. Grid­Derivation preserves the number of dimensions. For example, slicing sets the grid size to 1 in all dimensions specified by a slice point, but does not remove those dimensions from the grid geometry. For dimensionality reduction, see select­Dimensions(int[]).

      Example

      For clipping this grid geometry to a sub-area, one can use:
      GridGeometry gg = ...;
      Envelope areaOfInterest = ...;
      gg = gg.derive().rounding(GridRoundingMode.ENCLOSING)
                      .subgrid(areaOfInterest).build();
      
      Returns:
      an object for deriving a grid geometry from this.
    • upsample

      public GridGeometry upsample(int... periods)
      Creates a new grid geometry upsampled by the given amount of cells along each grid dimensions. This method multiplies low and high coordinates by the given periods, then scales the grid to CRS transform for compensating the grid change. The grid geometry envelope is preserved after upsampling.

      Number of arguments

      The periods array length should be equal to the number of grid dimensions. If the array is shorter, missing values default to 1 (i.e. samplings in unspecified dimensions are unchanged). If the array is longer, extraneous values are ignored.
      Parameters:
      periods - the upsampling. Length shall be equal to the number of dimension and all values shall be greater than zero.
      Returns:
      the upsampled grid geometry, or this is upsampling results in the same extent.
      Throws:
      Illegal­Argument­Exception - if a period is not greater than zero.
      Since:
      1.3
      See Also:
    • shiftGrid

      public GridGeometry shiftGrid(long... translation)
      Translates grid coordinates by the given amount of cells without changing "real world" coordinates. The returned grid has the same size than this grid, i.e. both low and high grid coordinates are displaced by the same amount of cells. The "grid to CRS" transforms are adjusted accordingly in order to map to the same "real world" coordinates.

      Number of arguments

      The translation array length should be equal to the number of dimensions. If the array is shorter, missing values default to 0 (i.e. no translation in unspecified dimensions). If the array is longer, extraneous values are ignored.
      Parameters:
      translation - translation to apply on each grid axis in order.
      Returns:
      a grid geometry whose coordinates (both low and high ones) and the "grid to CRS" transforms have been translated by given amounts. If the given translation is a no-op (no value or only 0 ones), then this grid is returned as is.
      Throws:
      Arithmetic­Exception - if the translation results in coordinates that overflow 64-bits integer.
      Since:
      1.3
      See Also:
    • relocate

      public GridGeometry relocate(GridExtent newExtent) throws TransformException
      Returns a grid geometry with the given grid extent, which implies a new "real world" computation. The "grid to CRS" transforms and the resolution stay the same than this Grid­Geometry. The "real world" envelope is recomputed for the new grid extent using the "grid to CRS" transforms.

      The given extent is taken verbatim; this method does no clipping. The given extent does not need to intersect the extent of this grid geometry.

      Parameters:
      new­Extent - extent of the grid geometry to return.
      Returns:
      grid geometry with the given extent. May be this if there is no change.
      Throws:
      Transform­Exception - if the geospatial envelope cannot be recomputed with the new grid extent.
      Since:
      1.3
    • selectDimensions

      public GridGeometry selectDimensions(int... indices)
      Returns a grid geometry that encompass only some dimensions of this grid geometry. The specified dimensions will be copied into a new grid geometry if necessary. The selection is applied on grid extent dimensions; they are not necessarily the same than the envelope dimensions. The given dimensions must be in strictly ascending order without duplicated values. The number of dimensions of the sub grid geometry will be dimensions​.length.

      This method performs a dimensionality reduction. This method cannot be used for changing dimension order.

      Parameters:
      indices - the grid (not CRS) dimensions to select, in strictly increasing order.
      Returns:
      the sub-grid geometry, or this if the given array contains all dimensions of this grid geometry.
      Throws:
      Index­Out­Of­Bounds­Exception - if an index is out of bounds.
      Since:
      1.3
      See Also:
    • createImageCRS

      public DerivedCRS createImageCRS(String name, PixelInCell anchor)
      Creates a one-, two- or three-dimensional coordinate reference system for cell indices in the grid. This method returns a CRS which is derived from the "real world" CRS or a subset of it. If the "real world" CRS is an instance of Single­CRS, then the derived CRS has the following properties: Otherwise if the "real world" CRS is an instance of Compound­CRS, then only the first Single­CRS (the head) is used. This is usually (but not necessarily) the horizontal component of the spatial CRS. The result is usually two-dimensional, but 1 and 3 dimensions are also possible.

      Because of above relationship, it is possible to use the derived CRS in a chain of operations with (for example) CRS​.find­Operation(…).

      Parameters:
      name - name of the CRS to create.
      anchor - the cell part to map (center or corner).
      Returns:
      a derived CRS for coordinates (cell indices) associated to the grid extent.
      Throws:
      Incomplete­Grid­Geometry­Exception - if the CRS, grid extent or "grid to CRS" transform is missing.
      Since:
      1.3
    • createTransformTo

      public MathTransform createTransformTo(GridGeometry target, PixelInCell anchor) throws TransformException
      Creates a transform from cell coordinates in this grid to cell coordinates in the given grid. The returned transform handles change of Coordinate Reference System and wraparound axes (e.g. longitude axis crossing the ±180° meridian) if applicable.

      Note: the transform created by this method may be non-invertible.

      Parameters:
      target - the grid which will be the target of returned transform.
      anchor - Cell center for OGC conventions or cell corner for Java2D/JAI conventions.
      Returns:
      transform from cell coordinates in this grid to cell coordinates in the given grid.
      Throws:
      Transform­Exception - if the math transform cannot be created.
      Since:
      1.1
    • hashCode

      public int hashCode()
      Returns a hash value for this grid geometry. This value needs not to remain consistent between different implementations of the same class.
      Overrides:
      hash­Code in class Object
    • equals

      public boolean equals(Object object)
      Compares the specified object with this grid geometry for equality. This method delegates to equals(object, Comparison­Mode​.STRICT).
      Specified by:
      equals in interface Lenient­Comparable
      Overrides:
      equals in class Object
      Parameters:
      object - the object to compare with.
      Returns:
      true if the given object is equal to this grid geometry.
      See Also:
    • equals

      public boolean equals(Object object, ComparisonMode mode)
      Compares the specified object with this grid geometry for equality. If the mode is Comparison­Mode​.IGNORE_METADATA or more flexible, then the axis types are ignored.
      Specified by:
      equals in interface Lenient­Comparable
      Parameters:
      object - the object to compare with this grid geometry for equality.
      mode - the strictness level of the comparison.
      Returns:
      true if the given object is equal to this grid geometry.
      Since:
      1.1
      See Also:
    • toString

      public String toString()
      Returns a string representation of this grid geometry. The returned string is implementation dependent and may change in any future version. Current implementation is equivalent to a call to to­Tree(Locale, int) with at least EXTENT, ENVELOPE and CRS flags. Whether more flags are present or not is unspecified.
      Overrides:
      to­String in class Object
    • toTree

      @Debug public TreeTable toTree(Locale locale, int bitmask)
      Returns a tree representation of some elements of this grid geometry. The tree representation is for debugging or logging purposes and may change in any future SIS version.
      Parameters:
      locale - the locale to use for textual labels.
      bitmask - combination of EXTENT, ENVELOPE, CRS, GRID_TO_CRS, RESOLUTION, GEOGRAPHIC_EXTENT and TEMPORAL_EXTENT.
      Returns:
      a tree representation of the specified elements.