Class TLcdNetCDFModelDecoder
- All Implemented Interfaces:
ILcdInputStreamFactoryCapable,ILcdDataSourceModelDecoder,ILcdModelDecoder,ILcdStatusSource
- NetCDF CF (Climate & Forecast) conventions.
- WRF (The Weather Research & Forecasting Model) NetCDF.
Input files
| File | Required | Entry point | Description |
|---|---|---|---|
| *.nc, *.netcdf | X | X | The NetCDF file |
| *.xml | X | NcML File | |
| *.grb, *.grib, *.dat, *.grb2, *.grib2 | X | GRIB File | |
| *.hdf, *.h5, *.he5, *.hdf5 | X | X | HDF5 File |
Supported file transfer protocols
- This model decoder decodes data from a file system.
Caching
This model decoder will generate certain cache files when decoding a source (e.g. GRIB index files).
If the default directory for these cache files needs to be changed, it can be done by setting the system property com.luciad.netcdf.cachedir.
Setting this property prevents issues with creating cache files in case the default cache directory is non-writable.
The system property can be set by providing it as a VM argument, e.g. -Dcom.luciad.netcdf.cachedir=<a-valid-path>.
The directory provided in the system property will be created if it is not available.
Model structure
- This model decoder creates a model for every NetCDF coverage variable.
- If the input NetCDF file has more than one coverage, the resulting model is an
ILcdModelTreeNode. - A multi variable NetCDF file can also be queried for specific coverages by using a file:// URI with query parameters.
- All models returned by this model decoder implement
ILcd2DBoundsIndexedModel.
Model descriptor
- All models returned by this model decoder have a model descriptor with
TLcdNetCDFModelDescriptor#TYPE_NAMEas type name (for NetCDF files) or withTLcdNetCDFModelDescriptor#TYPE_NAME_GRIB(for Grib files). - All leaf models returned by this model decoder have a
TLcdNetCDFModelDescriptor. - The decoded variable name is the display name of the model descriptor.
Model reference
- A model has a reference which implements either
ILcdGeodeticReferenceorILcdGridReference.
Model elements
- The leaf model is a
TLcdNetCDFFilteredModelinstance. - The leaf model elements implement
ILcdDataObjectand have a property that contains anALcdImage. See alsoTLcdNetCDFFilteredModelDataTypes.
TLcdNetCDFFilteredModel for more information.
Sample code
Example: Decoding a source
String source = "Data/NetCDF/cloud_cover.nc";
// decode the model
TLcdNetCDFModelDecoder decoder = new TLcdNetCDFModelDecoder();
ILcdModel model = decoder.decode(source);
Example: Decode a specific set of coverages
You can either use a string which includes query parameters TLcdNetCDFModelDecoder decoder = new TLcdNetCDFModelDecoder();
String source = "Data/NetCDF/wind_u.nc";
//Use a query parameter to indicate that only the U-component should be decoded
ILcdModel model = decoder.decode(source + "?variable=u-component_of_wind_isobaric");
TLcdNetCDFModelDecoder decoder = new TLcdNetCDFModelDecoder();
String source = "Data/NetCDF/wind_u.nc";
List<ILcdDataSource> allDataSources = decoder.discoverDataSources(source);
//Filter the available data sources
List<TLcdNetCDFDataSource> filteredDataSources =
allDataSources.stream()
.filter(dataSource -> dataSource instanceof TLcdNetCDFDataSource)
.map(dataSource -> (TLcdNetCDFDataSource) dataSource)
.filter(dataSource -> dataSource.getName().toLowerCase().contains("u-component"))
.collect(Collectors.toList());
//Only pass the data sources in which we are interested to the model decoder
ILcdModel model = decoder.decodeSource(new TLcdNetCDFMultiBandDataSource(filteredDataSources));
Example: Retrieve measurements
//Decode the model
List<TLcdISO19103Measure> measurementsToReturn = new ArrayList<>();
String source = "Data/NetCDF/cloud_cover.nc";
TLcdNetCDFModelDecoder decoder = new TLcdNetCDFModelDecoder();
ILcd2DBoundsIndexedModel model = (ILcd2DBoundsIndexedModel) decoder.decode(source);
//Create an ALcdMeasureProvider by using the ILcdModelMeasureProviderFactory instances registered as service
Iterator<ILcdModelMeasureProviderFactory> iterator = TLcdServiceLoader.getInstance(ILcdModelMeasureProviderFactory.class).iterator();
ALcdMeasureProvider measureProvider = null;
while (iterator.hasNext() && measureProvider == null) {
ILcdModelMeasureProviderFactory factory = iterator.next();
measureProvider = factory.createMeasureProvider(model);
}
//Query the ALcdMeasureProvider for the measurements at a certain location
if (measureProvider != null) {
ILcdModelReference modelReference = model.getModelReference();
ILcdPoint center = model.getBounds().getCenter();
ALcdMeasureProvider.Parameters params = ALcdMeasureProvider.Parameters.newBuilder().build();
TLcdISO19103Measure[] measurements = measureProvider.retrieveMeasuresAt(center, modelReference, params);
for (TLcdISO19103Measure measurement : measurements) {
//do something with the measurement
System.out.println("measurement = " + measurement);
}
}
Example: filter a NetCDF model
String source = "Data/NetCDF/cloud_cover.nc";
TLcdNetCDFModelDecoder decoder = new TLcdNetCDFModelDecoder();
ILcdModel model = decoder.decode(source);
if (model instanceof ILcdMultiDimensionalModel) {
// get the time axis if you don't have it already
TLcdDimensionAxis<Date> timeAxis =
((ILcdMultiDimensional) model).getDimensions()
.stream()
.map(ILcdDimension::getAxis)
.filter(axis -> axis.getType().equals(Date.class))
.map(axis -> (TLcdDimensionAxis<Date>) axis)
.findFirst()
.orElse(null);
Date startDate = ((ILcdMultiDimensionalModel) model).getDimensions()
.stream()
.filter(dimension -> dimension.getAxis() == timeAxis)
.map(ILcdDimension::getUnionOfValues)
.map(interval -> (TLcdDimensionInterval<Date>) interval)
.map(TLcdDimensionInterval::getMin)
.findFirst()
.orElse(null);
// create a filter for a specific date
TLcdDimensionFilter filter = TLcdDimensionFilter
.newBuilder()
.filterDimension(timeAxis, TLcdDimensionInterval.createSingleValue(Date.class, startDate))
.build();
// apply the filter within a write lock
try (TLcdLockUtil.Lock lock = TLcdLockUtil.writeLock(model)) {
((ILcdMultiDimensionalModel) model).applyDimensionFilter(filter, ILcdModel.FIRE_LATER);
} finally {
// fire model changes outside lock
model.fireCollectedModelChanges();
}
}
Thread safety
- The decoded models are thread-safe for read access when taking a
read lock.
- Since:
- 2015.0
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumDetermines when a multi-band image should be created. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddStatusListener(ILcdStatusListener aListener) Registers the given listener so it will receive status events from this source.booleancanDecodeSource(ILcdDataSource aDataSource) Checks whether this model decoder can decode the data source(s), identified by the passedILcdDataSource.booleancanDecodeSource(String aSource) Checks whether this model decoder can decode the specified data source.Creates a new model from the given data source.decodeModelMetadata(ILcdDataSource aDataSource) Decodes the model metadata of a NetCDF source.decodeSource(ILcdDataSource aDataSource) Creates a new model from the given data source.discoverDataSources(String aSource) Fetch the data sources from the given NetCDF file path.Returns a short, displayable name for the format that is decoded by thisILcdModelDecoder.Returns the input stream factory that is used.Returns when multi-band images are created.booleanReturns whether this decoder calculates a min and max value for theALcdBandSemanticsthat is set on the model element.voidremoveStatusListener(ILcdStatusListener aListener) Removes the specified listener so it is no longer notified.voidsetCalculateMinMaxValue(boolean aCalculateMinMaxValue) Configures whether this decoder calculates a min and max value for theALcdBandSemanticsthat is set on the model element.voidsetInputStreamFactory(ILcdInputStreamFactory aInputStreamFactory) Sets the input stream factory to be used.voidsetMultiBandImageCreation(TLcdNetCDFModelDecoder.MultiBandImageCreation aMultiValuedRasterCreation) Configures the creation of multi-band images.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface com.luciad.model.ILcdModelDecoder
decodeModelMetadata
-
Constructor Details
-
TLcdNetCDFModelDecoder
public TLcdNetCDFModelDecoder()Create a new decoder instance.
-
-
Method Details
-
getMultiBandImageCreation
Returns when multi-band images are created. Multi-band images combine related models, such as the x and y components of a wind measurement. They are typically visualized with a grid of icons. -
setMultiBandImageCreation
public void setMultiBandImageCreation(TLcdNetCDFModelDecoder.MultiBandImageCreation aMultiValuedRasterCreation) Configures the creation of multi-band images. Multi-band images combine related datasets, such as the x and y components of a wind measurement. They are typically visualized with a grid of icons.
When loading GRIB 1 files, setting this flag to
AUTOwill also make sure that thedecodemethod looks for other related GRIB files next to the one being decoded. For example, when passing a GRIB file that only contains 'wind U' data, it will also look for a file that contains 'Wind V' data. This automatic combining is based on a heuristic that assumes that the GRIB parameter ID is part of the file name.In case setting this flag to
AUTOfails to automatically create multi-band images, it is possible to combine them manually. This can be done by passing aTLcdNetCDFMultiBandDataSourceto thedecodeSourcemethod. -
setCalculateMinMaxValue
public void setCalculateMinMaxValue(boolean aCalculateMinMaxValue) Configures whether this decoder calculates a min and max value for the
ALcdBandSemanticsthat is set on the model element.By default, this is true.
Note however that the min and max values are only calculated on a small part of the model (to avoid reading the entire model in memory). This may lead to values that are incorrect. When using functionality that depends on the correctness of these values (for example image processing), it may be more desirable to not calculate these values at all.
- Parameters:
aCalculateMinMaxValue- whether to calculate a min and max value.- Since:
- 2025.0.05
-
isCalculateMinMaxValue
public boolean isCalculateMinMaxValue()Returns whether this decoder calculates a min and max value for the
ALcdBandSemanticsthat is set on the model element.- Returns:
- whether this decoder calculates a min and max value for the
ALcdBandSemanticsthat is set on the model element. - Since:
- 2025.0.05
- See Also:
-
getDisplayName
Description copied from interface:ILcdModelDecoderReturns a short, displayable name for the format that is decoded by thisILcdModelDecoder.- Specified by:
getDisplayNamein interfaceILcdModelDecoder- Returns:
- the displayable name of this
ILcdModelDecoder.
-
canDecodeSource
Description copied from interface:ILcdModelDecoderChecks whether this model decoder can decode the specified data source. It is acceptable for this method to returntruefor a source name whiledecodethrows an exception for that same source name.For performance reasons, we strongly recommend that this will only be a simple test. For example: check the file extension of a file, but not that the file exists or contains expected content.
- Specified by:
canDecodeSourcein interfaceILcdModelDecoder- Parameters:
aSource- the data source to be verified; typically a file name or a URL.- Returns:
trueif this decoder can likely decode the data specified by the source name,falseotherwise.- See Also:
-
discoverDataSources
Fetch the data sources from the given NetCDF file path.
The data sources are either
TLcdNetCDFDataSourceorTLcdNetCDFMultiBandDataSourceinstances. Data sources are combined in aTLcdNetCDFMultiBandDataSourceif they are related. To only get single-band sources, set the multi-band image creation of this decoder toTLcdNetCDFModelDecoder.MultiBandImageCreation.NEVERusing thesetMultiBandImageCreation(com.luciad.format.netcdf.TLcdNetCDFModelDecoder.MultiBandImageCreation)methodTo identify the type of data that is represented by a
TLcdNetCDFDataSourceinstance, you can retrieve the full name of the NetCDF variable using theTLcdNetCDFDataSource.getName()method.To identify the type of data that is represented by a
TLcdNetCDFMultiBandDataSourceinstance, you can retrieve data sources that are part of the multi-band source by using theTLcdNetCDFMultiBandDataSource.getDataSources()method.- Specified by:
discoverDataSourcesin interfaceILcdModelDecoder- Parameters:
aSource- a path to a NetCDF file.- Returns:
- A list of data sources available in the given source file. May be empty but not
null. Note that not all data sources returned may be supported by this decoder. - Throws:
IOException- if the decoder can't decode the source file.
-
canDecodeSource
Checks whether this model decoder can decode the data source(s), identified by the passed
ILcdDataSource.For performance reasons, we strongly recommend that this will only be a simple test. For example: check the instance class of
aDataSource, or check the file extension if it is aTLcdDataSource.The default implementation of this method will check if the given
ILcdDataSourceis aTLcdDataSource. If not, this method returns false. Otherwise, it delegates the source to theILcdModelDecoder.canDecodeSource(String)method.Supported data sources are:
- Specified by:
canDecodeSourcein interfaceILcdModelDecoder- Parameters:
aDataSource- theILcdModelSourceto be verified.- Returns:
trueif this decoder can likely decode the data specified byaDataSource,falseotherwise.- See Also:
-
decode
Description copied from interface:ILcdModelDecoderCreates a new model from the given data source.- Specified by:
decodein interfaceILcdModelDecoder- Parameters:
aSource- the data source to be decoded; typically a file name or a URL.- Returns:
- A model containing the decoded data. While
nullis allowed, implementors are advised to throw an error instead. - Throws:
IOException- for any exceptions caused by IO problems or invalid data. Since decoding invalid data almost always results in RunTimeExceptions (NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, ...) on unexpected places, implementations are advised to catch RuntimeExceptions in their decode() method, and wrap them into an IOException, as illustrated in the code snippet below.public ILcdModel decode( String aSourceName ) throws IOException { try (InputStream input = fInputStreamFactory.createInputStream(aSourceName)) { // Perform decoding ... } catch (RuntimeException e) { throw new IOException(e); } }- See Also:
-
decodeModelMetadata
Decodes the model metadata of a NetCDF source.Supported data sources are:
For multi-band sources, one of the sources is used as the entry point source of the model metadata. All other sources will be set as the supporting sources of the model metadata.
- Specified by:
decodeModelMetadatain interfaceILcdModelDecoder- Parameters:
aDataSource- the data source to be decoded.- Returns:
- a
TLcdModelMetadatainstance containing the model metadata of the NetCDF model of the source. - Throws:
IOException- If the given source cannot be decoded for some reason.- See Also:
-
decodeSource
Creates a new model from the given data source.
By default, this method:
- Throws a
NullPointerExceptionwhen anulldata source is passed. - Delegates to the
ILcdModelDecoder.decode(String)method when aTLcdDataSourceis passed. - Throws an IOException in other case.
Supported data sources are:
- Specified by:
decodeSourcein interfaceILcdModelDecoder- Parameters:
aDataSource- theILcdDataSourceto be decoded.- Returns:
- a model containing the decoded data. While
nullis allowed, implementors are advised to throw an error instead. - Throws:
IOException- for any exceptions caused by IO problems or invalid data. Since decoding invalid data almost always results in RunTimeExceptions (NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, ...) on unexpected places, implementations are advised to catch RuntimeExceptions in their decode() method, and wrap them into an IOException, as illustrated in the code snippet below.public ILcdModel decodeSource(ILcdDataSource aDataSource) throws IOException { try { // Perform decoding ... } catch (RuntimeException e) { throw new IOException(e); } }- See Also:
- Throws a
-
addStatusListener
Description copied from interface:ILcdStatusSourceRegisters the given listener so it will receive status events from this source.
In case you need to register a listener which keeps a reference to an object with a shorter life-time than this status source, you can use a
ALcdWeakStatusListenerinstance as status listener.- Specified by:
addStatusListenerin interfaceILcdStatusSource- Parameters:
aListener- The listener to be notified when the status has changed.
-
removeStatusListener
Description copied from interface:ILcdStatusSourceRemoves the specified listener so it is no longer notified.- Specified by:
removeStatusListenerin interfaceILcdStatusSource- Parameters:
aListener- The listener to remove.
-
setInputStreamFactory
Sets the input stream factory to be used. When the input stream factory is set,- This model decoder reads all the data from the created stream and stores it in a temporary file. The temporary
file is created by
File.createTempFile(String, String)in the OS temporary files directory. - The temporary file is used as the NetCDF source file.
- The temporary file is deleted either when the root NetCDF model is disposed or JVM terminates normally.
- Specified by:
setInputStreamFactoryin interfaceILcdInputStreamFactoryCapable- Parameters:
aInputStreamFactory- the input stream factory to be used.- See Also:
- This model decoder reads all the data from the created stream and stores it in a temporary file. The temporary
file is created by
-
getInputStreamFactory
Description copied from interface:ILcdInputStreamFactoryCapableReturns the input stream factory that is used.- Specified by:
getInputStreamFactoryin interfaceILcdInputStreamFactoryCapable- Returns:
- the input stream factory that is used.
-