org.geotoolkit.image.io.plugin
Class NetcdfImageReader

Object
  extended by ImageReader
      extended by SpatialImageReader
          extended by StreamImageReader
              extended by FileImageReader
                  extended by NetcdfImageReader
All Implemented Interfaces:
Disposable, Localized, AggregatedImageStore, MultidimensionalImageStore, NamedImageStore, WarningProducer, CancelTask

public class NetcdfImageReader
extends FileImageReader
implements MultidimensionalImageStore, NamedImageStore, AggregatedImageStore, CancelTask

Base implementation for NetCDF image readers. Pixels are assumed organized according the COARDS convention (a precursor of CF Metadata conventions). For a 4-D dataset with horizontal, vertical and temporal ordinates, the dimension are typically (x,y,z,t) where x index varies faster.

Note: NetCDF data files actually declare dimensions in reverse order. For the above example, the dimensions would be declared as (t,z,y,x). This NetcdfImageReader plugin reverse the order of dimensions read in the NetCDF file, in order to get an ordering consistent with the ordering used by other plugins.
The image is created from the (x,y) dimensions in the above example. Additional dimensions (if any) are ignored by default: only the slice at index 0 is read, which is z0 and t0 in the example above. See below for selecting slices in other dimensions.


Specifying the variable to read
Each variable having at least two dimensions (except the variables used for Coordinate System axes) is an image. The variables to read can be specified using the methods defined in the NamedImageStore interface, as in the example below:

imageReader.setImageNames("temperature", "salinity");
BufferedImage temperature = imageReader.read(0);
BufferedImage salinity    = imageReader.read(1);
Alternatively, the variables can be assigned to bands instead than images. This is useful when two related variables - for example the East-West (U) and North-South (V) components of wind speed - shall be stored in the same image:
imageReader.setBandNames(0, "WindSpeed-U", "WindSpeed-V");
BufferedImage windSpeed = imageReader.read(0);
// windSpeed is now an image with two bands.


Specifying the slice to read in extra dimensions
For any dimension greater than 2, the region to read can be specified in two different ways:


Connection to DODS servers
This image reader accepts String, File, URL and URI inputs. The input can use the DODS protocol (as in "dods://opendap.aviso.oceanobs.com/"), in order to connect to the specified DODS remote server.


Support of related formats
This implementation uses the UCAR NetCDF library for reading data. Consequently, it can be used for reading other formats supported by that library. For a list of supported formats, see file types and remote access protocols on the NetCDF web site.

Since:
3.08 (derived from 2.4)
Version:
3.20
Author:
Martin Desruisseaux (Geomatys), Antoine Hnawia (IRD), Johann Sorel (Geomatys)
See Also:
NetcdfCRS
Module:
coverage/geotk-coverageio-netcdf (download)    View source code for this class

Nested Class Summary
static class NetcdfImageReader.Spi
          The service provider for NetcdfImageReader.
 
Field Summary
protected  Variable variable
          The data from the NetCDF file for a given image index.
 
Fields inherited from class StreamImageReader
closeOnReset
 
Fields inherited from class ImageReader
availableLocales, ignoreMetadata, input, locale, minIndex, originatingProvider, progressListeners, seekForwardOnly, updateListeners, warningListeners, warningLocales
 
Fields inherited from interface MultidimensionalImageStore
X_DIMENSION, Y_DIMENSION
 
Fields inherited from interface WarningProducer
LOGGER
 
Constructor Summary
NetcdfImageReader(NetcdfImageReader.Spi spi)
          Constructs a new NetCDF reader.
 
Method Summary
 boolean canReadRaster()
          Returns true since this class supports calls to readRaster(int, ImageReadParam).
protected  void close()
          Closes the NetCDF file.
protected  SpatialMetadata createMetadata(int imageIndex)
          Creates a new stream or image metadata.
protected  Variable findVariable(String name)
          Returns the variable of the given name.
 List<URI> getAggregatedFiles(int imageIndex)
          Returns the URIs to the aggregated files, or null if none.
 DimensionSlice.API getAPIForDimension(Object... identifiers)
          Returns the API assigned to the given dimension identifiers.
 Set<DimensionSlice.API> getAPIForDimensions()
          Returns the set of APIs for which at least one dimension has identifiers.
 List<String> getBandNames(int imageIndex)
          Returns the names of the bands for the given image, or null if none.
 int getDimension(int imageIndex)
          Returns the number of dimensions in the image identified by the given index.
 DimensionIdentification getDimensionForAPI(DimensionSlice.API api)
          Returns the dimension assigned to the given API.
 GridEnvelope getGridEnvelope(int imageIndex)
          Returns the grid envelope in the image identified by the given index.
 int getHeight(int imageIndex)
          Returns the image height.
 List<String> getImageNames()
          Returns the names of the variables to be read.
 int getNumBands(int imageIndex)
          Returns the number of bands available for the image identified by the given index.
 int getNumImages(boolean allowSearch)
          Returns the number of images available from the current input source.
protected  int getRawDataType(int imageIndex)
          Returns the data type which most closely represents the "raw" internal data of the image.
 int getWidth(int imageIndex)
          Returns the image width.
 boolean isCancel()
          Invoked by the NetCDF library during read operation in order to check if the task has been canceled.
protected  boolean prepareVariable(int imageIndex)
          Ensures that data are loaded in the NetCDF variable.
 BufferedImage read(int imageIndex, ImageReadParam param)
          Creates an image from the specified parameters.
 Raster readRaster(int imageIndex, ImageReadParam param)
          Creates a raster from the specified parameters.
 void reset()
          Restores the ImageReader to its initial state.
 void setBandNames(int imageIndex, String... names)
          Sets the names of the bands for the given image, or null for removing any naming.
 void setError(String message)
          Invoked by the NetCDF library when an error occurred during the read operation.
 void setImageNames(String... names)
          Sets the name of the variables to be read in a NetCDF file.
 
Methods inherited from class FileImageReader
getInputFile, getURLEncoding, isRandomAccessEasy, isTemporaryFile
 
Methods inherited from class StreamImageReader
finalize, getChannel, getInputStream, getStreamLength, setInput
 
Methods inherited from class SpatialImageReader
checkBandIndex, checkImageIndex, collapseNoDataValues, dispose, getDefaultReadParam, getDestination, getImageMetadata, getImageType, getImageTypes, getRawImageType, getStreamMetadata, hasColors, warningOccurred
 
Methods inherited from class ImageReader
abort, abortRequested, addIIOReadProgressListener, addIIOReadUpdateListener, addIIOReadWarningListener, checkReadParamBandSettings, clearAbortRequest, computeRegions, getAspectRatio, getAvailableLocales, getDestination, getFormatName, getImageMetadata, getInput, getLocale, getMinIndex, getNumThumbnails, getOriginatingProvider, getSourceRegion, getStreamMetadata, getThumbnailHeight, getThumbnailWidth, getTileGridXOffset, getTileGridYOffset, getTileHeight, getTileWidth, hasThumbnails, isIgnoringMetadata, isImageTiled, isSeekForwardOnly, processImageComplete, processImageProgress, processImageStarted, processImageUpdate, processPassComplete, processPassStarted, processReadAborted, processSequenceComplete, processSequenceStarted, processThumbnailComplete, processThumbnailPassComplete, processThumbnailPassStarted, processThumbnailProgress, processThumbnailStarted, processThumbnailUpdate, processWarningOccurred, processWarningOccurred, read, readAll, readAll, readAsRenderedImage, readerSupportsThumbnails, readThumbnail, readTile, readTileRaster, removeAllIIOReadProgressListeners, removeAllIIOReadUpdateListeners, removeAllIIOReadWarningListeners, removeIIOReadProgressListener, removeIIOReadUpdateListener, removeIIOReadWarningListener, setInput, setInput, setLocale
 
Methods inherited from class Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface Localized
getLocale
 

Field Detail

variable

protected Variable variable
The data from the NetCDF file for a given image index. The value for this field is set by prepareVariable(int) when first needed, and may be updated when the argument given to any method expecting a imageIndex parameter has changed.

This field is typically (but not necessarily) an instance of VariableDS.

Constructor Detail

NetcdfImageReader

public NetcdfImageReader(NetcdfImageReader.Spi spi)
Constructs a new NetCDF reader.

Parameters:
spi - The service provider.
Method Detail

getDimensionForAPI

public DimensionIdentification getDimensionForAPI(DimensionSlice.API api)
Returns the dimension assigned to the given API. By default, the Image I/O API is used as below:

The above-cited default can be changed by calls to this method. For example, the following method call allows usage of the otherwise unused bands API for selecting slices in the third dimension:

reader.setImageNames("temperature");
reader.getDimensionForAPI(API.BANDS).addDimensionId(2); // Zero-based index
The following method call reads the same image than the above example, but uses the image index for selecting slices in the third dimension:
reader.setBandNames(0, "temperature");
reader.getDimensionForAPI(API.IMAGES).addDimensionId(3);
This NetCDF reader allows usage of BANDS and IMAGES API. The COLUMNS and ROWS API can not be assigned to new dimensions in current implementation.

Specified by:
getDimensionForAPI in interface MultidimensionalImageStore
Parameters:
api - The API for which to return a dimension.
Returns:
The dimension assigned to the given API.
Since:
3.15
See Also:
DimensionSet.getOrCreate(DimensionSlice.API)

getAPIForDimension

public DimensionSlice.API getAPIForDimension(Object... identifiers)
Returns the API assigned to the given dimension identifiers. The identifiers can be any kind of objects accepted by the DimensionIdentification.addDimensionId(...) methods. Unknown identifiers are silently ignored.

If more than one dimension is found for the given identifiers, then a warning is emitted and this method returns the first dimension matching the given identifiers. If no dimension is found, API.NONE is returned.

Specified by:
getAPIForDimension in interface MultidimensionalImageStore
Parameters:
identifiers - The identifiers of the dimension to query.
Returns:
The API assigned to the given dimension, or DimensionSlice.API.NONE if none.
Since:
3.15
See Also:
DimensionSet.getAPI(Object[])

getAPIForDimensions

public Set<DimensionSlice.API> getAPIForDimensions()
Returns the set of APIs for which at least one dimension has identifiers. This is typically an empty set until the following code is invoked at least once:
getDimensionForAPI(...).addDimensionId(...);

Specified by:
getAPIForDimensions in interface MultidimensionalImageStore
Returns:
The API for which at least one dimension has identifiers.
Since:
3.15
See Also:
DimensionSet.getAPIs()

getAggregatedFiles

public List<URI> getAggregatedFiles(int imageIndex)
                             throws IOException
Returns the URIs to the aggregated files, or null if none. This information applies mostly to NcML files, which are XML files listing many NetCDF files to be aggregated as if they were a single dataset. The method returns the individual files that compose such aggregation.

Specified by:
getAggregatedFiles in interface AggregatedImageStore
Parameters:
imageIndex - The index of the variable for which to get the aggregated files.
Returns:
The individual files which are aggregated, or null if none.
Throws:
IOException - If an error occurred while building the list of files.
Since:
3.16
See Also:
NetcdfDataset.getAggregation()

getImageNames

public List<String> getImageNames()
                           throws IOException
Returns the names of the variables to be read. The first name is assigned to the image at index 0, the second name to the image at index 1, etc. In other words a call to read(imageIndex) will read the variable named variables.get(imageIndex) where variables is the list returned by this method.

The sequence of variables to be read can be changed by a call to setImageNames(String[]).

Specified by:
getImageNames in interface NamedImageStore
Returns:
The names of the variables to be read.
Throws:
IOException - if the NetCDF file can not be read.
See Also:
NetcdfFile.getVariables()

setImageNames

public void setImageNames(String... names)
                   throws IOException
Sets the name of the variables to be read in a NetCDF file. The first name is assigned to image index 0, the second name to image index 1, etc.

Special cases:

Specified by:
setImageNames in interface NamedImageStore
Parameters:
names - The set of variables to be assigned to image index, or null for all variables declared in the NetCDF file.
Throws:
IOException - if the NetCDF file can not be read.

getNumImages

public int getNumImages(boolean allowSearch)
                 throws IllegalStateException,
                        IOException
Returns the number of images available from the current input source. By default, this method returns the number of variables since each variable is considered as an image. However if the IMAGES API has been assigned to a dimension, then this method returns the number of slices in that dimension.

Overrides:
getNumImages in class SpatialImageReader
Parameters:
allowSearch - If true, the number of images will be returned even if a search is required.
Returns:
The number of images, or -1 if allowSearch is false and a search would be required.
Throws:
IllegalStateException - if the input source has not been set.
IOException - if an error occurs reading the information from the input source.

getBandNames

public List<String> getBandNames(int imageIndex)
                          throws IOException
Returns the names of the bands for the given image, or null if none. By default, this method returns null for every image index. Non-null values can be specified with calls to the setBandNames(int, String[]) method.

Specified by:
getBandNames in interface NamedImageStore
Parameters:
imageIndex - Index of the image for which to get the band names.
Returns:
The variable names of the bands for the given image, or null if the bands for the given image are unnamed.
Throws:
IOException - if the NetCDF file can not be read.
Since:
3.11

setBandNames

public void setBandNames(int imageIndex,
                         String... names)
                  throws IOException
Sets the names of the bands for the given image, or null for removing any naming. This method is useful for merging different variables as different bands in the image to be read, typically because each band is a vector component. See the NamedImageStore javadoc for an example.

Specified by:
setBandNames in interface NamedImageStore
Parameters:
imageIndex - Index of the image for which to set the band names.
names - The variable names of the bands for the given image, or null for removing any naming.
Throws:
IOException - if the NetCDF file can not be read.
Since:
3.11

getNumBands

public int getNumBands(int imageIndex)
                throws IOException
Returns the number of bands available for the image identified by the given index. The default implementation returns the value of the first of the following conditions which is hold:

  1. If the bands at the give image index have been assigned to variable names, returns the number of assigned variables.
  2. Otherwise if the bands API has been assigned to a dimension, return the dimension length of the variable identified by the given image index.
  3. Otherwise the default number of bands is 1.

Overrides:
getNumBands in class SpatialImageReader
Parameters:
imageIndex - The image index.
Returns:
The number of bands available.
Throws:
IOException - if an error occurs reading the information from the input source.

getWidth

public int getWidth(int imageIndex)
             throws IOException
Returns the image width.

Specified by:
getWidth in class ImageReader
Throws:
IOException - If an error occurred while reading the NetCDF file.
See Also:
Variable.getDimension(int)

getHeight

public int getHeight(int imageIndex)
              throws IOException
Returns the image height.

Specified by:
getHeight in class ImageReader
Throws:
IOException - If an error occurred while reading the NetCDF file.
See Also:
Variable.getDimension(int)

getGridEnvelope

public GridEnvelope getGridEnvelope(int imageIndex)
                             throws IOException
Returns the grid envelope in the image identified by the given index.

Overrides:
getGridEnvelope in class SpatialImageReader
Parameters:
imageIndex - The image index.
Returns:
The grid envelope for the image at the given index.
Throws:
IOException - if an error occurs reading the information from the input source.
Since:
3.19
See Also:
Variable.getDimension(int)

getDimension

public int getDimension(int imageIndex)
                 throws IOException
Returns the number of dimensions in the image identified by the given index. In the case of NetCDF files, this is the rank of the variable associated to the given image index.

Overrides:
getDimension in class SpatialImageReader
Parameters:
imageIndex - The image index.
Returns:
The number of dimension for the image at the given index.
Throws:
IOException - if an error occurs reading the information from the input source.
See Also:
Variable.getRank()

createMetadata

protected SpatialMetadata createMetadata(int imageIndex)
                                  throws IOException
Creates a new stream or image metadata. This method is invoked automatically when first needed.

Overrides:
createMetadata in class SpatialImageReader
Parameters:
imageIndex - -1 for stream metadata, or the image index for image metadata.
Returns:
The requested metadata, or null if none.
Throws:
IOException - If an error occurred while reading metadata.
See Also:
CoordSysBuilder.factory(NetcdfDataset, CancelTask)

getRawDataType

protected int getRawDataType(int imageIndex)
                      throws IOException
Returns the data type which most closely represents the "raw" internal data of the image. In the case of NetCDF files, The raw type is determined from the value returned by the VariableIF.getDataType() method on the variable identified by the given index. The NetCDF DataType is then mapped to one of the DataBuffer constants.

Overrides:
getRawDataType in class SpatialImageReader
Parameters:
imageIndex - The index of the image to be queried.
Returns:
The data type, or DataBuffer.TYPE_UNDEFINED if unknown.
Throws:
IOException - If an error occurred while reading the NetCDF file.
See Also:
SpatialImageReader.getImageType(int, ImageReadParam, SampleConverter[]), SampleConversionType.SHIFT_SIGNED_INTEGERS

prepareVariable

protected boolean prepareVariable(int imageIndex)
                           throws IOException
Ensures that data are loaded in the NetCDF variable. If data are already loaded, then this method does nothing.

This method is invoked automatically before any operation requiring the NetCDF variable, including (but not limited to):

Parameters:
imageIndex - The image index.
Returns:
true if the variable changed as a result of this call, or false if the current value is already appropriate.
Throws:
IndexOutOfBoundsException - if the specified index is outside the expected range.
IllegalStateException - If ImageReader.input is not set.
IOException - If an error occurred while reading the NetCDF file.

findVariable

protected Variable findVariable(String name)
                         throws IOException
Returns the variable of the given name. This method is similar to NetcdfFile.findVariable(String) except that the search is case-insensitive and an exception is thrown if no variable has been found for the given name.

Subclasses can override this method if they want this NetcdfImageReader to use a different variable for the given name.

Parameters:
name - The name of the variable to search.
Returns:
The variable for the given name.
Throws:
IOException - If an error occurred while reading the NetCDF file.
See Also:
NetcdfFile.findVariable(String)

read

public BufferedImage read(int imageIndex,
                          ImageReadParam param)
                   throws IOException
Creates an image from the specified parameters.

Specified by:
read in class ImageReader
Throws:
IOException - If an error occurred while reading the NetCDF file.

readRaster

public Raster readRaster(int imageIndex,
                         ImageReadParam param)
                  throws IOException
Creates a raster from the specified parameters. This method is a bit closer to the actual NetCDF model than the read(int, ImageReadParam), because NetCDF file usually don't provide color information.

Overrides:
readRaster in class ImageReader
Throws:
IOException - If an error occurred while reading the NetCDF file.
Since:
3.20
TODO:
Current implementation delegates to read(int, param). Futures versions should do a more efficient work.

canReadRaster

public boolean canReadRaster()
Returns true since this class supports calls to readRaster(int, ImageReadParam).

Overrides:
canReadRaster in class ImageReader
Since:
3.20

isCancel

public boolean isCancel()
Invoked by the NetCDF library during read operation in order to check if the task has been canceled. Users should not invoke this method directly.

Specified by:
isCancel in interface CancelTask
Returns:
true if abort has been requested.

setError

public void setError(String message)
Invoked by the NetCDF library when an error occurred during the read operation. Users should not invoke this method directly.

Specified by:
setError in interface CancelTask
Parameters:
message - An error message to report.

close

protected void close()
              throws IOException
Closes the NetCDF file.

Overrides:
close in class FileImageReader
Throws:
IOException - If an error occurred while accessing the NetCDF file.
See Also:
StreamImageReader.closeOnReset

reset

public void reset()
Restores the ImageReader to its initial state. This method removes the input, the locale, all listeners and any DimensionSlice.API.

Overrides:
reset in class ImageReader


Copyright © 2009-2013 Geotoolkit.org. All Rights Reserved.